Merge pull request #156 from Gimanh/fix/issues

fix: initial user
This commit is contained in:
Nikolai Giman
2026-11-27 17:46:12 +01:00
committed by GitHub
23 changed files with 230 additions and 22 deletions
+2
View File
@@ -228,6 +228,8 @@ For deployment instructions, environment variables, HTTPS configuration, updates
> Production deployments should use persistent volumes, HTTPS, regular database backups, and securely generated secrets.
> **First account.** A new installation creates the account `user` with the password you set in `INITIAL_USER_PASSWORD`; there is no built-in password. Installations created before this variable existed may still have the account `user` / `test@mail.dest` with the old public password `user1!#Q` — see [how to check and disable it](https://taskview.tech/docs/getting-started/installation#check-an-older-installation-for-the-preinstalled-password).
## Repository structure
TaskView is maintained as a monorepo. Product packages share a single version.
+3
View File
@@ -28,6 +28,9 @@ JWT_ALG=HS256
# (default 10, 0 turns the limit off). An account is paused at 5x this number from all addresses
# together, an address at 10x across all accounts
# LOGIN_ATTEMPT_LIMIT=10
# Password of the first account (login: user), 6 to 128 characters. Read by the migration
# only when the database is created; if empty, no account is created
# INITIAL_USER_PASSWORD=
# Let users delete their own account (default false: on a company install an admin removes accounts)
# ALLOW_ACCOUNT_DELETION=false
+4 -1
View File
@@ -19,4 +19,7 @@ SMTP_FROM_EMAIL="smtp"
CORS_ALLOWED_ORIGINS="http://localhost:5173,http://127.0.0.1:5173,http://localhost:3000,http://localhost:8888,http://127.0.0.1:3000,http://127.0.0.1:8888"
# Constant value
APP_URL="https://taskview.handscream.com"
APP_URL="https://taskview.handscream.com"
# Test stand only: the first account keeps the password the test fixtures sign in with
INITIAL_USER_PASSWORD="user1!#Q"
+37
View File
@@ -0,0 +1,37 @@
import { hashSync } from 'bcryptjs';
import type { CreateInitialUserArgs, InitialUserPasswordCheck } from './initial-user.types';
/**
* The account a fresh installation starts with. Its password comes from the
* environment, so no credentials are shared between installations.
*/
export class InitialUser {
static readonly ENV_NAME = 'INITIAL_USER_PASSWORD';
static readonly LOGIN = 'user';
static readonly EMAIL = 'test@mail.dest';
static readonly PASSWORD_MIN_LENGTH = 6;
static readonly PASSWORD_MAX_LENGTH = 128;
static checkPassword(raw: string | undefined): InitialUserPasswordCheck {
if (raw === undefined || raw === '') return { status: 'missing' };
if (raw !== raw.trim()) {
return { status: 'invalid', reason: `${InitialUser.ENV_NAME} must not start or end with whitespace` };
}
if (raw.length < InitialUser.PASSWORD_MIN_LENGTH || raw.length > InitialUser.PASSWORD_MAX_LENGTH) {
return {
status: 'invalid',
reason: `${InitialUser.ENV_NAME} must be ${InitialUser.PASSWORD_MIN_LENGTH} to ${InitialUser.PASSWORD_MAX_LENGTH} characters long`,
};
}
return { status: 'ok', password: raw };
}
static async create(args: CreateInitialUserArgs): Promise<void> {
await args.client.query(
`INSERT INTO tv_auth.users (login, email, password, block, confirm_email_code, remind_password_code, remember_token)
VALUES ($1, $2, $3, 0, null, null, null);`,
[InitialUser.LOGIN, InitialUser.EMAIL, hashSync(args.password, 10)]
);
}
}
@@ -0,0 +1,43 @@
import { compareSync } from 'bcryptjs';
import { describe, expect, it, vi } from 'vitest';
import { InitialUser } from '../InitialUser';
describe('InitialUser.checkPassword', () => {
it('reports a missing password when the variable is unset or empty', () => {
expect(InitialUser.checkPassword(undefined)).toEqual({ status: 'missing' });
expect(InitialUser.checkPassword('')).toEqual({ status: 'missing' });
});
it('rejects a password shorter than the minimum', () => {
expect(InitialUser.checkPassword('12345').status).toBe('invalid');
});
it('rejects a password longer than the maximum', () => {
expect(InitialUser.checkPassword('a'.repeat(129)).status).toBe('invalid');
});
it('rejects a password wrapped in whitespace', () => {
expect(InitialUser.checkPassword(' secret-pass ').status).toBe('invalid');
expect(InitialUser.checkPassword(' ').status).toBe('invalid');
});
it('accepts a password within the limits', () => {
expect(InitialUser.checkPassword('s3cret-pass')).toEqual({ status: 'ok', password: 's3cret-pass' });
});
});
describe('InitialUser.create', () => {
it('inserts the account with a hash of the given password', async () => {
const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 1 });
await InitialUser.create({ client: { query }, password: 's3cret-pass' });
expect(query).toHaveBeenCalledTimes(1);
const [sql, params] = query.mock.calls[0];
expect(sql).toContain('INSERT INTO tv_auth.users');
expect(params[0]).toBe('user');
expect(params[1]).toBe('test@mail.dest');
expect(params[2]).not.toBe('s3cret-pass');
expect(compareSync('s3cret-pass', params[2])).toBe(true);
});
});
+15
View File
@@ -0,0 +1,15 @@
import type { QueryResult } from 'pg';
export type InitialUserQueryRunner = {
query: (text: string, params?: unknown[]) => Promise<QueryResult>;
};
export type InitialUserPasswordCheck =
| { status: 'missing' }
| { status: 'invalid'; reason: string }
| { status: 'ok'; password: string };
export type CreateInitialUserArgs = {
client: InitialUserQueryRunner;
password: string;
};
+13
View File
@@ -1,6 +1,7 @@
import { config } from 'dotenv';
import fs from 'fs/promises';
import { join, resolve } from 'path';
import { InitialUser } from './InitialUser';
config();
@@ -185,8 +186,20 @@ async function migrate() {
await disconnectOthers();
if (process.argv.includes('--create')) {
const initialPassword = InitialUser.checkPassword(process.env[InitialUser.ENV_NAME]);
if (initialPassword.status === 'invalid') {
throw new Error(initialPassword.reason);
}
console.log('\x1b[32m%s\x1b[0m', 'Start creating DB structure');
await execScripts(createDbData.scripts);
if (initialPassword.status === 'ok') {
await InitialUser.create({ client, password: initialPassword.password });
console.log('\x1b[32m%s\x1b[0m', `Initial account "${InitialUser.LOGIN}" created`);
} else {
console.warn(`${InitialUser.ENV_NAME} is not set: no initial account was created`);
}
console.log('\x1b[32m%s\x1b[0m', 'End creating DB structure');
}
await client.query('COMMIT');
@@ -41,9 +41,3 @@ VALUES ((select id from tv_auth.roles where name = 'app_user'),
INSERT INTO tv_auth.group_to_roles (group_id, role_id)
VALUES ((select id from tv_auth.groups where name = 'app_users'),
(select id from tv_auth.roles where name = 'app_user'));
INSERT INTO tv_auth.users (login, email, password, block, confirm_email_code, remind_password_code, remember_token)
VALUES ('user', 'test@mail.dest', '$2y$10$q8SLauZ0Syz9aEFdiq0i8.jIlafLj5T0ujXYD7RmRzyNkZ2hR7uhO', 0,
'40390b741a906a45119390922eaaff1d', null, null);
+44 -6
View File
@@ -126,6 +126,11 @@ services:
condition: service_healthy
env_file:
- ./.env.taskview
environment:
# CHANGE THIS before the first start: password of the first account (login: user).
# 6 to 128 characters. It is read only once, when the database is created.
# If left empty, no account is created.
INITIAL_USER_PASSWORD: ""
networks: [backend]
taskview-api-server:
@@ -212,26 +217,32 @@ Without `TASKVIEW_API_URL`, click the **server settings** section on the login p
http://localhost:1725
```
### Log in with the default user
### Log in with the first account
The database migration creates a default user so you can log in right away:
When the database is created, the migration adds the first account with the password you set in `INITIAL_USER_PASSWORD`:
- **Login:** `user`
- **Password:** `user1!#Q`
- **Password:** the value of `INITIAL_USER_PASSWORD` you set on the `migration` service in `docker-compose.yml`
Use these credentials to verify that everything is working - check that the UI loads, you can create a project, add tasks, etc.
::callout{icon="i-lucide-alert-triangle" color="warning"}
`INITIAL_USER_PASSWORD` is read only once, when the database is created. If it is empty at that moment, no account is created; a value that is shorter than 6 or longer than 128 characters stops the migration with an error. Changing the variable later does not change the password.
::
::callout{icon="i-lucide-alert-triangle" color="error"}
**Important:** The default credentials are publicly known — anyone who has read this page can sign in to a fresh installation. Claim the account right after the first login.
**Installed before `INITIAL_USER_PASSWORD` existed?** Older versions created this account with a fixed, publicly known password (`user1!#Q`). Updating does not change existing accounts. See [Check an older installation](#check-an-older-installation-for-the-preinstalled-password) below.
::
### Claim the default account
Make the default account your own — no SMTP or database access needed:
1. Log in with the default credentials
Until you do, the app keeps a reminder on screen with a **Change now** button that opens Account settings.
1. Log in as `user` with your `INITIAL_USER_PASSWORD`
2. Open **Account settings** — the highlighted **Login and email** card is shown at the top (it is visible only to the default user)
3. Set your own login, email and a strong password, confirm with the current password (`user1!#Q`), and click **Save and sign out**
3. Set your own login, email and a strong password, confirm with the current password, and click **Save and sign out**
4. Sign in again with your new login and password
![The Login and email card in Account settings for claiming the default account](/taskview/change-def-account.png)
@@ -242,6 +253,33 @@ Your organizations, projects and permissions are preserved. Once the email is ch
Changing the password later requires a confirmation code sent by email. If your installation has no SMTP, set `PASSWORD_CHANGE_CONFIRMATION="password"` in `.env.taskview` so password changes are confirmed with the current password instead. See [Environment Variables](/docs/configuration/environment-variables#authentication).
::
### Check an older installation for the preinstalled password
Installations created before `INITIAL_USER_PASSWORD` existed got the account `user` / `test@mail.dest` with the fixed password `user1!#Q`. That password is public, so anyone who can reach the instance can sign in to the account while it is unchanged. Updating TaskView leaves existing accounts as they are, so check once.
Run this in the directory with your `docker-compose.yml` (adjust the database user and name if yours differ from the examples above). It lists accounts that still have the preinstalled password:
```bash
docker compose exec -T db psql -U taskview_db_user -d taskviewdb <<'SQL'
SELECT id, login, email, block FROM tv_auth.users
WHERE password = '$2y$10$q8SLauZ0Syz9aEFdiq0i8.jIlafLj5T0ujXYD7RmRzyNkZ2hR7uhO';
SQL
```
No rows means there is nothing to do. If a row comes back with `block = 0`, the account is open:
- **You use this account** — claim it as described above (or change its password in Account settings). Its projects and permissions are kept.
- **You do not use it** — disable it:
```bash
docker compose exec -T db psql -U taskview_db_user -d taskviewdb <<'SQL'
UPDATE tv_auth.users SET block = 1, confirm_email_code = NULL
WHERE password = '$2y$10$q8SLauZ0Syz9aEFdiq0i8.jIlafLj5T0ujXYD7RmRzyNkZ2hR7uhO';
SQL
```
A disabled account can no longer sign in, and its open sessions and API tokens stop working. Its data stays in the database.
## Updating
To update TaskView to a new version:
@@ -53,6 +53,7 @@ Unlike everything else on this page, this variable is set on the **web app conta
| `AUTH_LOGIN_METHODS` | No | all enabled | Comma-separated list of login methods to offer: `magic-link`, `password`, `sso`, `social`. Disabled methods disappear from the login page and their API endpoints return 403. The API refuses to start if the list contains a typo or disables every method. |
| `LOGIN_CODE_HOURLY_LIMIT` | No | `5` | Maximum sign-in codes one account can request by email per hour. Each code also stops working after 5 wrong attempts. Must be a positive integer; anything else stops the server at startup. |
| `PASSWORD_CHANGE_CONFIRMATION` | No | `email` | How account password changes are confirmed: `email` — a confirmation code is sent to the user's email (requires SMTP); `password` — the user confirms with their current password (works without SMTP, recommended for installs without a mail server). |
| `INITIAL_USER_PASSWORD` | No | — | Password of the first account (login `user`), 6 to 128 characters. Read by the migration only once, when the database is created; changing it later has no effect. If empty, no account is created. See [Installation](/docs/getting-started/installation#log-in-with-the-first-account). |
| `ALLOW_PUBLIC_REGISTRATION` | No | `true` | Set to `false` to close the instance: strangers can no longer create accounts — the registration endpoint returns 403, and magic-link / social sign-in stop auto-creating users. Emails invited to an organization or project can still sign in and get their account created on first login. |
| `ALLOW_ACCOUNT_DELETION` | No | `false` | Whether users may delete their own account from **Settings**. Off by default: on a company install an admin decides who has access (by removing the member from the organization, or deactivating them over SCIM), and one person must not be able to wipe the projects they created for the team. While off, the **Delete account** button is hidden and the deletion endpoints return 403. Set to `true` on a public instance where people sign up by themselves. Deleting an account also deletes the projects and organizations the user owns. The value must be `true` or `false`; anything else stops the server at startup. |
| `OAUTH_DYNAMIC_REGISTRATION` | No | `false` | Whether AI clients may register themselves as OAuth clients (RFC 7591) when connecting to the [MCP server](/docs/integrations/mcp#oauth-cloud-clients). Off by default: the registration endpoint returns 403 and cloud clients such as ChatGPT or Claude cannot start an OAuth connection. Set to `true` to let them connect. Turning it back off later does not affect apps that are already connected. |
@@ -343,6 +344,9 @@ JWT_SIGN="secret"
ACCESS_LIFE_TIME="3d"
REFRESH_LIFE_TIME="9d"
# Password of the first account (login: user), read once when the database is created
INITIAL_USER_PASSWORD=
# Login methods offered on the login page (unset = all enabled)
#AUTH_LOGIN_METHODS="magic-link,password,sso,social"
# Max sign-in codes one account can request by email per hour
+1 -1
View File
@@ -57,7 +57,7 @@ Requires SMTP. Users click "Forgot password" on the login screen, enter their em
### The default user (self-hosted)
Fresh installations ship a preinstalled user (`user` / `user1!#Q`). That account gets a dedicated **Login and email** card in Account settings to claim it in one step — set your own login, email and password, confirmed by the current password, no SMTP required. See [Installation → Claim the default account](/docs/getting-started/installation#claim-the-default-account).
Fresh installations create a first account with the login `user` and the password set in `INITIAL_USER_PASSWORD`. That account gets a dedicated **Login and email** card in Account settings to claim it in one step — set your own login, email and password, confirmed by the current password, no SMTP required. See [Installation → Claim the default account](/docs/getting-started/installation#claim-the-default-account).
## OAuth providers
+1 -1
View File
@@ -431,7 +431,7 @@ const $axios = axios.create({ baseURL: BASE_URL });
async function login(): Promise<{ access: string; refresh: string }> {
const { data } = await $axios.post('/module/auth/login', {
login: 'test@mail.dest',
password: 'user1!#Q',
password: 'your-password',
});
return data;
}
@@ -8,7 +8,7 @@ const $axios = axios.create({ baseURL: BASE_URL });
async function login(): Promise<{ access: string; refresh: string }> {
const { data } = await $axios.post('/module/auth/login', {
login: 'test@mail.dest',
password: 'user1!#Q',
password: 'your-password',
});
return data;
}
@@ -18,3 +18,6 @@ REFRESH_LIFE_TIME=9d
CORS_ALLOWED_ORIGINS=*
APP_URL=http://localhost:1401
ENCRYPTION_KEY=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
# Test stand only: the first account keeps the password the test fixtures sign in with
INITIAL_USER_PASSWORD="user1!#Q"
+3
View File
@@ -28,6 +28,9 @@ services:
condition: service_healthy
env_file:
- ../../dockers-check/.env.taskview
environment:
# E2E only: the first account keeps the password the fixtures sign in with
INITIAL_USER_PASSWORD: "user1!#Q"
api:
image: gimanhead/taskview-se-api-server:latest
@@ -81,6 +81,7 @@ import DeleteAccountCodeModal from './parts/DeleteAccountCodeModal.vue'
import NotificationSettings from './parts/NotificationSettings.vue'
import PasswordSettings from './parts/PasswordSettings.vue'
import DefaultUserCredentials from './parts/DefaultUserCredentials.vue'
import { DEFAULT_USER_EMAIL } from '@/composables/useDefaultCredentialsReminder'
import SessionsPanel from '@/components/features/sessions/SessionsPanel.vue'
import ApiTokensPanel from '@/components/features/api-tokens/ApiTokensPanel.vue'
import ConnectedAppsPanel from '@/components/features/oauth/ConnectedAppsPanel.vue'
@@ -101,7 +102,7 @@ onMounted(async () => {
})
// Seeded default user on self-hosted installs (migration 0.0.0); backend enforces the same check
const isDefaultUser = computed(() => userStore.email.toLowerCase() === 'test@mail.dest')
const isDefaultUser = computed(() => userStore.email.toLowerCase() === DEFAULT_USER_EMAIL)
function onCodeSendError() {
toast.add({
@@ -0,0 +1,42 @@
import { watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user.store'
export const DEFAULT_USER_EMAIL = 'test@mail.dest'
const REMINDER_TOAST_ID = 'default-credentials-reminder'
export function useDefaultCredentialsReminder() {
const { t } = useI18n()
const toast = useToast()
const router = useRouter()
const userStore = useUserStore()
watch(
() => userStore.email.toLowerCase() === DEFAULT_USER_EMAIL,
(isDefaultUser) => {
if (!isDefaultUser) {
toast.remove(REMINDER_TOAST_ID)
return
}
toast.add({
id: REMINDER_TOAST_ID,
title: t('account.defaultCredsWarning'),
description: t('account.defaultCredsDescription'),
color: 'warning',
icon: 'i-lucide-shield-alert',
duration: 0,
actions: [
{
label: t('account.defaultCredsChange'),
color: 'warning',
onClick: () => {
router.push({ name: 'account' })
},
},
],
})
},
{ immediate: true },
)
}
+2
View File
@@ -49,6 +49,7 @@ import { useTimeTrackingStore } from '@/stores/time-tracking.store'
import { useUiPreferencesStore } from '@/stores/uiPreferences.store'
import { useOnboardingStore } from '@/stores/onboarding.store'
import { useRecentProjects } from '@/composables/useRecentProjects'
import { useDefaultCredentialsReminder } from '@/composables/useDefaultCredentialsReminder'
const { connect: connectCentrifugo } = useCentrifugo()
const { init: initPush } = usePushNotifications()
@@ -64,6 +65,7 @@ const { markProjectUsed } = useRecentProjects()
useWidgetSnapshot()
useWidgetDeepLink()
useDefaultCredentialsReminder()
watch(
() => timeTrackingStore.lastError,
+2 -1
View File
@@ -913,7 +913,8 @@ export default {
passwordCodeCooldown: 'Code wurde bereits gesendet. Versuchen Sie es in einer Minute erneut.',
passwordCodeSendError: 'Code konnte nicht gesendet werden. Versuchen Sie es später erneut.',
defaultCredsTitle: 'Login und E-Mail',
defaultCredsWarning: 'Die Standard-Zugangsdaten sind öffentlich bekannt',
defaultCredsWarning: 'Dieses Konto verwendet noch die anfänglichen Zugangsdaten',
defaultCredsChange: 'Jetzt ändern',
defaultCredsDescription: 'Ihr Konto verwendet die vorinstallierten Zugangsdaten. Legen Sie eigenen Login, E-Mail und Passwort fest — nach dem Speichern müssen Sie sich erneut anmelden.',
newLogin: 'Neuer Login',
newLoginPlaceholder: 'Buchstaben, Ziffern, . _ -',
+2 -1
View File
@@ -927,7 +927,8 @@ export default {
passwordCodeCooldown: 'Code already sent. Try again in a minute.',
passwordCodeSendError: 'Unable to send the code. Try again later.',
defaultCredsTitle: 'Login and email',
defaultCredsWarning: 'The default sign-in credentials are publicly known',
defaultCredsWarning: 'This account still uses the initial sign-in credentials',
defaultCredsChange: 'Change now',
defaultCredsDescription: 'Your account uses the preinstalled credentials. Set your own login, email and password — you will need to sign in again after saving.',
newLogin: 'New login',
newLoginPlaceholder: 'Letters, digits, . _ -',
+2 -1
View File
@@ -913,7 +913,8 @@ export default {
passwordCodeCooldown: 'El código ya fue enviado. Inténtalo de nuevo en un minuto.',
passwordCodeSendError: 'No se pudo enviar el código. Inténtalo más tarde.',
defaultCredsTitle: 'Login y email',
defaultCredsWarning: 'Las credenciales de acceso predeterminadas son de conocimiento público',
defaultCredsWarning: 'Esta cuenta aún usa las credenciales de acceso iniciales',
defaultCredsChange: 'Cambiar ahora',
defaultCredsDescription: 'Tu cuenta usa las credenciales preinstaladas. Establece tu propio login, email y contraseña — tendrás que iniciar sesión de nuevo después de guardar.',
newLogin: 'Nuevo login',
newLoginPlaceholder: 'Letras, dígitos, . _ -',
+2 -1
View File
@@ -926,7 +926,8 @@ export default {
passwordCodeCooldown: 'Código já enviado. Tente novamente em um minuto.',
passwordCodeSendError: 'Não foi possível enviar o código. Tente novamente mais tarde.',
defaultCredsTitle: 'Login e e-mail',
defaultCredsWarning: 'As credenciais de login padrão são conhecidas publicamente',
defaultCredsWarning: 'Esta conta ainda usa as credenciais de login iniciais',
defaultCredsChange: 'Alterar agora',
defaultCredsDescription: 'Sua conta usa as credenciais pré-instaladas. Defina seu próprio login, e-mail e senha — você precisará fazer login novamente após salvar.',
newLogin: 'Novo login',
newLoginPlaceholder: 'Letras, digitos, . _ -',
+2 -1
View File
@@ -893,7 +893,8 @@ export default {
passwordCodeCooldown: 'Код уже отправлен. Повторите через минуту.',
passwordCodeSendError: 'Не удалось отправить код. Попробуйте позже.',
defaultCredsTitle: 'Логин и email',
defaultCredsWarning: 'Стандартные данные для входа общеизвестны',
defaultCredsWarning: 'Учётная запись всё ещё использует начальные данные для входа',
defaultCredsChange: 'Сменить сейчас',
defaultCredsDescription: 'Учётная запись использует стандартные данные. Задайте свои логин, email и пароль — после сохранения потребуется войти заново.',
newLogin: 'Новый логин',
newLoginPlaceholder: 'Буквы, цифры, . _ -',