import { BadRequestException, ConflictException, Inject, Injectable, Logger, NotFoundException, UnauthorizedException, } from '@nestjs/common'; import bcrypt from 'bcrypt'; import { randomBytes } from 'node:crypto'; import type { PublicUser } from '../domain/models'; import { OWNERSHIP_MIGRATION, USER_REPOSITORY } from '../domain/ports'; import type { OwnershipMigration, UserRepository } from '../domain/ports'; import { SessionService } from './session.service'; const BCRYPT_ROUNDS = 12; const MIN_PASSWORD_LEN = 8; // Local-account use-cases: first-admin bootstrap, registration, and the // credential check the LocalStrategy delegates to. External-identity logins // (OIDC/SAML) don't come through here - their strategies resolve users // directly via the repository. @Injectable() export class AuthService { private readonly logger = new Logger(AuthService.name); constructor( @Inject(USER_REPOSITORY) private readonly users: UserRepository, @Inject(OWNERSHIP_MIGRATION) private readonly migration: OwnershipMigration, ) {} // True once at least one account exists. The frontend shows the one-time // "create the first admin" screen while this is false. async isConfigured(): Promise { return (await this.users.count()) > 0; } // Every account, public shape only - for the admin's Users panel. async listUsers(): Promise { return (await this.users.list()).map(SessionService.toPublicUser); } // Validates a username/password pair for the local provider. Always runs a // bcrypt comparison (against a dummy hash when the user is absent) so a // missing user and a wrong password take the same time - no user // enumeration via timing. async validateCredentials(username: string, password: string): Promise { const user = await this.users.findByUsername(username); const hash = user?.password_hash ?? DUMMY_HASH; const ok = await bcrypt.compare(password, hash); if (!ok || !user || !user.password_hash) return null; return SessionService.toPublicUser(user); } // Creates the first account (role 'admin'). Refuses once any user exists - // subsequent accounts are added by an admin, not this open endpoint. async bootstrapAdmin(username: string, password: string): Promise { if (await this.isConfigured()) { throw new ConflictException('An account already exists; registration is closed'); } const admin = await this.createLocalUser(username, password, 'admin'); // The workspace built before this account existed had no owner; hand it to // the admin so a single-user deployment keeps its data when auth turns on. await this.migration.adoptOwnerless(admin.id); return admin; } async createLocalUser( username: string, password: string, role: 'admin' | 'user', ): Promise { const name = (username || '').trim(); if (!name) throw new BadRequestException('Username is required'); if (!password || password.length < MIN_PASSWORD_LEN) { throw new BadRequestException(`Password must be at least ${MIN_PASSWORD_LEN} characters`); } if (await this.users.findByUsername(name)) { throw new ConflictException('That username is taken'); } const password_hash = await bcrypt.hash(password, BCRYPT_ROUNDS); const user = await this.users.create({ username: name, password_hash, role }); return SessionService.toPublicUser(user); } // Requires the whole flow: used by the login route as a guard rail so a // disabled/absent local provider can't be logged into by accident. async requireConfigured(): Promise { if (!(await this.isConfigured())) { throw new UnauthorizedException('No account has been created yet'); } } // Self-service password change for local accounts. The current password is // verified first so a hijacked session alone can't lock the owner out. async changePassword( userId: string, currentPassword: string, newPassword: string, ): Promise { const user = await this.users.findById(userId); if (!user) throw new UnauthorizedException('Not signed in'); if (!user.password_hash) { throw new BadRequestException('This account signs in through an external provider'); } if (!(await bcrypt.compare(currentPassword, user.password_hash))) { throw new UnauthorizedException('The current password is incorrect'); } if (!newPassword || newPassword.length < MIN_PASSWORD_LEN) { throw new BadRequestException(`Password must be at least ${MIN_PASSWORD_LEN} characters`); } await this.users.setPasswordHash(user.id, await bcrypt.hash(newPassword, BCRYPT_ROUNDS)); } // Admin-driven role change. Refusing to act on the caller's own account is // the lockout guard: an admin can never demote themselves, so at least one // admin always remains. async adminSetRole( targetId: string, role: 'user' | 'admin', actingUserId: string | null, ): Promise { if (actingUserId !== null && targetId === actingUserId) { throw new BadRequestException('You cannot change your own role'); } const user = await this.users.findById(targetId); if (!user) throw new NotFoundException('No such user'); await this.users.setRole(user.id, role); return { ...SessionService.toPublicUser(user), role }; } // Admin-driven reset: replaces a local account's password without knowing // the old one. The caller (controller) is responsible for the admin check // and for revoking the target's sessions. async adminSetPassword(userId: string, newPassword: string): Promise { const user = await this.users.findById(userId); if (!user) throw new NotFoundException('No such user'); if (!user.password_hash) { throw new BadRequestException('This account signs in through an external provider'); } if (!newPassword || newPassword.length < MIN_PASSWORD_LEN) { throw new BadRequestException(`Password must be at least ${MIN_PASSWORD_LEN} characters`); } await this.users.setPasswordHash(user.id, await bcrypt.hash(newPassword, BCRYPT_ROUNDS)); return SessionService.toPublicUser(user); } // Recovery for forgotten passwords: a self-hosted deployment has no email // infrastructure, so the operator restarts the server once with // AUTH_RESET_PASSWORD="username:new-password", signs in, and removes the // variable. Returns the affected user id (so callers can revoke sessions), // or null when nothing was reset. async resetPasswordFromEnv(env = process.env.AUTH_RESET_PASSWORD): Promise { if (!env) return null; const sep = env.indexOf(':'); const username = sep === -1 ? '' : env.slice(0, sep).trim(); const password = sep === -1 ? '' : env.slice(sep + 1); if (!username || password.length < MIN_PASSWORD_LEN) { this.logger.warn( `AUTH_RESET_PASSWORD ignored: expected "username:password" with at least ${MIN_PASSWORD_LEN} password characters`, ); return null; } const user = await this.users.findByUsername(username); if (!user) { this.logger.warn('AUTH_RESET_PASSWORD ignored: no matching user'); return null; } await this.users.setPasswordHash(user.id, await bcrypt.hash(password, BCRYPT_ROUNDS)); this.logger.warn('A password was reset from AUTH_RESET_PASSWORD; remove the variable now.'); return user.id; } } // A real bcrypt hash of a random string, generated once at load. Used only to // equalise timing when the requested user doesn't exist (so a missing user and // a wrong password cost the same). It cannot match any real password. const DUMMY_HASH = bcrypt.hashSync(randomBytes(16).toString('hex'), BCRYPT_ROUNDS);