feat(auth): implement TOTP setup and management
Lint / Lint (Node/Svelte) (push) Successful in 24s
Lint / Lint (Go) (push) Successful in 28s
Lint / Lint (Python) (push) Failing after 14s
Tests / Test (Node/Svelte) (push) Successful in 18s
Tests / Test (Go) (push) Successful in 25s
Tests / Test (Python) (push) Successful in 12s
Lint / Lint (Node/Svelte) (push) Successful in 24s
Lint / Lint (Go) (push) Successful in 28s
Lint / Lint (Python) (push) Failing after 14s
Tests / Test (Node/Svelte) (push) Successful in 18s
Tests / Test (Go) (push) Successful in 25s
Tests / Test (Python) (push) Successful in 12s
- Added TOTP support for two-factor authentication in the auth module. - Introduced new types and interfaces for TOTP setup and token actions in the web UI. - Created backend logic for generating and verifying TOTP secrets and tokens. - Implemented user management features including role assignments and user CRUD operations. - Enhanced UI components for managing users and TOTP settings. - Added styles for optional labels and authentication reset links. - Implemented reset code generation and validation for admin accounts.
This commit is contained in:
1 parent
2f57554154
commit
da97fd4fb1
30 files changed
+2145
-27
No files matched your search
@@ -3,6 +3,22 @@ import crypto from 'node:crypto';
|
||||
const PASSWORD_ITERATIONS = 100000;
|
||||
const PASSWORD_KEY_LENGTH = 32;
|
||||
const PASSWORD_DIGEST = 'sha256';
|
||||
export const RESET_CODE_TTL_MS = 5 * 60 * 1000;
|
||||
export const USER_ROLES = Object.freeze({ SUPERADMIN: 'superadmin', ADMIN: 'admin', USER: 'user' });
|
||||
|
||||
export function normalizeRole(value) {
|
||||
const normalized = String(value ?? '').trim().toLowerCase();
|
||||
return normalized === USER_ROLES.SUPERADMIN || normalized === USER_ROLES.ADMIN ? normalized : USER_ROLES.USER;
|
||||
}
|
||||
|
||||
export function canManageUsers(role) {
|
||||
const normalized = normalizeRole(role);
|
||||
return normalized === USER_ROLES.SUPERADMIN || normalized === USER_ROLES.ADMIN;
|
||||
}
|
||||
|
||||
export function canAssignRole(actorRole, targetRole) {
|
||||
return normalizeRole(actorRole) === USER_ROLES.SUPERADMIN && normalizeRole(targetRole) !== USER_ROLES.SUPERADMIN;
|
||||
}
|
||||
|
||||
export const AUTH_SCHEMA = `
|
||||
CREATE TABLE IF NOT EXISTS auth_users (
|
||||
@@ -10,12 +26,21 @@ CREATE TABLE IF NOT EXISTS auth_users (
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
email TEXT NOT NULL DEFAULT '',
|
||||
password_hash TEXT NOT NULL,
|
||||
role TEXT NOT NULL DEFAULT 'user',
|
||||
totp_secret TEXT NOT NULL DEFAULT '',
|
||||
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
UPDATE auth_users SET role = 'superadmin'
|
||||
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
|
||||
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx ON auth_users (lower(email)) WHERE email <> '';
|
||||
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
@@ -64,6 +89,48 @@ export function hashToken(token) {
|
||||
return crypto.createHash('sha256').update(String(token)).digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and validates the short-lived, one-time code used by the public
|
||||
* "reset admin account" flow. Account deletion stays with the application
|
||||
* because its account table and session policy may differ.
|
||||
*/
|
||||
export class ResetManager {
|
||||
constructor({ ttlMs = RESET_CODE_TTL_MS, log = console.log } = {}) {
|
||||
this.ttlMs = ttlMs;
|
||||
this.log = log;
|
||||
this.code = null;
|
||||
this.expiresAt = 0;
|
||||
}
|
||||
|
||||
request() {
|
||||
this.code = crypto.randomBytes(4).toString('hex').toUpperCase();
|
||||
this.expiresAt = Date.now() + this.ttlMs;
|
||||
this.log(
|
||||
`\n${'='.repeat(50)}\nADMIN RESET CODE: ${this.code}\nExpires in 5 minutes. Enter it on the login page.\n${'='.repeat(50)}\n`,
|
||||
);
|
||||
return this.code;
|
||||
}
|
||||
|
||||
confirm(candidate) {
|
||||
if (!this.code) return false;
|
||||
if (Date.now() > this.expiresAt) {
|
||||
this.code = null;
|
||||
this.expiresAt = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
const normalized = String(candidate ?? '').trim().toUpperCase();
|
||||
const expected = Buffer.from(this.code);
|
||||
const actual = Buffer.from(normalized);
|
||||
const valid = expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
|
||||
if (!valid) return false;
|
||||
|
||||
this.code = null;
|
||||
this.expiresAt = 0;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Persistence-only auth store; cookies, roles, and HTTP policy stay in the app. */
|
||||
export class AuthStore {
|
||||
constructor(database, { singleUser = true } = {}) {
|
||||
@@ -78,6 +145,8 @@ export class AuthStore {
|
||||
await this.database.query(AUTH_SCHEMA);
|
||||
if (this.singleUser) {
|
||||
await this.database.query('CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))');
|
||||
} else {
|
||||
await this.database.query('DROP INDEX IF EXISTS auth_users_singleton_idx');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,9 +158,11 @@ export class AuthStore {
|
||||
async createUser(username, email, passwordHash) {
|
||||
try {
|
||||
const result = await this.database.query(
|
||||
`INSERT INTO auth_users (username, email, password_hash, updated_at)
|
||||
VALUES ($1, $2, $3, now())
|
||||
RETURNING id, username, email, password_hash, created_at, updated_at`,
|
||||
`INSERT INTO auth_users (username, email, password_hash, role, updated_at)
|
||||
VALUES ($1, $2, $3,
|
||||
CASE WHEN EXISTS (SELECT 1 FROM auth_users) THEN 'user' ELSE 'superadmin' END,
|
||||
now())
|
||||
RETURNING id, username, email, password_hash, role, created_at, updated_at`,
|
||||
[username, email, passwordHash]
|
||||
);
|
||||
return result.rows[0];
|
||||
@@ -107,7 +178,7 @@ export class AuthStore {
|
||||
|
||||
async findByIdentifier(identifier) {
|
||||
const result = await this.database.query(
|
||||
`SELECT id, username, email, password_hash, created_at, updated_at
|
||||
`SELECT id, username, email, password_hash, role, created_at, updated_at
|
||||
FROM auth_users WHERE username = $1 OR lower(email) = lower($1)`,
|
||||
[identifier]
|
||||
);
|
||||
@@ -131,7 +202,7 @@ export class AuthStore {
|
||||
|
||||
async findSessionUser(tokenHash) {
|
||||
const result = await this.database.query(
|
||||
`SELECT u.id, u.username, u.email, u.password_hash, u.created_at, u.updated_at
|
||||
`SELECT u.id, u.username, u.email, u.password_hash, u.role, u.created_at, u.updated_at
|
||||
FROM auth_sessions s JOIN auth_users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1 AND s.expires_at > now()`,
|
||||
[tokenHash]
|
||||
@@ -147,6 +218,85 @@ export class AuthStore {
|
||||
await this.database.query('DELETE FROM auth_sessions WHERE user_id = $1', [userId]);
|
||||
}
|
||||
|
||||
async listUsers() {
|
||||
const result = await this.database.query(
|
||||
'SELECT id, username, email, role, created_at, updated_at FROM auth_users ORDER BY created_at, id',
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
async createManagedUser(username, email, passwordHash, role = USER_ROLES.USER) {
|
||||
try {
|
||||
const result = await this.database.query(
|
||||
`INSERT INTO auth_users (username, email, password_hash, role, updated_at)
|
||||
VALUES ($1, $2, $3, $4, now())
|
||||
RETURNING id, username, email, role, created_at, updated_at`,
|
||||
[username, email, passwordHash, normalizeRole(role)],
|
||||
);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
if (error?.code === '23505') {
|
||||
const duplicate = new Error('auth user already exists');
|
||||
duplicate.code = 'AUTH_USER_EXISTS';
|
||||
throw duplicate;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async updateUser(id, { username, email, passwordHash, role } = {}) {
|
||||
const fields = [];
|
||||
const values = [];
|
||||
const add = (sql, value) => { fields.push(sql); values.push(value); };
|
||||
if (username !== undefined) add(`username = $${values.length + 1}`, username);
|
||||
if (email !== undefined) add(`email = $${values.length + 1}`, email);
|
||||
if (passwordHash !== undefined) add(`password_hash = $${values.length + 1}`, passwordHash);
|
||||
if (role !== undefined) add(`role = $${values.length + 1}`, normalizeRole(role));
|
||||
if (fields.length === 0) return;
|
||||
values.push(id);
|
||||
await this.database.query(
|
||||
`UPDATE auth_users SET ${fields.join(', ')}, updated_at = now() WHERE id = $${values.length}`,
|
||||
values,
|
||||
);
|
||||
}
|
||||
|
||||
async deleteUser(id) {
|
||||
await this.database.query('DELETE FROM auth_users WHERE id = $1', [id]);
|
||||
}
|
||||
|
||||
async deleteAllUsers() {
|
||||
await this.database.query('DELETE FROM auth_users');
|
||||
}
|
||||
|
||||
async getTotpState(userId) {
|
||||
const result = await this.database.query(
|
||||
'SELECT COALESCE(totp_secret, \'\') AS secret, COALESCE(totp_enabled, false) AS enabled FROM auth_users WHERE id = $1',
|
||||
[userId],
|
||||
);
|
||||
return result.rows[0] || { secret: '', enabled: false };
|
||||
}
|
||||
|
||||
async setTotpSecret(userId, secret) {
|
||||
await this.database.query(
|
||||
'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2',
|
||||
[secret, userId],
|
||||
);
|
||||
}
|
||||
|
||||
async enableTotp(userId) {
|
||||
await this.database.query(
|
||||
"UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''",
|
||||
[userId],
|
||||
);
|
||||
}
|
||||
|
||||
async disableTotp(userId) {
|
||||
await this.database.query(
|
||||
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1",
|
||||
[userId],
|
||||
);
|
||||
}
|
||||
|
||||
async pruneExpiredSessions() {
|
||||
await this.database.query('DELETE FROM auth_sessions WHERE expires_at < now()');
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user