mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 18:34:09 +00:00
refactor(auth, files): async DB-touching methods; transactions through UnitOfWork
This commit is contained in:
@@ -45,8 +45,8 @@ export class AuthPublicController {
|
||||
@Post('demo-login')
|
||||
@Public('issues a session for the demo account; there is nothing to authenticate yet')
|
||||
@HttpCode(200)
|
||||
demoLogin(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
|
||||
const result = this.auth.demoLogin();
|
||||
async demoLogin(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
|
||||
const result = await this.auth.demoLogin();
|
||||
if (result.error) {
|
||||
throw new HttpException({ error: result.error }, result.status!);
|
||||
}
|
||||
@@ -56,9 +56,9 @@ export class AuthPublicController {
|
||||
|
||||
@Get('invite/:token')
|
||||
@Public('the invite token IS the credential')
|
||||
invite(@Param('token') token: string, @Req() req: Request) {
|
||||
async invite(@Param('token') token: string, @Req() req: Request) {
|
||||
this.limit('login', req, 10);
|
||||
const result = this.auth.validateInviteToken(token);
|
||||
const result = await this.auth.validateInviteToken(token);
|
||||
if (result.error) {
|
||||
throw new HttpException({ error: result.error }, result.status!);
|
||||
}
|
||||
@@ -85,7 +85,7 @@ export class AuthPublicController {
|
||||
async login(@Body() body: LoginDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) {
|
||||
this.limit('login', req, 10);
|
||||
const started = Date.now();
|
||||
const result = this.auth.loginUser(body);
|
||||
const result = await this.auth.loginUser(body);
|
||||
if (result.auditAction) {
|
||||
await this.audit.writeAudit({ userId: result.auditUserId ?? null, action: result.auditAction, ip: getClientIp(req), details: result.auditDetails });
|
||||
}
|
||||
@@ -116,7 +116,7 @@ export class AuthPublicController {
|
||||
const rawEmail = typeof body?.email === 'string' ? body.email : '';
|
||||
const ip = getClientIp(req);
|
||||
|
||||
const outcome = this.auth.requestPasswordReset(rawEmail, ip);
|
||||
const outcome = await this.auth.requestPasswordReset(rawEmail, ip);
|
||||
if (outcome.reason === 'issued' && outcome.tokenForDelivery && outcome.userEmail) {
|
||||
const origin = this.auth.getAppUrl();
|
||||
const url = `${origin.replace(/\/$/, '')}/reset-password?token=${encodeURIComponent(outcome.tokenForDelivery)}`;
|
||||
@@ -143,7 +143,7 @@ export class AuthPublicController {
|
||||
// a dedicated bucket) — without it reset tokens could be guessed unthrottled.
|
||||
this.limit('reset', req, 5);
|
||||
const ip = getClientIp(req);
|
||||
const result = this.auth.resetPassword(body);
|
||||
const result = await this.auth.resetPassword(body);
|
||||
if (result.error) {
|
||||
await this.audit.writeAudit({ userId: null, action: 'user.password_reset_fail', ip, details: { reason: result.error } });
|
||||
throw new HttpException({ error: result.error }, result.status!);
|
||||
@@ -160,7 +160,7 @@ export class AuthPublicController {
|
||||
@HttpCode(200)
|
||||
async verifyMfaLogin(@Body() body: MfaVerifyLoginDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) {
|
||||
this.limit('mfa', req, 5);
|
||||
const result = this.auth.verifyMfaLogin(body);
|
||||
const result = await this.auth.verifyMfaLogin(body);
|
||||
if (result.error) {
|
||||
throw new HttpException({ error: result.error }, result.status!);
|
||||
}
|
||||
|
||||
@@ -98,8 +98,8 @@ export class AuthController {
|
||||
|
||||
@Get('me')
|
||||
@MfaExempt('the client needs to know who it is to render the setup screen')
|
||||
me(@CurrentUser() user: User) {
|
||||
const loaded = this.auth.getCurrentUser(user.id);
|
||||
async me(@CurrentUser() user: User) {
|
||||
const loaded = await this.auth.getCurrentUser(user.id);
|
||||
if (!loaded) {
|
||||
throw new HttpException({ error: 'User not found' }, 404);
|
||||
}
|
||||
@@ -113,7 +113,7 @@ export class AuthController {
|
||||
// "remember me" login survives a password change (#1927). Bearer callers
|
||||
// have no cookie → undefined → the historical default duration.
|
||||
const remember = decodeSessionClaims((req.cookies as Record<string, string> | undefined)?.trek_session)?.remember;
|
||||
const result = this.auth.changePassword(user.id, user.email, body, remember);
|
||||
const result = await this.auth.changePassword(user.id, user.email, body, remember);
|
||||
if (result.error) {
|
||||
throw new HttpException({ error: result.error }, result.status!);
|
||||
}
|
||||
@@ -213,8 +213,8 @@ export class AuthController {
|
||||
}
|
||||
|
||||
@Get('users')
|
||||
users(@CurrentUser() user: User) {
|
||||
return { users: this.profile.listUsers(user.id) };
|
||||
async users(@CurrentUser() user: User) {
|
||||
return { users: await this.profile.listUsers(user.id) };
|
||||
}
|
||||
|
||||
@ManagedForbidden('validating a key spends the operator quota on a test click')
|
||||
@@ -229,8 +229,8 @@ export class AuthController {
|
||||
|
||||
@Get('app-settings')
|
||||
@MfaExempt('the setup screen reads the policy it is asking the user to satisfy')
|
||||
getAppSettings(@CurrentUser() user: User) {
|
||||
const result = this.auth.getAppSettings(user.id);
|
||||
async getAppSettings(@CurrentUser() user: User) {
|
||||
const result = await this.auth.getAppSettings(user.id);
|
||||
if (result.error) {
|
||||
throw new HttpException({ error: result.error }, result.status!);
|
||||
}
|
||||
@@ -240,7 +240,7 @@ export class AuthController {
|
||||
@Put('app-settings')
|
||||
@MfaExempt('an admin locked out by their own policy must still be able to lift it')
|
||||
async updateAppSettings(@CurrentUser() user: User, @Body() body: AppSettingsUpdateDto, @Req() req: Request) {
|
||||
const result = this.auth.updateAppSettings(user.id, body);
|
||||
const result = await this.auth.updateAppSettings(user.id, body);
|
||||
if (result.error) {
|
||||
throw new HttpException({ error: result.error }, result.status!);
|
||||
}
|
||||
@@ -258,7 +258,7 @@ export class AuthController {
|
||||
@MfaExempt('completing setup is the way out of the policy')
|
||||
@HttpCode(200)
|
||||
async mfaSetup(@CurrentUser() user: User) {
|
||||
const result = this.auth.setupMfa(user.id, user.email);
|
||||
const result = await this.auth.setupMfa(user.id, user.email);
|
||||
if (result.error) {
|
||||
throw new HttpException({ error: result.error }, result.status!);
|
||||
}
|
||||
@@ -276,7 +276,7 @@ export class AuthController {
|
||||
@HttpCode(200)
|
||||
async mfaEnable(@CurrentUser() user: User, @Body() body: MfaEnableDto, @Req() req: Request) {
|
||||
this.limit('mfa', req, 5);
|
||||
const result = this.auth.enableMfa(user.id, body.code);
|
||||
const result = await this.auth.enableMfa(user.id, body.code);
|
||||
if (result.error) {
|
||||
throw new HttpException({ error: result.error }, result.status!);
|
||||
}
|
||||
@@ -288,7 +288,7 @@ export class AuthController {
|
||||
@HttpCode(200)
|
||||
async mfaDisable(@CurrentUser() user: User, @Body() body: MfaDisableDto, @Req() req: Request) {
|
||||
this.limit('login', req, 5);
|
||||
const result = this.auth.disableMfa(user.id, user.email, body);
|
||||
const result = await this.auth.disableMfa(user.id, user.email, body);
|
||||
if (result.error) {
|
||||
throw new HttpException({ error: result.error }, result.status!);
|
||||
}
|
||||
|
||||
@@ -148,13 +148,13 @@ export class AuthService {
|
||||
// Toggles + tokens
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
resolveAuthToggles(): {
|
||||
async resolveAuthToggles(): Promise<{
|
||||
password_login: boolean;
|
||||
password_registration: boolean;
|
||||
oidc_login: boolean;
|
||||
oidc_registration: boolean;
|
||||
passkey_login: boolean;
|
||||
} {
|
||||
}> {
|
||||
const get = (key: string) =>
|
||||
this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = ?", key)?.value ?? null;
|
||||
|
||||
@@ -200,11 +200,11 @@ export class AuthService {
|
||||
};
|
||||
}
|
||||
|
||||
isOidcOnlyMode(): boolean {
|
||||
return !this.resolveAuthToggles().password_login;
|
||||
async isOidcOnlyMode(): Promise<boolean> {
|
||||
return !(await this.resolveAuthToggles()).password_login;
|
||||
}
|
||||
|
||||
generateToken(user: { id: number | bigint; password_version?: number }, remember?: boolean) {
|
||||
async generateToken(user: { id: number | bigint; password_version?: number }, remember?: boolean) {
|
||||
const pv = typeof user.password_version === 'number'
|
||||
? user.password_version
|
||||
: (this.db.get<{ password_version?: number }>('SELECT password_version FROM users WHERE id = ?', user.id)?.password_version ?? 0);
|
||||
@@ -244,8 +244,8 @@ export class AuthService {
|
||||
* the operator pointed here themselves (APP_URL, ALLOWED_ORIGINS or the
|
||||
* webauthn settings) is a real single-machine install and still counts.
|
||||
*/
|
||||
private passkeyConfigured(): boolean {
|
||||
const cfg = this.webauthn.resolve();
|
||||
private async passkeyConfigured(): Promise<boolean> {
|
||||
const cfg = await this.webauthn.resolve();
|
||||
if (!cfg) return false;
|
||||
if (cfg.rpID !== 'localhost' || cfg.explicitOrigins) return true;
|
||||
const env = readEnv();
|
||||
@@ -258,7 +258,7 @@ export class AuthService {
|
||||
async getAppConfig(authenticatedUser: User | undefined | null) {
|
||||
const userCount = this.db.get<{ count: number }>('SELECT COUNT(*) as count FROM users WHERE COALESCE(is_guest, 0) = 0')!.count;
|
||||
const isDemo = readEnv().demo.enabled;
|
||||
const toggles = this.resolveAuthToggles();
|
||||
const toggles = await this.resolveAuthToggles();
|
||||
// One directory deeper than the legacy src/services location — the extra
|
||||
// '../' keeps resolving to the workspace package.json.
|
||||
const version: string = readEnv().app.appVersion ?? require('../../../package.json').version;
|
||||
@@ -317,7 +317,7 @@ export class AuthService {
|
||||
// are true. `passkey_configured` stays a pure boolean — it never leaks the
|
||||
// resolved RP ID / origin / APP_URL on this unauthenticated endpoint.
|
||||
passkey_login: toggles.passkey_login,
|
||||
passkey_configured: this.passkeyConfigured(),
|
||||
passkey_configured: await this.passkeyConfigured(),
|
||||
env_override_oidc_only: readEnv().oidc.only,
|
||||
has_users: userCount > 0,
|
||||
setup_complete: setupComplete,
|
||||
@@ -333,7 +333,7 @@ export class AuthService {
|
||||
// fallback the upload filters use, so the client's picker and the
|
||||
// server's acceptance can never drift (the historical inline copy here
|
||||
// dropped pkpass, pkpasses, md and markdown).
|
||||
allowed_file_types: this.allowedFileTypes.get(),
|
||||
allowed_file_types: await this.allowedFileTypes.get(),
|
||||
// Whether the configuration belongs to whoever operates this install
|
||||
// rather than to its admin. The client uses it to stop offering settings
|
||||
// the server would refuse anyway — it is an honesty flag for the UI, never
|
||||
@@ -362,18 +362,18 @@ export class AuthService {
|
||||
// Auth: register, login, demo
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
demoLogin(): { error?: string; status?: number; token?: string; user?: Record<string, unknown> } {
|
||||
async demoLogin(): Promise<{ error?: string; status?: number; token?: string; user?: Record<string, unknown> }> {
|
||||
if (!readEnv().demo.enabled) {
|
||||
return { error: 'Not found', status: 404 };
|
||||
}
|
||||
const user = this.db.get<User>('SELECT * FROM users WHERE email = ?', DEMO_EMAIL_PRIMARY);
|
||||
if (!user) return { error: 'Demo user not found', status: 500 };
|
||||
const token = this.generateToken(user);
|
||||
const token = await this.generateToken(user);
|
||||
const safe = stripUserForClient(user) as Record<string, unknown>;
|
||||
return { token, user: { ...safe, avatar_url: avatarUrl(user) } };
|
||||
}
|
||||
|
||||
validateInviteToken(token: string): { error?: string; status?: number; valid?: boolean; max_uses?: number; used_count?: number; expires_at?: string } {
|
||||
async validateInviteToken(token: string): Promise<{ error?: string; status?: number; valid?: boolean; max_uses?: number; used_count?: number; expires_at?: string }> {
|
||||
const invite = this.db.get('SELECT * FROM invite_tokens WHERE token = ?', token) as any;
|
||||
if (!invite) return { error: 'Invalid invite link', status: 404 };
|
||||
if (invite.max_uses > 0 && invite.used_count >= invite.max_uses) return { error: 'Invite link has been fully used', status: 410 };
|
||||
@@ -398,7 +398,7 @@ export class AuthService {
|
||||
}
|
||||
|
||||
if (userCount > 0 && !validInvite) {
|
||||
const toggles = this.resolveAuthToggles();
|
||||
const toggles = await this.resolveAuthToggles();
|
||||
if (!toggles.password_registration) {
|
||||
return { error: 'Password registration is disabled. Contact your administrator.', status: 403 };
|
||||
}
|
||||
@@ -435,7 +435,7 @@ export class AuthService {
|
||||
);
|
||||
|
||||
const user = { id: result.lastInsertRowid, username, email, role, avatar: null, mfa_enabled: false };
|
||||
const token = this.generateToken(user);
|
||||
const token = await this.generateToken(user);
|
||||
|
||||
if (validInvite) {
|
||||
const updated = this.db.get(
|
||||
@@ -464,7 +464,7 @@ export class AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
loginUser(rawBody: unknown): {
|
||||
async loginUser(rawBody: unknown): Promise<{
|
||||
error?: string;
|
||||
status?: number;
|
||||
token?: string;
|
||||
@@ -475,9 +475,9 @@ export class AuthService {
|
||||
auditUserId?: number | null;
|
||||
auditAction?: string;
|
||||
auditDetails?: Record<string, unknown>;
|
||||
} {
|
||||
}> {
|
||||
const body = rawBody as { email?: string; password?: string; remember_me?: boolean };
|
||||
if (this.isOidcOnlyMode()) {
|
||||
if (await this.isOidcOnlyMode()) {
|
||||
return { error: 'Password authentication is disabled. Please sign in with SSO.', status: 403 };
|
||||
}
|
||||
|
||||
@@ -526,7 +526,7 @@ export class AuthService {
|
||||
}
|
||||
|
||||
this.db.run('UPDATE users SET last_login = CURRENT_TIMESTAMP, login_count = login_count + 1 WHERE id = ?', user.id);
|
||||
const token = this.generateToken(user, remember);
|
||||
const token = await this.generateToken(user, remember);
|
||||
const userSafe = stripUserForClient(user) as Record<string, unknown>;
|
||||
|
||||
return {
|
||||
@@ -543,9 +543,9 @@ export class AuthService {
|
||||
// Session
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
getCurrentUser(
|
||||
async getCurrentUser(
|
||||
userId: number
|
||||
): (Record<string, unknown> & Pick<User, 'id' | 'username' | 'email' | 'role'> & { avatar_url: string }) | null {
|
||||
): Promise<(Record<string, unknown> & Pick<User, 'id' | 'username' | 'email' | 'role'> & { avatar_url: string }) | null> {
|
||||
const user = this.db.get<User>(
|
||||
'SELECT id, username, email, role, avatar, oidc_issuer, created_at, mfa_enabled, must_change_password FROM users WHERE id = ?',
|
||||
userId
|
||||
@@ -559,14 +559,14 @@ export class AuthService {
|
||||
// Password & account
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
changePassword(
|
||||
async changePassword(
|
||||
userId: number,
|
||||
userEmail: string,
|
||||
rawBody: unknown,
|
||||
remember?: boolean,
|
||||
): { error?: string; status?: number; success?: boolean; token?: string } {
|
||||
): Promise<{ error?: string; status?: number; success?: boolean; token?: string }> {
|
||||
const body = rawBody as { current_password?: string; new_password?: string };
|
||||
if (this.isOidcOnlyMode()) {
|
||||
if (await this.isOidcOnlyMode()) {
|
||||
return { error: 'Password authentication is disabled.', status: 403 };
|
||||
}
|
||||
if (readEnv().demo.enabled && isDemoEmail(userEmail)) {
|
||||
@@ -588,7 +588,7 @@ export class AuthService {
|
||||
const hash = bcrypt.hashSync(new_password, BCRYPT_COST);
|
||||
const newPv = (user.password_version ?? 0) + 1;
|
||||
|
||||
this.db.transaction(() => {
|
||||
await this.uow.transactional(async () => {
|
||||
this.db.run('UPDATE users SET password_hash = ?, must_change_password = 0, password_version = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', hash, newPv, userId);
|
||||
// A password change rotates the user's sessions: bumping password_version
|
||||
// invalidates existing JWT cookie sessions, and the separate MCP static
|
||||
@@ -606,7 +606,7 @@ export class AuthService {
|
||||
// stays logged in while other existing sessions are rotated out by the pv
|
||||
// gate — preserving the login's remember choice instead of downgrading a
|
||||
// remembered session to the default duration (#1927).
|
||||
const token = this.generateToken({ id: userId, password_version: newPv }, remember);
|
||||
const token = await this.generateToken({ id: userId, password_version: newPv }, remember);
|
||||
return { success: true, token };
|
||||
}
|
||||
|
||||
@@ -639,7 +639,7 @@ export class AuthService {
|
||||
// work, not with a move.
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
getAppSettings(userId: number): { error?: string; status?: number; data?: Record<string, string> } {
|
||||
async getAppSettings(userId: number): Promise<{ error?: string; status?: number; data?: Record<string, string> }> {
|
||||
const user = this.db.get<{ role: string }>('SELECT role FROM users WHERE id = ?', userId);
|
||||
if (user?.role !== 'admin') return { error: 'Admin access required', status: 403 };
|
||||
|
||||
@@ -651,10 +651,10 @@ export class AuthService {
|
||||
return { data: result };
|
||||
}
|
||||
|
||||
updateAppSettings(
|
||||
async updateAppSettings(
|
||||
userId: number,
|
||||
rawBody: unknown
|
||||
): {
|
||||
): Promise<{
|
||||
error?: string;
|
||||
status?: number;
|
||||
success?: boolean;
|
||||
@@ -662,7 +662,7 @@ export class AuthService {
|
||||
auditDebugDetails?: Record<string, unknown>;
|
||||
/** Names the operator holds, skipped rather than written. Empty when self-hosted. */
|
||||
managedKeys?: string[];
|
||||
} {
|
||||
}> {
|
||||
const body = rawBody as Record<string, unknown>;
|
||||
const user = this.db.get<{ role: string }>('SELECT role FROM users WHERE id = ?', userId);
|
||||
if (user?.role !== 'admin') return { error: 'Admin access required', status: 403 };
|
||||
@@ -683,7 +683,7 @@ export class AuthService {
|
||||
|
||||
// Lockout prevention: can't disable all login methods
|
||||
if (body.password_login !== undefined || body.oidc_login !== undefined) {
|
||||
const current = this.resolveAuthToggles();
|
||||
const current = await this.resolveAuthToggles();
|
||||
const oidcConfigured = !!(
|
||||
(readEnv().oidc.issuer || this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'oidc_issuer'")?.value) &&
|
||||
(readEnv().oidc.clientId || this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'oidc_client_id'")?.value)
|
||||
@@ -748,7 +748,7 @@ export class AuthService {
|
||||
// MFA
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
setupMfa(userId: number, userEmail: string): { error?: string; status?: number; secret?: string; otpauth_url?: string; qrPromise?: Promise<string> } {
|
||||
async setupMfa(userId: number, userEmail: string): Promise<{ error?: string; status?: number; secret?: string; otpauth_url?: string; qrPromise?: Promise<string> }> {
|
||||
if (readEnv().demo.enabled && isDemoEmail(userEmail)) {
|
||||
return { error: 'MFA is not available in demo mode.', status: 403 };
|
||||
}
|
||||
@@ -768,7 +768,7 @@ export class AuthService {
|
||||
return { secret, otpauth_url, qrPromise: QRCode.toString(otpauth_url, { type: 'svg', width: 250 }) };
|
||||
}
|
||||
|
||||
enableMfa(userId: number, rawCode: unknown): { error?: string; status?: number; success?: boolean; mfa_enabled?: boolean; backup_codes?: string[] } {
|
||||
async enableMfa(userId: number, rawCode: unknown): Promise<{ error?: string; status?: number; success?: boolean; mfa_enabled?: boolean; backup_codes?: string[] }> {
|
||||
const code = rawCode as string | undefined;
|
||||
if (!code) {
|
||||
return { error: 'Verification code is required', status: 400 };
|
||||
@@ -794,11 +794,11 @@ export class AuthService {
|
||||
return { success: true, mfa_enabled: true, backup_codes: backupCodes };
|
||||
}
|
||||
|
||||
disableMfa(
|
||||
async disableMfa(
|
||||
userId: number,
|
||||
userEmail: string,
|
||||
rawBody: unknown
|
||||
): { error?: string; status?: number; success?: boolean; mfa_enabled?: boolean } {
|
||||
): Promise<{ error?: string; status?: number; success?: boolean; mfa_enabled?: boolean }> {
|
||||
const body = rawBody as { password?: string; code?: string };
|
||||
if (readEnv().demo.enabled && isDemoEmail(userEmail)) {
|
||||
return { error: 'MFA cannot be changed in demo mode.', status: 403 };
|
||||
@@ -831,14 +831,14 @@ export class AuthService {
|
||||
return { success: true, mfa_enabled: false };
|
||||
}
|
||||
|
||||
verifyMfaLogin(rawBody: unknown): {
|
||||
async verifyMfaLogin(rawBody: unknown): Promise<{
|
||||
error?: string;
|
||||
status?: number;
|
||||
token?: string;
|
||||
user?: Record<string, unknown>;
|
||||
remember?: boolean;
|
||||
auditUserId?: number;
|
||||
} {
|
||||
}> {
|
||||
const body = rawBody as { mfa_token?: string; code?: string; remember_me?: boolean };
|
||||
const { mfa_token, code, remember_me } = body;
|
||||
const remember = remember_me === true;
|
||||
@@ -868,7 +868,7 @@ export class AuthService {
|
||||
hashes.splice(idx, 1);
|
||||
// Consume the backup code and record the login atomically — the code
|
||||
// must not burn without the login landing (or vice versa).
|
||||
this.db.transaction(() => {
|
||||
await this.uow.transactional(async () => {
|
||||
this.db.run('UPDATE users SET mfa_backup_codes = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
|
||||
JSON.stringify(hashes),
|
||||
user.id
|
||||
@@ -878,7 +878,7 @@ export class AuthService {
|
||||
} else {
|
||||
this.db.run('UPDATE users SET last_login = CURRENT_TIMESTAMP, login_count = login_count + 1 WHERE id = ?', user.id);
|
||||
}
|
||||
const sessionToken = this.generateToken(user, remember);
|
||||
const sessionToken = await this.generateToken(user, remember);
|
||||
const userSafe = stripUserForClient(user) as Record<string, unknown>;
|
||||
return {
|
||||
token: sessionToken,
|
||||
@@ -895,7 +895,7 @@ export class AuthService {
|
||||
// Password reset
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
requestPasswordReset(rawEmail: string, createdIp: string | null): PasswordResetRequestOutcome {
|
||||
async requestPasswordReset(rawEmail: string, createdIp: string | null): Promise<PasswordResetRequestOutcome> {
|
||||
const email = String(rawEmail || '').trim().toLowerCase();
|
||||
// Basic shape check — a fully empty / malformed email is treated like
|
||||
// "no user" so we still spend the same time internally. Same "x@y.z somewhere
|
||||
@@ -904,7 +904,7 @@ export class AuthService {
|
||||
const looksLikeEmail = email.length > 0 && /^.[^@\r\n\u2028\u2029]*@.[^.\r\n\u2028\u2029]*\../m.test(email);
|
||||
|
||||
// Global policy check: password login disabled → no reset possible.
|
||||
const toggles = this.resolveAuthToggles();
|
||||
const toggles = await this.resolveAuthToggles();
|
||||
if (!toggles.password_login) {
|
||||
return { tokenForDelivery: null, userId: null, userEmail: null, reason: 'password_login_disabled' };
|
||||
}
|
||||
@@ -971,7 +971,7 @@ export class AuthService {
|
||||
* compromised email alone therefore does NOT allow taking over a
|
||||
* 2FA-protected account.
|
||||
*/
|
||||
resetPassword(rawBody: unknown): ResetPasswordOutcome {
|
||||
async resetPassword(rawBody: unknown): Promise<ResetPasswordOutcome> {
|
||||
const body = rawBody as { token?: string; new_password?: string; mfa_code?: string };
|
||||
const { token, new_password, mfa_code } = body;
|
||||
if (!token || typeof token !== 'string') {
|
||||
@@ -1028,7 +1028,7 @@ export class AuthService {
|
||||
const newHash = bcrypt.hashSync(new_password, BCRYPT_COST);
|
||||
const newPv = (user.password_version ?? 0) + 1;
|
||||
|
||||
this.db.transaction(() => {
|
||||
await this.uow.transactional(async () => {
|
||||
// Burn the token first to keep it atomic with the password change.
|
||||
this.db.run('UPDATE password_reset_tokens SET consumed_at = CURRENT_TIMESTAMP WHERE id = ?', row.id);
|
||||
// Also burn every OTHER live token for this user — a fresh login
|
||||
@@ -1074,7 +1074,7 @@ export class AuthService {
|
||||
// which is about minting a token.
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
isDemoUser(userId: number): boolean {
|
||||
async isDemoUser(userId: number): Promise<boolean> {
|
||||
if (!readEnv().demo.enabled) return false;
|
||||
const user = this.db.get<{ email: string }>('SELECT email FROM users WHERE id = ?', userId);
|
||||
return isDemoEmail(user?.email);
|
||||
@@ -1089,7 +1089,7 @@ export class AuthService {
|
||||
* (MCP bearer, WebSocket handshake, file-download query tokens, photo
|
||||
* route) should go through.
|
||||
*/
|
||||
verifyJwtToken(token: string): User | null {
|
||||
async verifyJwtToken(token: string): Promise<User | null> {
|
||||
return verifyJwtAndLoadUser(token);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,13 +10,13 @@ import { verifyJwtAndLoadUser } from './jwt-verify';
|
||||
*/
|
||||
@Injectable()
|
||||
export class CookieAuthGuard implements CanActivate {
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest<Request & { cookies?: Record<string, string> }>();
|
||||
const cookieToken = req.cookies?.trek_session;
|
||||
if (!cookieToken) {
|
||||
throw new HttpException({ error: 'Cookie session required for this endpoint', code: 'COOKIE_AUTH_REQUIRED' }, 401);
|
||||
}
|
||||
const user = verifyJwtAndLoadUser(cookieToken);
|
||||
const user = await verifyJwtAndLoadUser(cookieToken);
|
||||
if (!user) {
|
||||
throw new HttpException({ error: 'Invalid or expired session', code: 'AUTH_REQUIRED' }, 401);
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ import { IS_PUBLIC, OPTIONAL_AUTH } from './public.decorator';
|
||||
export class GlobalAuthGuard implements CanActivate {
|
||||
constructor(private readonly reflector: Reflector) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const handler = context.getHandler();
|
||||
const controller = context.getClass();
|
||||
|
||||
@@ -40,7 +40,7 @@ export class GlobalAuthGuard implements CanActivate {
|
||||
|
||||
if (this.reflector.getAllAndOverride(OPTIONAL_AUTH, [handler, controller])) {
|
||||
const token = extractToken(req);
|
||||
(req as { user: unknown }).user = (token ? verifyJwtAndLoadUser(token) : null) || null;
|
||||
(req as { user: unknown }).user = (token ? await verifyJwtAndLoadUser(token) : null) || null;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ export class GlobalAuthGuard implements CanActivate {
|
||||
];
|
||||
if (declared.length > 0) {
|
||||
const declaredToken = extractToken(req);
|
||||
(req as { user: unknown }).user = (declaredToken ? verifyJwtAndLoadUser(declaredToken) : null) || null;
|
||||
(req as { user: unknown }).user = (declaredToken ? await verifyJwtAndLoadUser(declaredToken) : null) || null;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ export class GlobalAuthGuard implements CanActivate {
|
||||
if (!token) {
|
||||
throw new HttpException({ error: 'Access token required', code: 'AUTH_REQUIRED' }, 401);
|
||||
}
|
||||
const user = verifyJwtAndLoadUser(token);
|
||||
const user = await verifyJwtAndLoadUser(token);
|
||||
if (!user) {
|
||||
throw new HttpException({ error: 'Invalid or expired token', code: 'AUTH_REQUIRED' }, 401);
|
||||
}
|
||||
|
||||
@@ -12,13 +12,13 @@ import { extractToken, verifyJwtAndLoadUser } from './jwt-verify';
|
||||
*/
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest<Request>();
|
||||
const token = extractToken(req);
|
||||
if (!token) {
|
||||
throw new HttpException({ error: 'Access token required', code: 'AUTH_REQUIRED' }, 401);
|
||||
}
|
||||
const user = verifyJwtAndLoadUser(token);
|
||||
const user = await verifyJwtAndLoadUser(token);
|
||||
if (!user) {
|
||||
throw new HttpException({ error: 'Invalid or expired token', code: 'AUTH_REQUIRED' }, 401);
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ export function decodeSessionClaims(token: string | undefined): SessionClaims |
|
||||
return decoded as SessionClaims;
|
||||
}
|
||||
|
||||
export function verifyJwtAndLoadUser(token: string): User | null {
|
||||
export async function verifyJwtAndLoadUser(token: string): Promise<User | null> {
|
||||
try {
|
||||
const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] }) as { id: number; pv?: number; purpose?: string };
|
||||
// Purpose-scoped tokens (e.g. the short-lived mfa_login token) share this
|
||||
|
||||
@@ -49,7 +49,7 @@ export class MfaPolicyGuard implements CanActivate {
|
||||
private readonly reflector: Reflector,
|
||||
) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const handler = context.getHandler();
|
||||
const controller = context.getClass();
|
||||
|
||||
|
||||
@@ -10,10 +10,10 @@ import { extractToken, verifyJwtAndLoadUser } from './jwt-verify';
|
||||
*/
|
||||
@Injectable()
|
||||
export class OptionalJwtGuard implements CanActivate {
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest<Request>();
|
||||
const token = extractToken(req);
|
||||
(req as { user: unknown }).user = (token ? verifyJwtAndLoadUser(token) : null) || null;
|
||||
(req as { user: unknown }).user = (token ? await verifyJwtAndLoadUser(token) : null) || null;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,8 @@ import { AuthService } from './auth.service';
|
||||
export class PasskeyEnabledGuard implements CanActivate {
|
||||
constructor(private readonly auth: AuthService) {}
|
||||
|
||||
canActivate(): boolean {
|
||||
if (!this.auth.resolveAuthToggles().passkey_login) {
|
||||
async canActivate(): Promise<boolean> {
|
||||
if (!(await this.auth.resolveAuthToggles()).passkey_login) {
|
||||
throw new HttpException({ error: 'Passkey login is not enabled' }, 404);
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -104,14 +104,14 @@ export class PasskeyController {
|
||||
@Get('credentials')
|
||||
@MfaExempt('the setup screen lists what the user already has')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
list(@CurrentUser() user: User) {
|
||||
return { credentials: this.passkeys.listPasskeys(user.id) };
|
||||
async list(@CurrentUser() user: User) {
|
||||
return { credentials: await this.passkeys.listPasskeys(user.id) };
|
||||
}
|
||||
|
||||
@Patch('credentials/:id')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
rename(@CurrentUser() user: User, @Param('id') id: string, @Body() body: PasskeyRenameDto) {
|
||||
const result = this.passkeys.renamePasskey(user.id, id, body?.name);
|
||||
async rename(@CurrentUser() user: User, @Param('id') id: string, @Body() body: PasskeyRenameDto) {
|
||||
const result = await this.passkeys.renamePasskey(user.id, id, body?.name);
|
||||
if (result.error) throw new HttpException({ error: result.error }, result.status!);
|
||||
return { success: true };
|
||||
}
|
||||
@@ -120,7 +120,7 @@ export class PasskeyController {
|
||||
@UseGuards(JwtAuthGuard)
|
||||
async remove(@CurrentUser() user: User, @Param('id') id: string, @Body() body: PasskeyDeleteDto, @Req() req: Request) {
|
||||
this.limit('login', req, 5);
|
||||
const result = this.passkeys.deletePasskey(user.id, id, body?.password);
|
||||
const result = await this.passkeys.deletePasskey(user.id, id, body?.password);
|
||||
if (result.error) throw new HttpException({ error: result.error }, result.status!);
|
||||
await this.audit.writeAudit({ userId: user.id, action: 'user.passkey_delete', resource: String(id), ip: getClientIp(req) });
|
||||
return { success: true };
|
||||
|
||||
@@ -12,6 +12,7 @@ import { avatarUrl } from '../common/avatarUrl';
|
||||
import { stripUserForClient } from './auth.helpers';
|
||||
import { AuthService } from './auth.service';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import type { User } from '../../types';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -107,17 +108,18 @@ export class PasskeyService {
|
||||
private readonly db: DatabaseService,
|
||||
private readonly auth: AuthService,
|
||||
private readonly webauthn: WebauthnConfigService,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Challenge store (DB-backed, single-use, TTL'd)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private purgeExpiredChallenges(now: number): void {
|
||||
private async purgeExpiredChallenges(now: number): Promise<void> {
|
||||
this.db.run('DELETE FROM webauthn_challenges WHERE expires_at < ?', now);
|
||||
}
|
||||
|
||||
private storeChallenge(challenge: string, userId: number | null, type: 'registration' | 'authentication', now: number): void {
|
||||
private async storeChallenge(challenge: string, userId: number | null, type: 'registration' | 'authentication', now: number): Promise<void> {
|
||||
this.db.run(
|
||||
'INSERT INTO webauthn_challenges (challenge, user_id, type, expires_at) VALUES (?, ?, ?, ?)',
|
||||
challenge, userId, type, now + CHALLENGE_TTL_MS,
|
||||
@@ -130,7 +132,7 @@ export class PasskeyService {
|
||||
* concurrent double-submit of the same assertion can never spend one challenge
|
||||
* twice (the replay window a SELECT→await→DELETE ordering would open).
|
||||
*/
|
||||
private claimChallenge(challenge: string, type: 'registration' | 'authentication', now: number): { user_id: number | null } | null {
|
||||
private async claimChallenge(challenge: string, type: 'registration' | 'authentication', now: number): Promise<{ user_id: number | null } | null> {
|
||||
const row = this.db.get<{ user_id: number | null }>(
|
||||
'DELETE FROM webauthn_challenges WHERE challenge = ? AND type = ? AND expires_at > ? RETURNING user_id',
|
||||
challenge, type, now,
|
||||
@@ -203,7 +205,7 @@ export class PasskeyService {
|
||||
password: string | undefined,
|
||||
requestOrigin?: string,
|
||||
): Promise<{ error?: string; status?: number; options?: Awaited<ReturnType<typeof generateRegistrationOptions>> }> {
|
||||
const cfg = this.webauthn.resolve();
|
||||
const cfg = await this.webauthn.resolve();
|
||||
if (!cfg) return { ...NOT_CONFIGURED };
|
||||
if (this.originCannotVerify(cfg, requestOrigin)) return { ...NOT_CONFIGURED };
|
||||
|
||||
@@ -222,7 +224,7 @@ export class PasskeyService {
|
||||
);
|
||||
|
||||
const now = Date.now();
|
||||
this.purgeExpiredChallenges(now);
|
||||
await this.purgeExpiredChallenges(now);
|
||||
|
||||
const options = await generateRegistrationOptions({
|
||||
rpName: cfg.rpName,
|
||||
@@ -237,7 +239,7 @@ export class PasskeyService {
|
||||
supportedAlgorithmIDs: SUPPORTED_ALGORITHM_IDS,
|
||||
});
|
||||
|
||||
this.storeChallenge(options.challenge, userId, 'registration', now);
|
||||
await this.storeChallenge(options.challenge, userId, 'registration', now);
|
||||
return { options };
|
||||
}
|
||||
|
||||
@@ -245,7 +247,7 @@ export class PasskeyService {
|
||||
userId: number,
|
||||
body: { attestationResponse?: unknown; name?: unknown },
|
||||
): Promise<{ error?: string; status?: number; success?: boolean; credential?: unknown }> {
|
||||
const cfg = this.webauthn.resolve();
|
||||
const cfg = await this.webauthn.resolve();
|
||||
if (!cfg) return { ...NOT_CONFIGURED };
|
||||
|
||||
const resp = body?.attestationResponse;
|
||||
@@ -255,7 +257,7 @@ export class PasskeyService {
|
||||
if (!challenge) return { error: 'Invalid registration response', status: 400 };
|
||||
|
||||
const now = Date.now();
|
||||
const claimed = this.claimChallenge(challenge, 'registration', now);
|
||||
const claimed = await this.claimChallenge(challenge, 'registration', now);
|
||||
if (!claimed || claimed.user_id !== userId) {
|
||||
return { error: 'Registration challenge expired. Please try again.', status: 400 };
|
||||
}
|
||||
@@ -291,15 +293,14 @@ export class PasskeyService {
|
||||
// Duplicate check + INSERT in one transaction so the UNIQUE race can't slip
|
||||
// between them; the sentinel keeps the legacy 409-vs-400 split intact.
|
||||
try {
|
||||
this.db.transaction((conn) => {
|
||||
if (conn.prepare('SELECT id FROM webauthn_credentials WHERE credential_id = ?').get(credential.id)) {
|
||||
await this.uow.transactional(async () => {
|
||||
if (this.db.get('SELECT id FROM webauthn_credentials WHERE credential_id = ?', credential.id)) {
|
||||
throw DUPLICATE_CREDENTIAL;
|
||||
}
|
||||
conn.prepare(
|
||||
this.db.run(
|
||||
`INSERT INTO webauthn_credentials
|
||||
(user_id, credential_id, public_key, counter, transports, device_type, backed_up, name, aaguid, last_used_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)`,
|
||||
).run(
|
||||
userId,
|
||||
credential.id,
|
||||
Buffer.from(credential.publicKey),
|
||||
@@ -334,12 +335,12 @@ export class PasskeyService {
|
||||
status?: number;
|
||||
options?: Awaited<ReturnType<typeof generateAuthenticationOptions>>;
|
||||
}> {
|
||||
const cfg = this.webauthn.resolve();
|
||||
const cfg = await this.webauthn.resolve();
|
||||
if (!cfg) return { ...NOT_CONFIGURED };
|
||||
if (this.originCannotVerify(cfg, requestOrigin)) return { ...NOT_CONFIGURED };
|
||||
|
||||
const now = Date.now();
|
||||
this.purgeExpiredChallenges(now);
|
||||
await this.purgeExpiredChallenges(now);
|
||||
|
||||
const options = await generateAuthenticationOptions({
|
||||
rpID: cfg.rpID,
|
||||
@@ -348,7 +349,7 @@ export class PasskeyService {
|
||||
// accounts have passkeys, so the endpoint can't be used to enumerate users.
|
||||
});
|
||||
|
||||
this.storeChallenge(options.challenge, null, 'authentication', now);
|
||||
await this.storeChallenge(options.challenge, null, 'authentication', now);
|
||||
return { options };
|
||||
}
|
||||
|
||||
@@ -360,7 +361,7 @@ export class PasskeyService {
|
||||
auditUserId?: number | null;
|
||||
auditAction?: string;
|
||||
}> {
|
||||
const cfg = this.webauthn.resolve();
|
||||
const cfg = await this.webauthn.resolve();
|
||||
if (!cfg) return { ...NOT_CONFIGURED };
|
||||
|
||||
const resp = body?.assertionResponse;
|
||||
@@ -371,7 +372,7 @@ export class PasskeyService {
|
||||
|
||||
// Claim the challenge (single-use) BEFORE looking anything up or verifying.
|
||||
const now = Date.now();
|
||||
if (!this.claimChallenge(challenge, 'authentication', now)) return { ...AUTH_FAILED };
|
||||
if (!(await this.claimChallenge(challenge, 'authentication', now))) return { ...AUTH_FAILED };
|
||||
|
||||
const credId = (resp as { id?: unknown; rawId?: unknown }).id ?? (resp as { rawId?: unknown }).rawId;
|
||||
if (typeof credId !== 'string') return { ...AUTH_FAILED };
|
||||
@@ -417,15 +418,15 @@ export class PasskeyService {
|
||||
if (!user) return { ...AUTH_FAILED };
|
||||
|
||||
// Persist the new counter + last-used and bump login bookkeeping atomically.
|
||||
this.db.transaction((conn) => {
|
||||
conn.prepare('UPDATE webauthn_credentials SET counter = ?, last_used_at = CURRENT_TIMESTAMP WHERE id = ?').run(newCounter, cred.id);
|
||||
conn.prepare('UPDATE users SET last_login = CURRENT_TIMESTAMP, login_count = login_count + 1 WHERE id = ?').run(user.id);
|
||||
await this.uow.transactional(async () => {
|
||||
this.db.run('UPDATE webauthn_credentials SET counter = ?, last_used_at = CURRENT_TIMESTAMP WHERE id = ?', newCounter, cred.id);
|
||||
this.db.run('UPDATE users SET last_login = CURRENT_TIMESTAMP, login_count = login_count + 1 WHERE id = ?', user.id);
|
||||
});
|
||||
|
||||
// A user-verified passkey is phishing-resistant and inherently two-factor
|
||||
// (device possession + biometric/PIN), so it mints the real session directly
|
||||
// — the SAME path as password and OIDC login (no new token shape).
|
||||
const token = this.auth.generateToken(user);
|
||||
const token = await this.auth.generateToken(user);
|
||||
const userSafe = stripUserForClient(user) as Record<string, unknown>;
|
||||
return { token, user: { ...userSafe, avatar_url: avatarUrl(user) }, auditUserId: Number(user.id) };
|
||||
}
|
||||
@@ -434,7 +435,7 @@ export class PasskeyService {
|
||||
// Management (authenticated, owner-scoped)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
listPasskeys(userId: number): Array<Record<string, unknown>> {
|
||||
async listPasskeys(userId: number): Promise<Array<Record<string, unknown>>> {
|
||||
const rows = this.db.all<{ backed_up: number } & Record<string, unknown>>(
|
||||
'SELECT id, name, device_type, backed_up, created_at, last_used_at FROM webauthn_credentials WHERE user_id = ? ORDER BY created_at DESC',
|
||||
userId,
|
||||
@@ -442,7 +443,7 @@ export class PasskeyService {
|
||||
return rows.map((r) => ({ ...r, backed_up: r.backed_up === 1 }));
|
||||
}
|
||||
|
||||
renamePasskey(userId: number, id: string, name: unknown): { error?: string; status?: number; success?: boolean } {
|
||||
async renamePasskey(userId: number, id: string, name: unknown): Promise<{ error?: string; status?: number; success?: boolean }> {
|
||||
const cleanName = sanitizeName(name);
|
||||
if (!cleanName) return { error: 'Name is required', status: 400 };
|
||||
// Ownership enforced in SQL (404 on miss, never a 403 that leaks existence).
|
||||
@@ -451,11 +452,11 @@ export class PasskeyService {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
deletePasskey(
|
||||
async deletePasskey(
|
||||
userId: number,
|
||||
id: string,
|
||||
password: string | undefined,
|
||||
): { error?: string; status?: number; success?: boolean } {
|
||||
): Promise<{ error?: string; status?: number; success?: boolean }> {
|
||||
// Re-auth before removing a credential (a hijacked session must not be able to
|
||||
// strip the victim's passkeys). Deleting is always allowed because every
|
||||
// account keeps a usable password as recovery fallback — losing all passkeys
|
||||
@@ -470,7 +471,7 @@ export class PasskeyService {
|
||||
}
|
||||
|
||||
/** Admin: clear all of a user's passkeys (e.g. on suspected compromise). */
|
||||
adminResetPasskeys(targetUserId: number): { error?: string; status?: number; success?: boolean; deleted?: number; email?: string } {
|
||||
async adminResetPasskeys(targetUserId: number): Promise<{ error?: string; status?: number; success?: boolean; deleted?: number; email?: string }> {
|
||||
const target = this.db.get<{ id: number; email: string }>('SELECT id, email FROM users WHERE id = ?', targetUserId);
|
||||
if (!target) return { error: 'User not found', status: 404 };
|
||||
const result = this.db.run('DELETE FROM webauthn_credentials WHERE user_id = ?', targetUserId);
|
||||
|
||||
@@ -21,7 +21,7 @@ import { DatabaseService } from '../database/database.service';
|
||||
export class RegistrationInvitesService {
|
||||
constructor(private readonly db: DatabaseService) {}
|
||||
|
||||
listInvites() {
|
||||
async listInvites() {
|
||||
return this.db.all(`
|
||||
SELECT i.*, u.username as created_by_name, t.title as trip_title
|
||||
FROM invite_tokens i
|
||||
@@ -32,11 +32,11 @@ export class RegistrationInvitesService {
|
||||
}
|
||||
|
||||
/** Trips an admin can bind an invite to — id + title only, for the picker (#1402). */
|
||||
listTripsForInvite() {
|
||||
async listTripsForInvite() {
|
||||
return this.db.all('SELECT id, title FROM trips ORDER BY title COLLATE NOCASE ASC');
|
||||
}
|
||||
|
||||
createInvite(
|
||||
async createInvite(
|
||||
createdBy: number,
|
||||
data: { max_uses?: string | number; expires_in_days?: string | number; trip_id?: string | number | null },
|
||||
) {
|
||||
@@ -77,7 +77,7 @@ export class RegistrationInvitesService {
|
||||
return { invite, inviteId, uses, expiresInDays: data.expires_in_days ?? null, tripId };
|
||||
}
|
||||
|
||||
deleteInvite(id: string) {
|
||||
async deleteInvite(id: string) {
|
||||
const invite = this.db.get('SELECT id FROM invite_tokens WHERE id = ?', id);
|
||||
if (!invite) return { error: 'Invite not found', status: 404 };
|
||||
this.db.run('DELETE FROM invite_tokens WHERE id = ?', id);
|
||||
|
||||
@@ -33,16 +33,16 @@ import { setAuthCookie } from '../common/cookie';
|
||||
export class SessionRenewalInterceptor implements NestInterceptor {
|
||||
constructor(private readonly auth: AuthService) {}
|
||||
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<unknown>> {
|
||||
if (context.getType() === 'http') {
|
||||
const req = context.switchToHttp().getRequest<Request & { user?: { id: number } }>();
|
||||
const res = context.switchToHttp().getResponse<Response>();
|
||||
this.maybeRenew(req, res);
|
||||
await this.maybeRenew(req, res);
|
||||
}
|
||||
return next.handle();
|
||||
}
|
||||
|
||||
private maybeRenew(req: Request & { user?: { id: number } }, res: Response): void {
|
||||
private async maybeRenew(req: Request & { user?: { id: number } }, res: Response): Promise<void> {
|
||||
const cookieToken: string | undefined = (req as { cookies?: Record<string, string> }).cookies?.trek_session;
|
||||
if (!req.user || !cookieToken || res.headersSent) return;
|
||||
|
||||
@@ -53,7 +53,7 @@ export class SessionRenewalInterceptor implements NestInterceptor {
|
||||
const halfLife = claims.iat + (claims.exp - claims.iat) / 2;
|
||||
if (Date.now() / 1000 < halfLife) return;
|
||||
|
||||
const token = this.auth.generateToken(
|
||||
const token = await this.auth.generateToken(
|
||||
{ id: req.user.id, password_version: claims.pv ?? 0 },
|
||||
claims.remember,
|
||||
);
|
||||
|
||||
@@ -39,7 +39,7 @@ export class UserCleanupService {
|
||||
* Best-effort per table so a slimmed-down schema (some tests) can't fail the user
|
||||
* deletion itself.
|
||||
*/
|
||||
erasePluginUserData(userId: number): void {
|
||||
async erasePluginUserData(userId: number): Promise<void> {
|
||||
for (const table of ['plugin_user_config', 'plugin_oauth_tokens', 'plugin_oauth_state']) {
|
||||
try { this.db.run(`DELETE FROM ${table} WHERE user_id = ?`, userId); } catch { /* table absent (slim schema) */ }
|
||||
}
|
||||
@@ -81,7 +81,7 @@ export class UserCleanupService {
|
||||
async deleteUserCompletely(userId: number): Promise<void> {
|
||||
await this.uow.transactional(async () => {
|
||||
await this.cleanupUserReferences(userId);
|
||||
this.erasePluginUserData(userId);
|
||||
await this.erasePluginUserData(userId);
|
||||
this.db.run('DELETE FROM users WHERE id = ?', userId);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ export class UserProfileService {
|
||||
}
|
||||
|
||||
/** The three key columns plus the role that decides where a save lands. */
|
||||
private currentKeys(userId: number) {
|
||||
private async currentKeys(userId: number) {
|
||||
return this.db.get<Pick<User, 'role' | 'maps_api_key' | 'openweather_api_key' | 'unsplash_api_key' | 'amap_api_key'>>(
|
||||
'SELECT role, maps_api_key, openweather_api_key, unsplash_api_key, amap_api_key FROM users WHERE id = ?',
|
||||
userId
|
||||
@@ -128,7 +128,7 @@ export class UserProfileService {
|
||||
if (this.managed) {
|
||||
return { success: true, maps_api_key: null, managed_keys: ['maps_api_key'], changedKeys: [] };
|
||||
}
|
||||
const current = this.currentKeys(userId);
|
||||
const current = await this.currentKeys(userId);
|
||||
const isAdmin = current?.role === 'admin';
|
||||
const changedKeys = await this.changedKeyNames({ maps_api_key }, current, isAdmin);
|
||||
await this.uow.transactional(async () => {
|
||||
@@ -145,7 +145,7 @@ export class UserProfileService {
|
||||
const body = rawBody as { maps_api_key?: string; openweather_api_key?: string; unsplash_api_key?: string; amap_api_key?: string };
|
||||
const { blocked } = splitManagedKeys(body, this.managed);
|
||||
for (const key of blocked) delete body[key as keyof typeof body];
|
||||
const current = this.currentKeys(userId);
|
||||
const current = await this.currentKeys(userId);
|
||||
const isAdmin = current?.role === 'admin';
|
||||
const changedKeys = await this.changedKeyNames(body, current, isAdmin, blocked);
|
||||
|
||||
@@ -222,7 +222,7 @@ export class UserProfileService {
|
||||
|
||||
// Read before the write, so the comparison sees the old value; the role in
|
||||
// the same row decides whether the two instance-wide names travel with it.
|
||||
const current = this.currentKeys(userId);
|
||||
const current = await this.currentKeys(userId);
|
||||
const isAdmin = current?.role === 'admin';
|
||||
const changedKeys = keyLocked ? [] : await this.changedKeyNames(body, current, isAdmin, blocked);
|
||||
|
||||
@@ -322,7 +322,7 @@ export class UserProfileService {
|
||||
// User directory
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
listUsers(excludeUserId: number) {
|
||||
async listUsers(excludeUserId: number) {
|
||||
// The global user directory feeds the trip member-add / contributor pickers —
|
||||
// guests (#1362) are trip-scoped and must never be selectable here.
|
||||
const users = this.db.all<Pick<User, 'id' | 'username' | 'avatar'>>(
|
||||
|
||||
@@ -70,7 +70,7 @@ export interface WebauthnConfig {
|
||||
export class WebauthnConfigService {
|
||||
constructor(private readonly db: DatabaseService) {}
|
||||
|
||||
private setting(key: string): string | null {
|
||||
private async setting(key: string): Promise<string | null> {
|
||||
const raw = this.db.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', key)?.value;
|
||||
const trimmed = raw?.trim();
|
||||
return trimmed ? trimmed : null;
|
||||
@@ -81,10 +81,10 @@ export class WebauthnConfigService {
|
||||
* configured) — the feature then reports itself as "not configured" and stays
|
||||
* disabled so nobody can enrol a credential bound to the wrong origin.
|
||||
*/
|
||||
resolve(): WebauthnConfig | null {
|
||||
async resolve(): Promise<WebauthnConfig | null> {
|
||||
// 1. Explicit operator config always wins.
|
||||
const explicitRpId = (readEnv().webauthn.rpId || this.setting('webauthn_rp_id'))?.trim() || null;
|
||||
const explicitOrigins = (readEnv().webauthn.origins || this.setting('webauthn_origins') || '')
|
||||
const explicitRpId = (readEnv().webauthn.rpId || (await this.setting('webauthn_rp_id')))?.trim() || null;
|
||||
const explicitOrigins = (readEnv().webauthn.origins || (await this.setting('webauthn_origins')) || '')
|
||||
.split(',')
|
||||
// The lookbehind matches only the first slash of the trailing run. Without it the
|
||||
// engine retries from every slash, which is quadratic on a slash-heavy value.
|
||||
@@ -118,7 +118,7 @@ export class WebauthnConfigService {
|
||||
}
|
||||
|
||||
/** True when a usable RP ID resolves for this deployment (exposed as a pure boolean on app-config). */
|
||||
isConfigured(): boolean {
|
||||
return this.resolve() !== null;
|
||||
async isConfigured(): Promise<boolean> {
|
||||
return (await this.resolve()) !== null;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user