diff --git a/src/client/ts/main.ts b/src/client/ts/main.ts index d41b44c..e15f94c 100644 --- a/src/client/ts/main.ts +++ b/src/client/ts/main.ts @@ -284,7 +284,7 @@ async function syncStatusAndRender(): Promise { authenticated: boolean; safeMode?: boolean; elevatedUntil?: number | null; - vaultState: ClientState['vaultState']; + vaultState?: ClientState['vaultState']; vaultRuntimeReady?: boolean; isPanicLocked?: boolean; defaultMobileSafeMode: boolean; @@ -295,8 +295,8 @@ async function syncStatusAndRender(): Promise { state.bootstrapped = status.bootstrapped; state.authenticated = status.authenticated; - state.vaultState = status.vaultState; - state.vaultRuntimeReady = status.vaultRuntimeReady ?? status.vaultState === 'unlocked'; + state.vaultState = status.vaultState ?? 'locked'; + state.vaultRuntimeReady = status.vaultRuntimeReady ?? false; state.isPanicLocked = Boolean(status.isPanicLocked); state.defaultMobileSafeMode = status.defaultMobileSafeMode; state.elevatedUntil = status.elevatedUntil ?? null; diff --git a/src/client/ts/state.ts b/src/client/ts/state.ts index f44aac5..9224ff1 100644 --- a/src/client/ts/state.ts +++ b/src/client/ts/state.ts @@ -85,13 +85,13 @@ export interface ClientAuthRequirements { requireTotpOnLogin: boolean; passwordMode: 'any' | 'all'; passwordCount: number; - passwordLabels: Array<{ id: string; label: string }>; + passwordLabels?: Array<{ id: string; label: string }>; totpMode: 'any' | 'all'; totpCount: number; - totpLabels: Array<{ id: string; label: string }>; + totpLabels?: Array<{ id: string; label: string }>; passkeyCount: number; - stepUpPolicy: ClientSecuritySettings['stepUpPolicy']; - stepUpMethod: ClientSecuritySettings['stepUpMethod']; + stepUpPolicy?: ClientSecuritySettings['stepUpPolicy']; + stepUpMethod?: ClientSecuritySettings['stepUpMethod']; } export interface ClientState { diff --git a/src/client/ts/views/auth-view.ts b/src/client/ts/views/auth-view.ts index d183e36..6dab298 100644 --- a/src/client/ts/views/auth-view.ts +++ b/src/client/ts/views/auth-view.ts @@ -7,9 +7,11 @@ import { import { getPasskeyAssertion, isWebAuthnSupported } from '../webauthn.js'; interface BootstrapData { + bootstrapToken?: string; secretBase32: string; otpauthUri: string; qrSvg: string; + qrDataUri?: string; } export async function renderAuthView( @@ -87,9 +89,11 @@ export async function renderAuthView( }); let secretBase32 = ''; + let bootstrapToken = ''; try { const data = await apiFetch('/api/auth/bootstrap'); secretBase32 = data.secretBase32; + bootstrapToken = data.bootstrapToken ?? ''; const doc = new DOMParser().parseFromString(data.qrSvg, 'image/svg+xml'); if (doc.documentElement.nodeName === 'svg') { qrContainer.append(document.importNode(doc.documentElement, true)); @@ -134,6 +138,7 @@ export async function renderAuthView( password: passInput.value, totpCode: codeInput.value.trim(), secretBase32, + ...(bootstrapToken ? { bootstrapToken } : {}), initialSafeMode, securityPreset: presetSelect.value, }, @@ -283,7 +288,7 @@ export async function renderAuthView( form.append(el('label', { for: 'login-username' }, 'Username'), userInput); const passwordInputs: HTMLInputElement[] = []; - const pwCount = pwMode === 'all' ? Math.max(1, pwLabels.length) : 1; + const pwCount = Math.max(1, reqs?.passwordCount ?? pwLabels.length); for (let i = 0; i < pwCount; i++) { const labelText = pwMode === 'all' ? `Password — ${pwLabels[i]?.label ?? `#${i + 1}`}` : 'Password'; @@ -310,7 +315,7 @@ export async function renderAuthView( const codeInputs: HTMLInputElement[] = []; if (requireTotp) { - const totpCount = totpMode === 'all' ? Math.max(1, totpLabels.length) : 1; + const totpCount = Math.max(1, reqs?.totpCount ?? totpLabels.length); for (let i = 0; i < totpCount; i++) { const labelText = totpMode === 'all' diff --git a/src/client/ts/views/settings-view.ts b/src/client/ts/views/settings-view.ts index 4830224..2524ecc 100644 --- a/src/client/ts/views/settings-view.ts +++ b/src/client/ts/views/settings-view.ts @@ -837,7 +837,10 @@ export async function renderSettingsView( dlBackupBtn.addEventListener('click', async () => { bMsg.textContent = ''; try { - const res = await apiFetch<{ bundle: unknown }>('/api/auth/recovery-backup/export'); + const res = await apiFetch<{ bundle: unknown }>('/api/auth/recovery-backup/export', { + method: 'POST', + body: {}, + }); const blob = new Blob([`${JSON.stringify(res.bundle, null, 2)}\n`], { type: 'application/json', }); diff --git a/src/server/api/routes/auth.routes.ts b/src/server/api/routes/auth.routes.ts index 4f9fe52..44dc5bf 100644 --- a/src/server/api/routes/auth.routes.ts +++ b/src/server/api/routes/auth.routes.ts @@ -1,13 +1,19 @@ -import { Router, type Request, type Response } from 'express'; +import { Router, type NextFunction, type Request, type Response } from 'express'; import { z } from 'zod'; import type { AuthenticationResponseJSON, RegistrationResponseJSON, } from '@simplewebauthn/server'; +import { SecuritySettingsSchema } from '../../../shared/schemas/settings.schema.js'; import type { ConfigManager } from '../../config/config-manager.js'; import type { AuditService } from '../../security/audit.js'; -import { SESSION_COOKIE_NAME, type AuthService } from '../../security/auth.js'; import { + AuthOverloadError, + SESSION_COOKIE_NAME, + type AuthService, +} from '../../security/auth.js'; +import { + asyncHandler, createStepUpGuard, enforceSafeMode, extractCookies, @@ -28,6 +34,8 @@ export interface AuthRouterDeps { recoveryStore: EmergencyRecoveryService; rateLimiter: RateLimiter; trustCloudflare: boolean; + webauthnRpId?: string; + webauthnOrigins?: string[]; } function isSecureCookie(req: Request, trustCloudflare: boolean): boolean { @@ -44,9 +52,10 @@ function setAuthCookies( sessionToken: string, csrfToken: string, trustCloudflare: boolean, + sessionTtlHours = 168, ): void { const secure = isSecureCookie(req, trustCloudflare); - const maxAge = 7 * 24 * 60 * 60 * 1000; + const maxAge = Math.max(1, sessionTtlHours) * 60 * 60 * 1000; res.cookie(SESSION_COOKIE_NAME, sessionToken, { httpOnly: true, sameSite: 'strict', @@ -76,6 +85,8 @@ class WebAuthnRpError extends Error { function resolveWebAuthnRp( req: Request, trustCloudflare: boolean, + configuredRpId?: string, + configuredOrigins?: string[], ): { rpID: string; expectedOrigin: string } { const originHeader = typeof req.headers.origin === 'string' && req.headers.origin.trim() @@ -92,10 +103,35 @@ function resolveWebAuthnRp( throw new WebAuthnRpError('Invalid Origin header for WebAuthn request'); } - const rpID = parsed.hostname; - if (/^\d+\.\d+\.\d+\.\d+$/.test(rpID) || rpID.includes(':')) { + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + throw new WebAuthnRpError('WebAuthn Origin must use http or https'); + } + + if (configuredOrigins && configuredOrigins.length > 0) { + if (!configuredOrigins.includes(parsed.origin)) { + throw new WebAuthnRpError( + `Origin "${parsed.origin}" is not listed in GCOORD_WEBAUTHN_ORIGINS`, + ); + } + } else if (originHeader && parsed.host !== hostHeader) { + throw new WebAuthnRpError('WebAuthn Origin host does not match Request Host'); + } + + const hostname = parsed.hostname; + if (/^\d+\.\d+\.\d+\.\d+$/.test(hostname) || hostname.includes(':')) { throw new WebAuthnRpError( - `WebAuthn Passkeys require "localhost" or an HTTPS domain name (IP address "${rpID}" is rejected by browsers).`, + `WebAuthn Passkeys require "localhost" or an HTTPS domain name (IP address "${hostname}" is rejected by browsers).`, + ); + } + + const rpID = configuredRpId || hostname; + if ( + configuredRpId && + hostname !== configuredRpId && + !hostname.endsWith(`.${configuredRpId}`) + ) { + throw new WebAuthnRpError( + `Hostname "${hostname}" does not match GCOORD_WEBAUTHN_RP_ID "${configuredRpId}"`, ); } @@ -115,6 +151,8 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { recoveryStore, rateLimiter, trustCloudflare, + webauthnRpId, + webauthnOrigins, } = deps; const stepUpGuard = createStepUpGuard( @@ -133,11 +171,16 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { res.json({ bootstrapped, authenticated: false, - vaultState: vaultService.state, - vaultRuntimeReady: vaultService.isRuntimeReady, defaultMobileSafeMode: settings.defaultMobileSafeMode, theme: settings.theme, - authRequirements, + authRequirements: { + requireTotpOnLogin: authRequirements.requireTotpOnLogin, + passwordMode: authRequirements.passwordMode, + passwordCount: authRequirements.passwordCount, + totpMode: authRequirements.totpMode, + totpCount: authRequirements.totpCount, + passkeyCount: authRequirements.passkeyCount, + }, }); return; } @@ -148,196 +191,231 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { safeMode: session.safeMode, elevatedUntil: session.elevatedUntil, vaultState: vaultService.state, + sealState: vaultService.sealState, vaultRuntimeReady: vaultService.isRuntimeReady, isPanicLocked: vaultService.isPanicLocked, defaultMobileSafeMode: settings.defaultMobileSafeMode, theme: settings.theme, security: settings.security, + runtime: settings.runtime, authRequirements, }); }); - router.get('/bootstrap', async (req, res) => { - if (authService.isBootstrapped()) { - res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); - return; - } - const username = - typeof req.query.username === 'string' && req.query.username.trim() - ? req.query.username.trim() - : 'admin'; - const data = await authService.beginBootstrap(username); - res.json(data); - }); + router.get( + '/bootstrap', + asyncHandler(async (req, res) => { + if (authService.isBootstrapped()) { + res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); + return; + } + const rawUser = + typeof req.query.username === 'string' && req.query.username.trim() + ? req.query.username.trim().slice(0, 64) + : 'admin'; + const data = await authService.beginBootstrap(rawUser); + res.json(data); + }), + ); - router.post('/bootstrap', async (req, res) => { - if (authService.isBootstrapped()) { - res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); - return; - } - const ip = req.clientIp ?? 'unknown'; - const rate = rateLimiter.check('bootstrap', ip); - if (!rate.allowed) { - res.setHeader('Retry-After', String(rate.retryAfterSec)); - res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); - return; - } - - const bodySchema = z.object({ - username: z.string().min(2).max(64).default('admin'), - password: z.string().min(10).max(256), - totpCode: z.string().regex(/^\d{6}$/, 'TOTP code must be 6 digits'), - secretBase32: z.string().optional(), - initialSafeMode: z.boolean().optional(), - securityPreset: z.enum(['relaxed', 'balanced', 'strict']).optional(), - }); - const parsed = bodySchema.safeParse(req.body); - if (!parsed.success) { - rateLimiter.recordFailure('bootstrap', ip); - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } - - try { - if (parsed.data.securityPreset) { - const cur = configManager.getSettings(); - const presetSecurity = - parsed.data.securityPreset === 'relaxed' - ? { - ...cur.security, - requireTotpOnLogin: false, - stepUpPolicy: 'off' as const, - stepUpMethod: 'password' as const, - elevateOnLogin: true, - keepElevationOnSafeMode: true, - } - : parsed.data.securityPreset === 'strict' - ? { - ...cur.security, - requireTotpOnLogin: true, - stepUpPolicy: '5m' as const, - stepUpMethod: 'totp' as const, - elevateOnLogin: false, - keepElevationOnSafeMode: false, - } - : cur.security; - - configManager.saveConfigText( - 'settings.json', - JSON.stringify({ ...cur, security: presetSecurity }, null, 2), - 'ui', - `Bootstrap preset: ${parsed.data.securityPreset}`, - ); + router.post( + '/bootstrap', + asyncHandler(async (req, res) => { + if (authService.isBootstrapped()) { + res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); + return; + } + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('bootstrap', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; } - const result = await authService.completeBootstrap({ - ...parsed.data, - ip, - userAgent: String(req.headers['user-agent'] ?? 'unknown'), - }); - rateLimiter.recordSuccess('bootstrap', ip); - setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare); - auditService.log({ - action: 'auth.bootstrap', - actorIp: ip, - sessionIdHash: result.session.idHash, - target: parsed.data.username, - status: 'ok', - }); - res.status(201).json({ - authenticated: true, - csrfToken: result.csrfToken, - recoveryCodes: result.recoveryCodes, - safeMode: result.session.safeMode, - elevatedUntil: result.session.elevatedUntil, - vaultState: vaultService.state, - vaultRuntimeReady: vaultService.isRuntimeReady, - }); - } catch (err) { - rateLimiter.recordFailure('bootstrap', ip); - auditService.log({ - action: 'auth.bootstrap', - actorIp: ip, - status: 'error', - details: err instanceof Error ? err.message : 'Bootstrap failed', - }); - res.status(400).json({ - error: 'BOOTSTRAP_FAILED', - message: err instanceof Error ? err.message : 'Bootstrap failed', - }); - } - }); - - router.post('/login', async (req, res) => { - if (!authService.isBootstrapped()) { - res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); - return; - } - const ip = req.clientIp ?? 'unknown'; - const rate = rateLimiter.check('login', ip); - if (!rate.allowed) { - res.setHeader('Retry-After', String(rate.retryAfterSec)); - res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); - return; - } - - const bodySchema = z - .object({ - username: z.string().min(1).optional(), - password: z.string().min(1).optional(), - passwords: z.array(z.string().min(1)).optional(), - code: z.string().max(32).optional(), - codes: z.array(z.string().max(32)).optional(), + const bodySchema = z.object({ + username: z.string().trim().min(2).max(64).default('admin'), + password: z.string().min(10).max(256), + totpCode: z.string().regex(/^\d{6}$/, 'TOTP code must be 6 digits'), + secretBase32: z.string().max(128).optional(), + bootstrapToken: z.string().min(16).max(128).optional(), initialSafeMode: z.boolean().optional(), - }) - .refine( - (b) => Boolean(b.password || (b.passwords && b.passwords.length > 0)), - 'Password is required', - ); - const parsed = bodySchema.safeParse(req.body); - if (!parsed.success) { - rateLimiter.recordFailure('login', ip); - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } - - const result = await authService.login({ - ...parsed.data, - ip, - userAgent: String(req.headers['user-agent'] ?? 'unknown'), - }); - - if (!result) { - rateLimiter.recordFailure('login', ip); - auditService.log({ - action: 'auth.login', - actorIp: ip, - target: parsed.data.username ?? 'admin', - status: 'denied', + securityPreset: z.enum(['relaxed', 'balanced', 'strict']).optional(), }); - res.status(401).json({ error: 'INVALID_CREDENTIALS' }); - return; - } + const parsed = bodySchema.safeParse(req.body); + if (!parsed.success) { + rateLimiter.recordFailure('bootstrap', ip); + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } - rateLimiter.recordSuccess('login', ip); - setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare); - auditService.log({ - action: 'auth.login', - actorIp: ip, - sessionIdHash: result.session.idHash, - target: parsed.data.username ?? 'admin', - status: 'ok', - }); + try { + const result = await authService.completeBootstrap({ + ...parsed.data, + ip, + userAgent: String(req.headers['user-agent'] ?? 'unknown'), + }); - res.json({ - authenticated: true, - csrfToken: result.csrfToken, - safeMode: result.session.safeMode, - elevatedUntil: result.session.elevatedUntil, - vaultState: vaultService.state, - vaultRuntimeReady: vaultService.isRuntimeReady, - }); - }); + if (parsed.data.securityPreset) { + const cur = configManager.getSettings(); + const presetSecurity = + parsed.data.securityPreset === 'relaxed' + ? { + ...cur.security, + requireTotpOnLogin: false, + stepUpPolicy: 'off' as const, + stepUpMethod: 'password' as const, + elevateOnLogin: true, + keepElevationOnSafeMode: true, + } + : parsed.data.securityPreset === 'strict' + ? { + ...cur.security, + requireTotpOnLogin: true, + stepUpPolicy: '5m' as const, + stepUpMethod: 'totp' as const, + elevateOnLogin: false, + keepElevationOnSafeMode: false, + } + : cur.security; + + configManager.saveConfigText( + 'settings.json', + JSON.stringify({ ...cur, security: presetSecurity }, null, 2), + 'ui', + `Bootstrap preset: ${parsed.data.securityPreset}`, + ); + authService.syncRecovery({ + newRecoveryCodes: result.recoveryCodes, + snapshotReason: 'bootstrap-preset', + }); + } + + const ttlHours = configManager.getSettings().security.sessionTtlHours; + rateLimiter.recordSuccess('bootstrap', ip); + setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare, ttlHours); + auditService.log({ + action: 'auth.bootstrap', + actorIp: ip, + sessionIdHash: result.session.idHash, + target: parsed.data.username, + status: 'ok', + }); + res.status(201).json({ + authenticated: true, + csrfToken: result.csrfToken, + recoveryCodes: result.recoveryCodes, + safeMode: result.session.safeMode, + elevatedUntil: result.session.elevatedUntil, + vaultState: vaultService.state, + vaultRuntimeReady: vaultService.isRuntimeReady, + }); + } catch (err) { + if (err instanceof AuthOverloadError) throw err; + rateLimiter.recordFailure('bootstrap', ip); + auditService.log({ + action: 'auth.bootstrap', + actorIp: ip, + status: 'error', + details: err instanceof Error ? err.message : 'Bootstrap failed', + }); + res.status(400).json({ + error: 'BOOTSTRAP_FAILED', + message: err instanceof Error ? err.message : 'Bootstrap failed', + }); + } + }), + ); + + router.post( + '/login', + asyncHandler(async (req, res) => { + if (!authService.isBootstrapped()) { + res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); + return; + } + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('login', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; + } + if (!rateLimiter.acquireInFlight('login', ip, 2)) { + res.setHeader('Retry-After', '2'); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: 2 }); + return; + } + + try { + const bodySchema = z + .object({ + username: z.string().trim().min(1).max(64), + password: z.string().min(1).max(256).optional(), + passwords: z.array(z.string().min(1).max(256)).max(16).optional(), + code: z.string().max(64).optional(), + codes: z.array(z.string().max(64)).max(16).optional(), + initialSafeMode: z.boolean().optional(), + }) + .refine( + (b) => Boolean(b.password || (b.passwords && b.passwords.length > 0)), + 'Password is required', + ); + const parsed = bodySchema.safeParse(req.body); + if (!parsed.success) { + rateLimiter.recordFailure('login', ip); + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + + const result = await authService.login({ + ...parsed.data, + ip, + userAgent: String(req.headers['user-agent'] ?? 'unknown'), + }); + + if (!result) { + const failState = rateLimiter.recordFailure('login', ip); + if (failState.lockedUntil > 0 || failState.globalTriggered) { + authService.emitSecurityEvent('auth.lockout', ip, { + failures: failState.failures, + globalTriggered: failState.globalTriggered, + }); + } + auditService.log({ + action: 'auth.login', + actorIp: ip, + target: parsed.data.username, + status: 'denied', + }); + res.status(401).json({ error: 'INVALID_CREDENTIALS' }); + return; + } + + const ttlHours = configManager.getSettings().security.sessionTtlHours; + rateLimiter.recordSuccess('login', ip); + setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare, ttlHours); + auditService.log({ + action: 'auth.login', + actorIp: ip, + sessionIdHash: result.session.idHash, + target: parsed.data.username, + status: 'ok', + }); + + res.json({ + authenticated: true, + csrfToken: result.csrfToken, + safeMode: result.session.safeMode, + elevatedUntil: result.session.elevatedUntil, + vaultState: vaultService.state, + vaultRuntimeReady: vaultService.isRuntimeReady, + }); + } finally { + rateLimiter.releaseInFlight('login', ip); + } + }), + ); // Exempt from enforceSafeMode router.post('/logout', requireAuth(authService), requireCsrf, (req, res) => { @@ -383,7 +461,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { requireAuth(authService), requireCsrf, enforceSafeMode, - async (req, res) => { + asyncHandler(async (req, res) => { const ip = req.clientIp ?? 'unknown'; const rate = rateLimiter.check('step-up', ip); if (!rate.allowed) { @@ -394,10 +472,10 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { const parsed = z .object({ - code: z.string().optional(), - codes: z.array(z.string()).optional(), - password: z.string().optional(), - passwords: z.array(z.string()).optional(), + code: z.string().max(64).optional(), + codes: z.array(z.string().max(64)).max(16).optional(), + password: z.string().max(256).optional(), + passwords: z.array(z.string().max(256)).max(16).optional(), }) .safeParse(req.body ?? {}); if (!parsed.success) { @@ -407,7 +485,12 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { const outcome = await authService.stepUp(req.authSession!.idHash, parsed.data); if (!outcome.ok) { - rateLimiter.recordFailure('step-up', ip); + const failState = rateLimiter.recordFailure('step-up', ip); + if (failState.lockedUntil > 0) { + authService.emitSecurityEvent('auth.step_up_lockout', ip, { + failures: failState.failures, + }); + } auditService.log({ action: 'auth.step_up', actorIp: ip, @@ -430,7 +513,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { status: 'ok', }); res.json({ elevatedUntil: outcome.elevatedUntil }); - }, + }), ); router.post('/drop-elevation', requireAuth(authService), requireCsrf, (req, res) => { @@ -627,7 +710,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { requireCsrf, enforceSafeMode, stepUpGuard, - async (req, res) => { + asyncHandler(async (req, res) => { const parsed = z .object({ label: z.string().min(1).max(64).default('Passkey') }) .safeParse(req.body ?? {}); @@ -636,7 +719,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { return; } try { - const rp = resolveWebAuthnRp(req, trustCloudflare); + const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins); const data = await authService.beginPasskeyRegistration({ label: parsed.data.label, ...rp, @@ -648,7 +731,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { message: err instanceof Error ? err.message : 'Unable to start passkey registration', }); } - }, + }), ); router.post( @@ -657,10 +740,10 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { requireCsrf, enforceSafeMode, stepUpGuard, - async (req, res) => { + asyncHandler(async (req, res) => { const parsed = z .object({ - challengeId: z.string().min(1), + challengeId: z.string().min(1).max(128), response: z.record(z.unknown()), }) .safeParse(req.body ?? {}); @@ -687,7 +770,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { message: err instanceof Error ? err.message : 'Unable to verify passkey registration', }); } - }, + }), ); router.delete( @@ -721,102 +804,115 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { }, ); - router.post('/passkeys/login/options', async (req, res) => { - if (!authService.isBootstrapped()) { - res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); - return; - } - const ip = req.clientIp ?? 'unknown'; - const rate = rateLimiter.check('login', ip); - if (!rate.allowed) { - res.setHeader('Retry-After', String(rate.retryAfterSec)); - res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); - return; - } - try { - const rp = resolveWebAuthnRp(req, trustCloudflare); - const data = await authService.beginPasskeyAuthentication({ - purpose: 'login', - ...rp, + router.post( + '/passkeys/login/options', + asyncHandler(async (req, res) => { + if (!authService.isBootstrapped()) { + res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); + return; + } + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('login', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; + } + try { + const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins); + const data = await authService.beginPasskeyAuthentication({ + purpose: 'login', + ...rp, + }); + res.json(data); + } catch (err) { + res.status(400).json({ + error: err instanceof WebAuthnRpError ? err.code : 'PASSKEY_LOGIN_OPTIONS_FAILED', + message: err instanceof Error ? err.message : 'No passkeys available', + }); + } + }), + ); + + router.post( + '/passkeys/login/verify', + asyncHandler(async (req, res) => { + if (!authService.isBootstrapped()) { + res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); + return; + } + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('login', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; + } + + const parsed = z + .object({ + challengeId: z.string().min(1).max(128), + response: z.record(z.unknown()), + initialSafeMode: z.boolean().optional(), + }) + .safeParse(req.body ?? {}); + if (!parsed.success) { + rateLimiter.recordFailure('login', ip); + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + + const result = await authService.loginWithPasskey({ + challengeId: parsed.data.challengeId, + response: parsed.data.response as unknown as AuthenticationResponseJSON, + ip, + userAgent: String(req.headers['user-agent'] ?? 'unknown'), + initialSafeMode: parsed.data.initialSafeMode, }); - res.json(data); - } catch (err) { - res.status(400).json({ - error: err instanceof WebAuthnRpError ? err.code : 'PASSKEY_LOGIN_OPTIONS_FAILED', - message: err instanceof Error ? err.message : 'No passkeys available', - }); - } - }); + if (!result) { + const failState = rateLimiter.recordFailure('login', ip); + if (failState.lockedUntil > 0 || failState.globalTriggered) { + authService.emitSecurityEvent('auth.lockout', ip, { + failures: failState.failures, + globalTriggered: failState.globalTriggered, + }); + } + auditService.log({ + action: 'auth.passkey_login', + actorIp: ip, + status: 'denied', + }); + res.status(401).json({ error: 'INVALID_PASSKEY_ASSERTION' }); + return; + } - router.post('/passkeys/login/verify', async (req, res) => { - if (!authService.isBootstrapped()) { - res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); - return; - } - const ip = req.clientIp ?? 'unknown'; - const rate = rateLimiter.check('login', ip); - if (!rate.allowed) { - res.setHeader('Retry-After', String(rate.retryAfterSec)); - res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); - return; - } - - const parsed = z - .object({ - challengeId: z.string().min(1), - response: z.record(z.unknown()), - initialSafeMode: z.boolean().optional(), - }) - .safeParse(req.body ?? {}); - if (!parsed.success) { - rateLimiter.recordFailure('login', ip); - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } - - const result = await authService.loginWithPasskey({ - challengeId: parsed.data.challengeId, - response: parsed.data.response as unknown as AuthenticationResponseJSON, - ip, - userAgent: String(req.headers['user-agent'] ?? 'unknown'), - initialSafeMode: parsed.data.initialSafeMode, - }); - if (!result) { - rateLimiter.recordFailure('login', ip); + const ttlHours = configManager.getSettings().security.sessionTtlHours; + rateLimiter.recordSuccess('login', ip); + setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare, ttlHours); auditService.log({ action: 'auth.passkey_login', actorIp: ip, - status: 'denied', + sessionIdHash: result.session.idHash, + status: 'ok', }); - res.status(401).json({ error: 'INVALID_PASSKEY_ASSERTION' }); - return; - } - rateLimiter.recordSuccess('login', ip); - setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare); - auditService.log({ - action: 'auth.passkey_login', - actorIp: ip, - sessionIdHash: result.session.idHash, - status: 'ok', - }); - - res.json({ - authenticated: true, - csrfToken: result.csrfToken, - safeMode: result.session.safeMode, - elevatedUntil: result.session.elevatedUntil, - vaultState: vaultService.state, - vaultRuntimeReady: vaultService.isRuntimeReady, - }); - }); + res.json({ + authenticated: true, + csrfToken: result.csrfToken, + safeMode: result.session.safeMode, + elevatedUntil: result.session.elevatedUntil, + vaultState: vaultService.state, + vaultRuntimeReady: vaultService.isRuntimeReady, + }); + }), + ); router.post( '/passkeys/step-up/options', requireAuth(authService), requireCsrf, enforceSafeMode, - async (req, res) => { + asyncHandler(async (req, res) => { const ip = req.clientIp ?? 'unknown'; const rate = rateLimiter.check('step-up', ip); if (!rate.allowed) { @@ -825,7 +921,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { return; } try { - const rp = resolveWebAuthnRp(req, trustCloudflare); + const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins); const data = await authService.beginPasskeyAuthentication({ purpose: 'stepup', sessionIdHash: req.authSession!.idHash, @@ -838,7 +934,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { message: err instanceof Error ? err.message : 'Unable to start passkey verification', }); } - }, + }), ); router.post( @@ -846,7 +942,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { requireAuth(authService), requireCsrf, enforceSafeMode, - async (req, res) => { + asyncHandler(async (req, res) => { const ip = req.clientIp ?? 'unknown'; const rate = rateLimiter.check('step-up', ip); if (!rate.allowed) { @@ -856,7 +952,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { } const parsed = z .object({ - challengeId: z.string().min(1), + challengeId: z.string().min(1).max(128), response: z.record(z.unknown()), }) .safeParse(req.body ?? {}); @@ -894,6 +990,46 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { status: 'ok', }); res.json({ elevatedUntil: outcome.elevatedUntil }); + }), + ); + + router.put( + '/security-policy', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + (req, res) => { + const cur = configManager.getSettings(); + const bodyObj = + typeof req.body === 'object' && req.body !== null && !Array.isArray(req.body) + ? (req.body as Record) + : null; + if (!bodyObj) { + res.status(400).json({ error: 'VALIDATION_ERROR', message: 'Expected JSON object' }); + return; + } + const parsed = SecuritySettingsSchema.safeParse({ + ...cur.security, + ...bodyObj, + }); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + configManager.saveConfigText( + 'settings.json', + JSON.stringify({ ...cur, security: parsed.data }, null, 2), + 'ui', + 'Updated security policy via /api/auth/security-policy', + ); + auditService.log({ + action: 'auth.security_policy_update', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + status: 'ok', + }); + res.json({ security: parsed.data }); }, ); @@ -922,9 +1058,11 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { }, ); - router.get( + router.post( '/recovery-backup/export', requireAuth(authService), + requireCsrf, + enforceSafeMode, stepUpGuard, (req, res) => { const settings = configManager.getSettings(); @@ -1032,5 +1170,14 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { }, ); + router.use((err: unknown, _req: Request, res: Response, next: NextFunction) => { + if (err instanceof AuthOverloadError) { + res.setHeader('Retry-After', '2'); + res.status(503).json({ error: err.code, message: err.message }); + return; + } + next(err); + }); + return router; } diff --git a/src/server/api/ws-hub.ts b/src/server/api/ws-hub.ts index abfa4ff..42f80e7 100644 --- a/src/server/api/ws-hub.ts +++ b/src/server/api/ws-hub.ts @@ -5,10 +5,18 @@ import { ClientWsFrameSchema, type ServerWsFrame, } from '../../shared/ws-protocol.js'; -import { SESSION_COOKIE_NAME, type AuthService } from '../security/auth.js'; +import { + SESSION_COOKIE_NAME, + type AuthService, + type AuthSession, +} from '../security/auth.js'; import { extractCookies } from '../security/guards.js'; import type { VaultService } from '../security/vault.js'; +const WS_MAX_PAYLOAD_BYTES = 128 * 1024; +const WS_SOFT_BACKPRESSURE_BYTES = 1024 * 1024; +const WS_HARD_BACKPRESSURE_BYTES = 4 * 1024 * 1024; + interface WsClientMeta { ws: WebSocket; sessionToken: string; @@ -42,25 +50,41 @@ export interface WsAiHandlers { } export class WsHub { - private readonly wss = new WebSocketServer({ noServer: true }); + private readonly wss = new WebSocketServer({ + noServer: true, + maxPayload: WS_MAX_PAYLOAD_BYTES, + }); private readonly clients = new Set(); private readonly pingTimer: NodeJS.Timeout; private readonly upgradeHandlers: Array<{ prefix: string; handler: WsUpgradeHandler }> = []; private readonly subscribeListeners = new Set(); private ptyHandlers: WsPtyHandlers | null = null; private aiHandlers: WsAiHandlers | null = null; + private readonly trustCloudflare: boolean; constructor( httpServer: HttpServer, private readonly authService: AuthService, private readonly vaultService: VaultService, + options: { trustCloudflare?: boolean } = {}, ) { + this.trustCloudflare = Boolean(options.trustCloudflare); httpServer.on('upgrade', (req, socket, head) => { this.handleUpgrade(req, socket, head); }); this.pingTimer = setInterval(() => { for (const client of this.clients) { + const session = this.authService.getSessionByToken(client.sessionToken); + if (!session) { + try { + client.ws.close(4001, 'Session expired'); + } catch { + client.ws.terminate(); + } + this.clients.delete(client); + continue; + } if (!client.alive) { client.ws.terminate(); this.clients.delete(client); @@ -73,6 +97,24 @@ export class WsHub { this.pingTimer.unref(); } + disconnectSessions(idHashes: string[]): void { + if (idHashes.length === 0) return; + const targetSet = new Set(idHashes); + for (const client of this.clients) { + if (!targetSet.has(client.sessionIdHash)) continue; + try { + if (client.ws.readyState === WebSocket.OPEN) { + client.ws.close(4001, 'Session revoked'); + } else { + client.ws.terminate(); + } + } catch { + // Ignore close errors + } + this.clients.delete(client); + } + } + registerUpgradeHandler(prefix: string, handler: WsUpgradeHandler): void { this.upgradeHandlers.push({ prefix, handler }); } @@ -118,21 +160,18 @@ export class WsHub { broadcastAll(frame: ServerWsFrame): void { const text = JSON.stringify(frame); + const critical = frame.type === 'security:panic-lock' || frame.type === 'vault:state'; for (const client of this.clients) { - if (client.ws.readyState === WebSocket.OPEN) { - client.ws.send(text); - } + this.safeSendRaw(client, text, critical); } } broadcastChannel(channel: string, frame: ServerWsFrame): void { const text = JSON.stringify(frame); + const critical = frame.type === 'pty:exit' || frame.type === 'error'; for (const client of this.clients) { - if ( - client.ws.readyState === WebSocket.OPEN && - (client.channels.has(channel) || client.channels.has('*')) - ) { - client.ws.send(text); + if (client.channels.has(channel)) { + this.safeSendRaw(client, text, critical); } } } @@ -155,13 +194,29 @@ export class WsHub { return; } - // Validate Origin when provided by browsers to block cross-site WS hijacking + const cookies = extractCookies(req.headers.cookie); + const token = cookies[SESSION_COOKIE_NAME]; + const session = this.authService.getSessionByToken(token); + if (!session || !token) { + socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); + socket.destroy(); + return; + } + + // Validate Origin strictly when present (browsers always send Origin) to block CSWSH const origin = req.headers.origin; const host = req.headers.host; - if (origin && host) { + if (origin) { try { const originUrl = new URL(origin); - if (originUrl.host !== host) { + const validScheme = + originUrl.protocol === 'http:' || originUrl.protocol === 'https:'; + const isHttpsReq = Boolean( + (req.socket as { encrypted?: boolean }).encrypted || + (this.trustCloudflare && req.headers['x-forwarded-proto'] === 'https'), + ); + const expectedScheme = isHttpsReq ? 'https:' : 'http:'; + if (!validScheme || !host || originUrl.host !== host || originUrl.protocol !== expectedScheme) { socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); socket.destroy(); return; @@ -173,15 +228,6 @@ export class WsHub { } } - const cookies = extractCookies(req.headers.cookie); - const token = cookies[SESSION_COOKIE_NAME]; - const session = this.authService.getSessionByToken(token); - if (!session || !token) { - socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); - socket.destroy(); - return; - } - this.wss.handleUpgrade(req, socket, head, (ws) => { const meta: WsClientMeta = { ws, @@ -193,13 +239,17 @@ export class WsHub { }; this.clients.add(meta); - this.sendFrame(ws, { - type: 'hello', - vaultState: this.vaultService.state, - vaultRuntimeReady: this.vaultService.isRuntimeReady, - safeMode: session.safeMode, - elevatedUntil: session.elevatedUntil, - }); + this.sendFrame( + ws, + { + type: 'hello', + vaultState: this.vaultService.state, + vaultRuntimeReady: this.vaultService.isRuntimeReady, + safeMode: session.safeMode, + elevatedUntil: session.elevatedUntil, + }, + true, + ); ws.on('pong', () => { meta.alive = true; @@ -219,40 +269,69 @@ export class WsHub { }); } + private ensureActiveSession(meta: WsClientMeta): AuthSession | null { + const latestSession = this.authService.getSessionByToken(meta.sessionToken); + if (!latestSession) { + try { + meta.ws.close(4001, 'Session expired'); + } catch { + meta.ws.terminate(); + } + this.clients.delete(meta); + return null; + } + return latestSession; + } + private onMessage(meta: WsClientMeta, raw: unknown): void { let parsedJson: unknown; try { const text = typeof raw === 'string' ? raw : Buffer.from(raw as Buffer).toString('utf8'); parsedJson = JSON.parse(text); } catch { - this.sendFrame(meta.ws, { - type: 'error', - code: 'BAD_JSON', - message: 'Invalid WebSocket JSON frame', - }); + this.sendFrame( + meta.ws, + { + type: 'error', + code: 'BAD_JSON', + message: 'Invalid WebSocket JSON frame', + }, + true, + ); return; } const result = ClientWsFrameSchema.safeParse(parsedJson); if (!result.success) { - this.sendFrame(meta.ws, { - type: 'error', - code: 'INVALID_FRAME', - message: 'Unrecognized or malformed WebSocket frame', - }); + this.sendFrame( + meta.ws, + { + type: 'error', + code: 'INVALID_FRAME', + message: 'Unrecognized or malformed WebSocket frame', + }, + true, + ); return; } const frame = result.data; switch (frame.type) { - case 'ping': - this.sendFrame(meta.ws, { - type: 'pong', - ts: frame.ts, - serverTs: Date.now(), - }); + case 'ping': { + if (!this.ensureActiveSession(meta)) return; + this.sendFrame( + meta.ws, + { + type: 'pong', + ts: frame.ts, + serverTs: Date.now(), + }, + true, + ); break; + } case 'sub': { + if (!this.ensureActiveSession(meta)) return; const ctx = { send: (outFrame: ServerWsFrame) => this.sendFrame(meta.ws, outFrame), sessionIdHash: meta.sessionIdHash, @@ -274,44 +353,78 @@ export class WsHub { meta.channels.delete(ch); } break; - case 'safe-mode': - meta.clientSafeMode = frame.enabled; + case 'safe-mode': { + const latestSession = this.ensureActiveSession(meta); + if (!latestSession) return; + meta.clientSafeMode = latestSession.safeMode || frame.enabled; break; + } case 'pty:input': { - const latestSession = this.authService.getSessionByToken(meta.sessionToken); - if (!latestSession) { - meta.ws.close(4001, 'Session expired'); - return; - } + const latestSession = this.ensureActiveSession(meta); + if (!latestSession) return; if (latestSession.safeMode || meta.clientSafeMode) { - this.sendFrame(meta.ws, { - type: 'error', - code: 'SAFE_MODE_ACTIVE', - message: 'Safe / Read-Only Mode blocks terminal input.', - }); + this.sendFrame( + meta.ws, + { + type: 'error', + code: 'SAFE_MODE_ACTIVE', + message: 'Safe / Read-Only Mode blocks terminal input.', + }, + true, + ); return; } this.ptyHandlers?.onInput(frame.sessionId, frame.data); break; } case 'pty:resize': { - const latestSession = this.authService.getSessionByToken(meta.sessionToken); - if (!latestSession) { - meta.ws.close(4001, 'Session expired'); - return; - } + if (!this.ensureActiveSession(meta)) return; this.ptyHandlers?.onResize(frame.sessionId, frame.cols, frame.rows); break; } - case 'ai:cancel': + case 'ai:cancel': { + const latestSession = this.ensureActiveSession(meta); + if (!latestSession) return; + if (latestSession.safeMode || meta.clientSafeMode) { + this.sendFrame( + meta.ws, + { + type: 'error', + code: 'SAFE_MODE_ACTIVE', + message: 'Safe / Read-Only Mode blocks mutating AI actions.', + }, + true, + ); + return; + } this.aiHandlers?.onCancel(frame.chatId); break; + } } } - private sendFrame(ws: WebSocket, frame: ServerWsFrame): void { - if (ws.readyState === WebSocket.OPEN) { - ws.send(JSON.stringify(frame)); + private safeSendRaw(client: WsClientMeta, payload: string, critical = false): void { + if (client.ws.readyState !== WebSocket.OPEN) return; + if (client.ws.bufferedAmount > WS_HARD_BACKPRESSURE_BYTES) { + client.ws.terminate(); + this.clients.delete(client); + return; } + if (!critical && client.ws.bufferedAmount > WS_SOFT_BACKPRESSURE_BYTES) { + return; + } + client.ws.send(payload); + } + + private sendFrame(ws: WebSocket, frame: ServerWsFrame, critical = false): void { + if (ws.readyState !== WebSocket.OPEN) return; + if (ws.bufferedAmount > WS_HARD_BACKPRESSURE_BYTES) { + ws.terminate(); + return; + } + if (!critical && ws.bufferedAmount > WS_SOFT_BACKPRESSURE_BYTES) { + return; + } + ws.send(JSON.stringify(frame)); } } diff --git a/src/server/app.ts b/src/server/app.ts index c0cdded..2b889a8 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -56,6 +56,7 @@ export interface ServerOptions { publicDir?: string; secretFilePath?: string; envMasterKey?: string; + envDbKey?: string; trustCloudflare?: boolean; trustedProxyCidrs?: string[]; allowLanTunnels?: boolean; @@ -135,8 +136,11 @@ export async function createGCoordinatorServer( const authService = new AuthService(db, { getSecuritySettings: () => configManager.getSettings().security, + getRuntimeLimits, recoveryStore, vaultService, + dataDir, + envDbKey: options.envDbKey, }); const backupKey = configManager.getSettings().security.enableEmergencySecretsBackup @@ -163,7 +167,10 @@ export async function createGCoordinatorServer( } const httpServer = http.createServer(app); - const wsHub = new WsHub(httpServer, authService, vaultService); + const wsHub = new WsHub(httpServer, authService, vaultService, { trustCloudflare }); + authService.onSessionsRevoked((idHashes) => { + wsHub.disconnectSessions(idHashes); + }); const knownHosts = new KnownHostsService(db, auditService); const sshPool = new SSHPool(configManager, vaultService, knownHosts); @@ -374,8 +381,8 @@ export async function createGCoordinatorServer( tunnelManager.stopAll(); ptyManager.closeAll(true); sshPool.closeAll('panic_lock'); - authService.revokeAllSessions(); wsHub.handlePanicLock(); + authService.revokeAllSessions(); }); configManager.onChange((event) => { @@ -437,6 +444,8 @@ export async function createGCoordinatorServer( recoveryStore, rateLimiter, trustCloudflare, + webauthnRpId: options.webauthnRpId, + webauthnOrigins: options.webauthnOrigins, }), ); @@ -628,6 +637,7 @@ export async function createGCoordinatorServer( tunnelManager.stopAll(); ptyManager.close(); sshPool.closeAll('shutdown'); + authService.close(); wsHub.close(); await configManager.close(); await new Promise((resolve) => { diff --git a/src/server/index.ts b/src/server/index.ts index 67672d9..8e1a56b 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -20,6 +20,7 @@ async function main(): Promise { const secretFilePath = process.env.GCOORD_MASTER_KEY_FILE ?? '/run/secrets/gcoord_master_key'; const envMasterKey = process.env.GCOORD_MASTER_KEY; + const envDbKey = process.env.GCOORD_DB_KEY; const proxyPortRaw = process.env.GCOORD_PROXY_PORT ? Number(process.env.GCOORD_PROXY_PORT) : undefined; const instance = await createGCoordinatorServer({ @@ -28,6 +29,7 @@ async function main(): Promise { host, secretFilePath, envMasterKey, + envDbKey, trustCloudflare, trustedProxyCidrs, allowLanTunnels: process.env.GCOORD_ALLOW_LAN_TUNNELS === 'true', diff --git a/src/server/security/auth.ts b/src/server/security/auth.ts index fb1500d..0c33dd8 100644 --- a/src/server/security/auth.ts +++ b/src/server/security/auth.ts @@ -1,4 +1,6 @@ import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; import { generateAuthenticationOptions, generateRegistrationOptions, @@ -17,18 +19,120 @@ import { type SecuritySettings, type StepUpPolicy, } from '../../shared/schemas/settings.schema.js'; +import type { RuntimeLimits } from '../config/runtime-limits.js'; import type { EmergencyRecoveryService, SavedTotpEntry } from './recovery-store.js'; import type { VaultService } from './vault.js'; const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; -const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000; const BOOTSTRAP_TTL_MS = 15 * 60 * 1000; const WEBAUTHN_TTL_MS = 5 * 60 * 1000; +const SESSION_REAPER_MS = 5 * 60 * 1000; const TOTP_PERIOD_SEC = 30; const DEFAULT_SECURITY = SecuritySettingsSchema.parse({}); export const SESSION_COOKIE_NAME = 'gcoord_sid'; +export class AuthOverloadError extends Error { + readonly code = 'AUTH_OVERLOADED'; + constructor(message = 'Authentication queue is busy; try again shortly') { + super(message); + this.name = 'AuthOverloadError'; + } +} + +export function loadOrCreateDbKey(options: { dataDir?: string; envDbKey?: string }): Buffer { + if (options.envDbKey && options.envDbKey.trim().length > 0) { + const clean = options.envDbKey.trim().toLowerCase(); + if (!/^[0-9a-f]{64}$/.test(clean)) { + throw new Error('GCOORD_DB_KEY must be exactly 64 hex characters (32 bytes)'); + } + return Buffer.from(clean, 'hex'); + } + + if (!options.dataDir) { + return crypto.randomBytes(32); + } + + const keyPath = path.join(options.dataDir, 'db.key'); + try { + const stat = fs.lstatSync(keyPath); + if (stat.isSymbolicLink() || !stat.isFile()) { + throw new Error(`Refusing symlink or non-file db key at ${keyPath}`); + } + const clean = fs.readFileSync(keyPath, 'utf8').trim().toLowerCase(); + if (!/^[0-9a-f]{64}$/.test(clean)) { + throw new Error(`Invalid db.key format at ${keyPath}`); + } + try { + fs.chmodSync(keyPath, 0o600); + } catch { + // Best-effort POSIX permission tightening + } + return Buffer.from(clean, 'hex'); + } catch (err) { + if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') { + throw err; + } + } + + const key = crypto.randomBytes(32); + const hex = `${key.toString('hex')}\n`; + try { + fs.mkdirSync(path.dirname(keyPath), { recursive: true, mode: 0o700 }); + const fd = fs.openSync( + keyPath, + fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, + 0o600, + ); + try { + fs.writeSync(fd, hex, 0, 'utf8'); + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } + return key; + } catch (err) { + if ((err as NodeJS.ErrnoException)?.code === 'EEXIST') { + const clean = fs.readFileSync(keyPath, 'utf8').trim().toLowerCase(); + if (!/^[0-9a-f]{64}$/.test(clean)) { + throw new Error(`Invalid db.key format at ${keyPath}`); + } + return Buffer.from(clean, 'hex'); + } + throw err; + } +} + +export function encryptTotpSecret(dbKey: Buffer, totpId: string, secretBase32: string): string { + const iv = crypto.randomBytes(12); + const cipher = crypto.createCipheriv('aes-256-gcm', dbKey, iv); + cipher.setAAD(Buffer.from(`gcoord-totp-v1:${totpId}`, 'utf8')); + const ct = Buffer.concat([cipher.update(secretBase32, 'utf8'), cipher.final()]); + const tag = cipher.getAuthTag(); + return `v1:${iv.toString('hex')}:${tag.toString('hex')}:${ct.toString('hex')}`; +} + +export function decryptTotpSecret(dbKey: Buffer, totpId: string, encoded: string): string { + const parts = encoded.split(':'); + if (parts.length !== 4 || parts[0] !== 'v1') { + throw new Error(`Invalid encrypted TOTP envelope for ${totpId}`); + } + const iv = Buffer.from(parts[1]!, 'hex'); + const tag = Buffer.from(parts[2]!, 'hex'); + const ct = Buffer.from(parts[3]!, 'hex'); + const decipher = crypto.createDecipheriv('aes-256-gcm', dbKey, iv); + decipher.setAAD(Buffer.from(`gcoord-totp-v1:${totpId}`, 'utf8')); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(ct), decipher.final()]).toString('utf8'); +} + +function timingSafeStringEqual(a: string, b: string): boolean { + const bufA = Buffer.from(a, 'utf8'); + const bufB = Buffer.from(b, 'utf8'); + if (bufA.length !== bufB.length) return false; + return crypto.timingSafeEqual(bufA, bufB); +} + export interface AuthSession { idHash: string; csrfTokenHash: string; @@ -96,8 +200,16 @@ export type StepUpInput = export interface AuthServiceOptions { getSecuritySettings?: () => SecuritySettings; + getRuntimeLimits?: () => RuntimeLimits; recoveryStore?: EmergencyRecoveryService; vaultService?: VaultService; + dataDir?: string; + envDbKey?: string; + onSecurityEvent?: (event: { + type: string; + ip?: string; + details?: Record; + }) => void; } interface AdminRow { @@ -120,8 +232,10 @@ interface TotpRow { id: string; label: string; secret_base32: string; + secret_enc: string | null; last_login_step: number | null; last_stepup_step: number | null; + last_used_step: number | null; created_at: number; } @@ -191,13 +305,21 @@ function computeElevatedUntil( } export class AuthService { - private pendingBootstrap: { secretBase32: string; createdAt: number } | null = null; + private pendingBootstrap: { secretBase32: string; token: string; createdAt: number } | null = null; private readonly pendingEnrollments = new Map< string, { label: string; secretBase32: string; createdAt: number } >(); private readonly pendingWebAuthn = new Map(); + private readonly sessionRevokedListeners = new Set<(idHashes: string[]) => void>(); private readonly getSecurity: () => SecuritySettings; + private readonly getRuntimeLimits?: () => RuntimeLimits; + private onSecurityEvent?: AuthServiceOptions['onSecurityEvent']; + private readonly dbKey: Buffer; + private readonly sessionReaperTimer: NodeJS.Timeout; + private argon2Active = 0; + private readonly argon2Queue: Array<{ resolve: () => void; reject: (err: Error) => void }> = []; + private dummyArgon2Hash: string | null = null; private recoveryStore?: EmergencyRecoveryService; private vaultService?: VaultService; @@ -206,8 +328,169 @@ export class AuthService { options: AuthServiceOptions = {}, ) { this.getSecurity = options.getSecuritySettings ?? (() => DEFAULT_SECURITY); + this.getRuntimeLimits = options.getRuntimeLimits; + this.onSecurityEvent = options.onSecurityEvent; this.recoveryStore = options.recoveryStore; this.vaultService = options.vaultService; + + const inferredDir = + options.dataDir ?? + (db.name && db.name !== ':memory:' ? path.dirname(db.name) : undefined); + this.dbKey = loadOrCreateDbKey({ dataDir: inferredDir, envDbKey: options.envDbKey }); + this.migratePlaintextTotpsIfNeeded(); + + this.sessionReaperTimer = setInterval(() => { + this.reapExpiredSessions(); + }, SESSION_REAPER_MS); + this.sessionReaperTimer.unref(); + } + + close(): void { + clearInterval(this.sessionReaperTimer); + while (this.argon2Queue.length > 0) { + const waiter = this.argon2Queue.shift()!; + waiter.reject(new Error('AuthService shutting down')); + } + } + + setSecurityEventListener(listener: AuthServiceOptions['onSecurityEvent']): void { + this.onSecurityEvent = listener; + } + + emitSecurityEvent(type: string, ip?: string, details?: Record): void { + try { + this.onSecurityEvent?.({ type, ip, details }); + } catch { + // Never let security event hook break authentication flow + } + } + + onSessionsRevoked(listener: (idHashes: string[]) => void): () => void { + this.sessionRevokedListeners.add(listener); + return () => { + this.sessionRevokedListeners.delete(listener); + }; + } + + private notifySessionsRevoked(idHashes: string[]): void { + if (idHashes.length === 0) return; + for (const listener of this.sessionRevokedListeners) { + try { + listener(idHashes); + } catch { + // Ignore subscriber errors + } + } + } + + private async runArgon2(task: (memoryCost: number) => Promise): Promise { + const limits = this.getRuntimeLimits?.(); + const concurrency = Math.max(1, limits?.argon2Concurrency ?? 2); + const maxQueue = Math.max(1, limits?.argon2MaxQueue ?? 16); + const memoryCost = limits?.argon2MemoryCost ?? 32768; + + if (this.argon2Active >= concurrency) { + if (this.argon2Queue.length >= maxQueue) { + throw new AuthOverloadError(); + } + await new Promise((resolve, reject) => { + this.argon2Queue.push({ resolve, reject }); + }); + } + + this.argon2Active += 1; + try { + return await task(memoryCost); + } finally { + this.argon2Active -= 1; + const next = this.argon2Queue.shift(); + if (next) next.resolve(); + } + } + + private hashPassword(password: string): Promise { + return this.runArgon2((memoryCost) => + argon2.hash(password, { + type: argon2.argon2id, + memoryCost, + timeCost: 3, + parallelism: 1, + }), + ); + } + + private verifyPasswordHash(hash: string, candidate: string): Promise { + return this.runArgon2(() => argon2.verify(hash, candidate).catch(() => false)); + } + + private async verifyDummyPassword(candidate: string): Promise { + if (!this.dummyArgon2Hash) { + this.dummyArgon2Hash = await this.hashPassword('gcoord-dummy-timing-guard-v1'); + } + await this.verifyPasswordHash(this.dummyArgon2Hash, candidate); + } + + private getTotpSecret(row: TotpRow): string { + if (row.secret_enc && row.secret_enc.startsWith('v1:')) { + return decryptTotpSecret(this.dbKey, row.id, row.secret_enc); + } + if (row.secret_base32 && row.secret_base32.length > 0) { + const enc = encryptTotpSecret(this.dbKey, row.id, row.secret_base32); + try { + this.db + .prepare("UPDATE admin_totps SET secret_enc = ?, secret_base32 = '' WHERE id = ?") + .run(enc, row.id); + } catch { + // Ignore read-only DB edge case + } + return row.secret_base32; + } + throw new Error(`Missing TOTP secret for ${row.id}`); + } + + private migratePlaintextTotpsIfNeeded(): void { + try { + const rows = this.db + .prepare("SELECT id, secret_base32 FROM admin_totps WHERE (secret_enc IS NULL OR secret_enc = '') AND secret_base32 != ''") + .all() as Array<{ id: string; secret_base32: string }>; + if (rows.length === 0) return; + const tx = this.db.transaction(() => { + const stmt = this.db.prepare( + "UPDATE admin_totps SET secret_enc = ?, secret_base32 = '' WHERE id = ?", + ); + for (const r of rows) { + stmt.run(encryptTotpSecret(this.dbKey, r.id, r.secret_base32), r.id); + } + }); + tx(); + } catch { + // Safe before migrations finish if constructed manually + } + } + + reapExpiredSessions(): number { + const now = Date.now(); + const sec = this.getSecurity(); + const idleMs = (sec.sessionIdleTimeoutMin ?? 60) * 60 * 1000; + const rows = + idleMs > 0 + ? (this.db + .prepare('SELECT id_hash FROM sessions WHERE expires_at <= ? OR last_seen_at <= ?') + .all(now, now - idleMs) as Array<{ id_hash: string }>) + : (this.db + .prepare('SELECT id_hash FROM sessions WHERE expires_at <= ?') + .all(now) as Array<{ id_hash: string }>); + if (rows.length === 0) return 0; + const hashes = rows.map((r) => r.id_hash); + if (idleMs > 0) { + this.db + .prepare('DELETE FROM sessions WHERE expires_at <= ? OR last_seen_at <= ?') + .run(now, now - idleMs); + } else { + this.db.prepare('DELETE FROM sessions WHERE expires_at <= ?').run(now); + } + this.notifySessionsRevoked(hashes); + return hashes.length; } attachRecoveryDependencies( @@ -259,9 +542,11 @@ export class AuthService { } async beginBootstrap(username = 'admin'): Promise<{ + bootstrapToken: string; secretBase32: string; otpauthUri: string; qrSvg: string; + qrDataUri: string; }> { if (this.isBootstrapped()) { throw new Error('Admin account is already configured'); @@ -274,17 +559,24 @@ export class AuthService { const secret = new OTPAuth.Secret({ size: 20 }); this.pendingBootstrap = { secretBase32: secret.base32, + token: crypto.randomBytes(24).toString('base64url'), createdAt: Date.now(), }; } - const totp = buildTotp(this.pendingBootstrap.secretBase32, username); + const cleanUser = username.trim().slice(0, 64) || 'admin'; + const totp = buildTotp(this.pendingBootstrap.secretBase32, cleanUser); const otpauthUri = totp.toString(); - const qrSvg = await QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }); + const [qrSvg, qrDataUri] = await Promise.all([ + QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }), + QRCode.toDataURL(otpauthUri, { margin: 1, width: 220 }), + ]); return { + bootstrapToken: this.pendingBootstrap.token, secretBase32: this.pendingBootstrap.secretBase32, otpauthUri, qrSvg, + qrDataUri, }; } @@ -293,6 +585,7 @@ export class AuthService { password: string; totpCode: string; secretBase32?: string; + bootstrapToken?: string; ip: string; userAgent: string; initialSafeMode?: boolean; @@ -313,11 +606,30 @@ export class AuthService { throw new Error('Password must be at least 10 characters'); } - const secretBase32 = params.secretBase32 ?? this.pendingBootstrap?.secretBase32; - if (!secretBase32) { + if ( + !this.pendingBootstrap || + Date.now() - this.pendingBootstrap.createdAt > BOOTSTRAP_TTL_MS + ) { + this.pendingBootstrap = null; throw new Error('Bootstrap enrollment session expired; reload setup'); } + if ( + params.bootstrapToken !== undefined && + !timingSafeStringEqual(params.bootstrapToken, this.pendingBootstrap.token) + ) { + throw new Error('Invalid bootstrap session token; reload setup'); + } + + if ( + params.secretBase32 !== undefined && + !timingSafeStringEqual(params.secretBase32.trim(), this.pendingBootstrap.secretBase32) + ) { + throw new Error('Bootstrap secret mismatch; reload setup'); + } + + const secretBase32 = this.pendingBootstrap.secretBase32; + const nowMs = Date.now(); const totp = buildTotp(secretBase32, username); const delta = totp.validate({ @@ -330,12 +642,8 @@ export class AuthService { } const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta; - const passwordHash = await argon2.hash(params.password, { - type: argon2.argon2id, - memoryCost: 65536, - timeCost: 3, - parallelism: 1, - }); + const passwordHash = await this.hashPassword(params.password); + const secretEnc = encryptTotpSecret(this.dbKey, 'totp-primary', secretBase32); const recoveryCodes: string[] = []; for (let i = 0; i < 8; i++) { @@ -346,9 +654,9 @@ export class AuthService { this.db .prepare( `INSERT INTO admin_users (id, username, password_hash, totp_secret, last_login_totp_step, last_stepup_totp_step, created_at, updated_at) - VALUES (1, ?, ?, ?, ?, NULL, ?, ?)`, + VALUES (1, ?, '', '', ?, ?, ?, ?)`, ) - .run(username, passwordHash, secretBase32, matchedStep, nowMs, nowMs); + .run(username, matchedStep, matchedStep, nowMs, nowMs); this.db .prepare( @@ -358,10 +666,10 @@ export class AuthService { this.db .prepare( - `INSERT INTO admin_totps (id, label, secret_base32, last_login_step, last_stepup_step, created_at) - VALUES (?, ?, ?, ?, NULL, ?)`, + `INSERT INTO admin_totps (id, label, secret_base32, secret_enc, last_login_step, last_stepup_step, last_used_step, created_at) + VALUES (?, ?, '', ?, ?, ?, ?, ?)`, ) - .run('totp-primary', 'Primary Authenticator', secretBase32, matchedStep, nowMs); + .run('totp-primary', 'Primary Authenticator', secretEnc, matchedStep, matchedStep, matchedStep, nowMs); const insertRec = this.db.prepare( 'INSERT INTO recovery_codes (code_hash, used_at) VALUES (?, NULL)', @@ -399,28 +707,35 @@ export class AuthService { const admin = this.db .prepare('SELECT * FROM admin_users WHERE id = 1') .get() as AdminRow | undefined; - if (!admin) return null; + const suppliedPasswords = ( + params.passwords ?? (params.password !== undefined ? [params.password] : []) + ) + .filter((p) => p.length > 0) + .slice(0, 16); + const cleanUser = params.username?.trim() ?? ''; - if (params.username && params.username.trim() !== admin.username) { + if ( + !admin || + !cleanUser || + cleanUser.length > 64 || + suppliedPasswords.length === 0 || + !timingSafeStringEqual(cleanUser, admin.username) + ) { + await this.verifyDummyPassword(suppliedPasswords[0] ?? 'dummy'); return null; } const sec = this.getSecurity(); - const suppliedPasswords = ( - params.passwords ?? (params.password !== undefined ? [params.password] : []) - ).filter((p) => p.length > 0); - if (suppliedPasswords.length === 0) return null; - const pwOk = await this.verifyPasswords(suppliedPasswords, sec.passwordMode); if (!pwOk) return null; - const totpRows = this.listTotpRows(); - if (sec.requireTotpOnLogin && totpRows.length > 0) { + if (sec.requireTotpOnLogin) { const suppliedCodes = ( params.codes ?? (params.code !== undefined ? [params.code] : []) ) .map((c) => c.trim()) - .filter((c) => c.length > 0); + .filter((c) => c.length > 0) + .slice(0, 16); if (suppliedCodes.length === 0) return null; @@ -429,6 +744,7 @@ export class AuthService { sec.totpMode, 'login', admin.username, + params.ip, ); if (!mfaOk) return null; } @@ -451,10 +767,24 @@ export class AuthService { const now = Date.now(); if (row.expires_at <= now) { this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash); + this.notifySessionsRevoked([idHash]); return null; } - if (now - row.last_seen_at > 60_000) { + const sec = this.getSecurity(); + const idleMs = (sec.sessionIdleTimeoutMin ?? 60) * 60 * 1000; + if (idleMs > 0 && now - row.last_seen_at > idleMs) { + this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash); + this.notifySessionsRevoked([idHash]); + this.emitSecurityEvent('auth.session_idle_expired', row.ip, { + idPrefix: idHash.slice(0, 12), + }); + return null; + } + + const touchIntervalMs = + idleMs > 0 ? Math.min(60_000, Math.max(1000, Math.floor(idleMs / 4))) : 60_000; + if (now - row.last_seen_at > touchIntervalMs) { this.db .prepare('UPDATE sessions SET last_seen_at = ? WHERE id_hash = ?') .run(now, idHash); @@ -522,20 +852,17 @@ export class AuthService { } if (sec.stepUpMethod === 'totp' || sec.stepUpMethod === 'both') { - const totpRows = this.listTotpRows(); - if (totpRows.length > 0) { - if (suppliedCodes.length === 0) { - return { ok: false, reason: 'invalid_totp' }; - } - const totpResult = this.verifyTotpRows( - suppliedCodes, - sec.totpMode, - 'stepup', - admin.username, - ); - if (!totpResult.ok) { - return { ok: false, reason: totpResult.reason }; - } + if (suppliedCodes.length === 0) { + return { ok: false, reason: 'invalid_totp' }; + } + const totpResult = this.verifyTotpRows( + suppliedCodes, + sec.totpMode, + 'stepup', + admin.username, + ); + if (!totpResult.ok) { + return { ok: false, reason: totpResult.reason }; } } @@ -680,7 +1007,7 @@ export class AuthService { })), authenticatorSelection: { residentKey: 'preferred', - userVerification: 'preferred', + userVerification: 'required', }, }); @@ -711,7 +1038,7 @@ export class AuthService { expectedChallenge: pending.challenge, expectedOrigin: pending.expectedOrigin, expectedRPID: pending.rpID, - requireUserVerification: false, + requireUserVerification: true, }); if (!verification.verified || !verification.registrationInfo) { @@ -776,7 +1103,7 @@ export class AuthService { ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) : undefined, })), - userVerification: 'preferred', + userVerification: 'required', }); const challengeId = crypto.randomBytes(16).toString('hex'); @@ -802,6 +1129,14 @@ export class AuthService { if (!this.isBootstrapped()) return null; const pending = this.consumeWebAuthnChallenge(params.challengeId, 'login'); if (!pending) return null; + if ( + !params.response || + typeof params.response.id !== 'string' || + params.response.id.length === 0 || + params.response.id.length > 512 + ) { + return null; + } const row = this.db .prepare('SELECT * FROM webauthn_credentials WHERE id = ?') @@ -822,7 +1157,7 @@ export class AuthService { ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) : undefined, }, - requireUserVerification: false, + requireUserVerification: true, }); if (!verification.verified) return null; @@ -857,11 +1192,22 @@ export class AuthService { if (session.safe_mode === 1) { return { ok: false, reason: 'safe_mode_active' }; } + if (sec.stepUpMethod !== 'passkey') { + return { ok: false, reason: 'passkey_stepup_not_enabled' }; + } const pending = this.consumeWebAuthnChallenge(params.challengeId, 'stepup'); if (!pending || pending.sessionIdHash !== params.idHash) { return { ok: false, reason: 'invalid_challenge' }; } + if ( + !params.response || + typeof params.response.id !== 'string' || + params.response.id.length === 0 || + params.response.id.length > 512 + ) { + return { ok: false, reason: 'invalid_assertion' }; + } const row = this.db .prepare('SELECT * FROM webauthn_credentials WHERE id = ?') @@ -882,7 +1228,7 @@ export class AuthService { ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) : undefined, }, - requireUserVerification: false, + requireUserVerification: true, }); if (!verification.verified) { return { ok: false, reason: 'invalid_assertion' }; @@ -922,12 +1268,7 @@ export class AuthService { const id = `pw-${crypto.randomBytes(4).toString('hex')}`; const createdAt = Date.now(); - const hash = await argon2.hash(password, { - type: argon2.argon2id, - memoryCost: 65536, - timeCost: 3, - parallelism: 1, - }); + const hash = await this.hashPassword(password); this.db .prepare( @@ -962,6 +1303,7 @@ export class AuthService { secretBase32: string; otpauthUri: string; qrSvg: string; + qrDataUri: string; }> { const cleanLabel = label.trim(); if (cleanLabel.length < 1 || cleanLabel.length > 64) { @@ -985,13 +1327,17 @@ export class AuthService { const username = this.getAdminUsername() ?? 'admin'; const totp = buildTotp(secret.base32, `${username} (${cleanLabel})`); const otpauthUri = totp.toString(); - const qrSvg = await QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }); + const [qrSvg, qrDataUri] = await Promise.all([ + QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }), + QRCode.toDataURL(otpauthUri, { margin: 1, width: 220 }), + ]); return { enrollmentId, label: cleanLabel, secretBase32: secret.base32, otpauthUri, qrSvg, + qrDataUri, }; } @@ -1019,12 +1365,13 @@ export class AuthService { const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta; const id = `totp-${crypto.randomBytes(4).toString('hex')}`; + const secretEnc = encryptTotpSecret(this.dbKey, id, pending.secretBase32); this.db .prepare( - `INSERT INTO admin_totps (id, label, secret_base32, last_login_step, last_stepup_step, created_at) - VALUES (?, ?, ?, ?, ?, ?)`, + `INSERT INTO admin_totps (id, label, secret_base32, secret_enc, last_login_step, last_stepup_step, last_used_step, created_at) + VALUES (?, ?, '', ?, ?, ?, ?, ?)`, ) - .run(id, pending.label, pending.secretBase32, matchedStep, matchedStep, nowMs); + .run(id, pending.label, secretEnc, matchedStep, matchedStep, matchedStep, nowMs); this.pendingEnrollments.delete(enrollmentId); this.syncRecovery({ snapshotReason: 'totp-added' }); @@ -1092,16 +1439,19 @@ export class AuthService { .prepare('SELECT id, label, created_at AS createdAt FROM admin_passwords ORDER BY created_at ASC') .all() as Array<{ id: string; label: string; createdAt: number }>; const totpRows = this.listTotpRows(); - const totps: SavedTotpEntry[] = totpRows.map((t) => ({ - id: t.id, - label: t.label, - secretBase32: t.secret_base32, - otpauthUri: buildTotp( - t.secret_base32, - username ? `${username} (${t.label})` : t.label, - ).toString(), - createdAt: new Date(t.created_at).toISOString(), - })); + const totps: SavedTotpEntry[] = totpRows.map((t) => { + const secretBase32 = this.getTotpSecret(t); + return { + id: t.id, + label: t.label, + secretBase32, + otpauthUri: buildTotp( + secretBase32, + username ? `${username} (${t.label})` : t.label, + ).toString(), + createdAt: new Date(t.created_at).toISOString(), + }; + }); this.recoveryStore.syncState({ enabled: sec.enableEmergencySecretsBackup, @@ -1134,24 +1484,43 @@ export class AuthService { } revokeSessionByHash(idHash: string): void { - this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash); + const res = this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash); + if (res.changes > 0) { + this.notifySessionsRevoked([idHash]); + } } revokeSessionByPrefix(prefix: string): number { if (!/^[0-9a-f]{8,64}$/i.test(prefix)) return 0; + const rows = this.db + .prepare('SELECT id_hash FROM sessions WHERE id_hash LIKE ?') + .all(`${prefix}%`) as Array<{ id_hash: string }>; + if (rows.length === 0) return 0; const result = this.db .prepare('DELETE FROM sessions WHERE id_hash LIKE ?') .run(`${prefix}%`); + if (result.changes > 0) { + this.notifySessionsRevoked(rows.map((r) => r.id_hash)); + } return result.changes; } revokeAllSessions(exceptIdHash?: string): number { - if (exceptIdHash) { - return this.db - .prepare('DELETE FROM sessions WHERE id_hash != ?') - .run(exceptIdHash).changes; + const rows = ( + exceptIdHash + ? this.db + .prepare('SELECT id_hash FROM sessions WHERE id_hash != ?') + .all(exceptIdHash) + : this.db.prepare('SELECT id_hash FROM sessions').all() + ) as Array<{ id_hash: string }>; + if (rows.length === 0) return 0; + const changes = exceptIdHash + ? this.db.prepare('DELETE FROM sessions WHERE id_hash != ?').run(exceptIdHash).changes + : this.db.prepare('DELETE FROM sessions').run().changes; + if (changes > 0) { + this.notifySessionsRevoked(rows.map((r) => r.id_hash)); } - return this.db.prepare('DELETE FROM sessions').run().changes; + return changes; } private listTotpRows(): TotpRow[] { @@ -1172,7 +1541,7 @@ export class AuthService { if (mode === 'any') { for (const row of rows) { for (const candidate of suppliedPasswords) { - if (await argon2.verify(row.password_hash, candidate)) { + if (await this.verifyPasswordHash(row.password_hash, candidate)) { return true; } } @@ -1184,7 +1553,7 @@ export class AuthService { for (const row of rows) { let rowMatched = false; for (const candidate of suppliedPasswords) { - if (await argon2.verify(row.password_hash, candidate)) { + if (await this.verifyPasswordHash(row.password_hash, candidate)) { rowMatched = true; break; } @@ -1199,8 +1568,9 @@ export class AuthService { mode: 'any' | 'all', purpose: 'login' | 'stepup', username: string, + ip?: string, ): boolean { - const totpRes = this.verifyTotpRows(suppliedCodes, mode, purpose, username); + const totpRes = this.verifyTotpRows(suppliedCodes, mode, purpose, username, ip); if (totpRes.ok) return true; // In 'any' mode, a single-use recovery code may replace TOTP @@ -1214,33 +1584,48 @@ export class AuthService { 'UPDATE recovery_codes SET used_at = ? WHERE code_hash = ? AND used_at IS NULL', ) .run(Date.now(), sha256Hex(normalized)); - if (updated.changes === 1) return true; + if (updated.changes === 1) { + this.emitSecurityEvent('auth.recovery_code_used', ip, { username }); + return true; + } } } return false; } + private getRowLastUsedStep(row: TotpRow): number | null { + if (row.last_used_step !== null && row.last_used_step !== undefined) { + return row.last_used_step; + } + const candidates = [row.last_login_step, row.last_stepup_step].filter( + (n): n is number => typeof n === 'number', + ); + return candidates.length > 0 ? Math.max(...candidates) : null; + } + private verifyTotpRows( suppliedCodes: string[], mode: 'any' | 'all', purpose: 'login' | 'stepup', username: string, + ip?: string, ): { ok: true } | { ok: false; reason: string } { const rows = this.listTotpRows(); - if (rows.length === 0) return { ok: true }; + if (rows.length === 0) { + return { ok: false, reason: 'totp_not_configured' }; + } const numericCodes = suppliedCodes.filter((c) => /^\d{6}$/.test(c)); if (numericCodes.length === 0) return { ok: false, reason: 'invalid_totp' }; const nowMs = Date.now(); - const stepCol = purpose === 'login' ? 'last_login_step' : 'last_stepup_step'; if (mode === 'any') { let sawReplay = false; for (const row of rows) { - const totp = buildTotp(row.secret_base32, username); - const lastStep = - purpose === 'login' ? row.last_login_step : row.last_stepup_step; + const secret = this.getTotpSecret(row); + const totp = buildTotp(secret, username); + const lastStep = this.getRowLastUsedStep(row); for (const code of numericCodes) { const delta = totp.validate({ token: code, window: 1, timestamp: nowMs }); if (delta === null) continue; @@ -1250,20 +1635,25 @@ export class AuthService { continue; } this.db - .prepare(`UPDATE admin_totps SET ${stepCol} = ? WHERE id = ?`) - .run(matchedStep, row.id); + .prepare( + 'UPDATE admin_totps SET last_used_step = ?, last_login_step = ?, last_stepup_step = ? WHERE id = ?', + ) + .run(matchedStep, matchedStep, matchedStep, row.id); return { ok: true }; } } + if (sawReplay) { + this.emitSecurityEvent('auth.totp_replay', ip, { purpose }); + } return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' }; } // 'all': every configured TOTP authenticator must match a supplied valid non-replayed code const matchedUpdates: Array<{ id: string; step: number }> = []; for (const row of rows) { - const totp = buildTotp(row.secret_base32, username); - const lastStep = - purpose === 'login' ? row.last_login_step : row.last_stepup_step; + const secret = this.getTotpSecret(row); + const totp = buildTotp(secret, username); + const lastStep = this.getRowLastUsedStep(row); let rowStep: number | null = null; let sawReplay = false; @@ -1280,15 +1670,20 @@ export class AuthService { } if (rowStep === null) { + if (sawReplay) { + this.emitSecurityEvent('auth.totp_replay', ip, { purpose }); + } return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' }; } matchedUpdates.push({ id: row.id, step: rowStep }); } const tx = this.db.transaction(() => { - const stmt = this.db.prepare(`UPDATE admin_totps SET ${stepCol} = ? WHERE id = ?`); + const stmt = this.db.prepare( + 'UPDATE admin_totps SET last_used_step = ?, last_login_step = ?, last_stepup_step = ? WHERE id = ?', + ); for (const upd of matchedUpdates) { - stmt.run(upd.step, upd.id); + stmt.run(upd.step, upd.step, upd.step, upd.id); } }); tx(); @@ -1305,8 +1700,9 @@ export class AuthService { const idHash = sha256Hex(sessionToken); const csrfTokenHash = sha256Hex(csrfToken); const now = Date.now(); - const expiresAt = now + SESSION_TTL_MS; const sec = this.getSecurity(); + const ttlMs = (sec.sessionTtlHours ?? 168) * 60 * 60 * 1000; + const expiresAt = now + ttlMs; const shouldElevate = sec.elevateOnLogin && (!safeMode || sec.keepElevationOnSafeMode); diff --git a/tests/auth-and-guards.test.ts b/tests/auth-and-guards.test.ts index 2fb7ca6..1683dbe 100644 --- a/tests/auth-and-guards.test.ts +++ b/tests/auth-and-guards.test.ts @@ -129,15 +129,21 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => { }); expect(boot.session.elevatedUntil).toBeNull(); - // Step-up tracks replay independently from login step - const stepUp1 = await auth.stepUp(boot.session.idHash, code0); + // Unified monotonic TOTP step blocks replaying bootstrap code for step-up + const replayBootCode = await auth.stepUp(boot.session.idHash, code0); + expect(replayBootCode).toEqual({ ok: false, reason: 'totp_replayed' }); + + const t1 = t0 + 31_000; + vi.setSystemTime(t1); + const code1 = generateTotp(enroll.secretBase32, t1); + const stepUp1 = await auth.stepUp(boot.session.idHash, code1); expect(stepUp1).toEqual({ ok: true, - elevatedUntil: t0 + 5 * 60 * 1000, + elevatedUntil: t1 + 5 * 60 * 1000, }); // Replaying exact same step-up code is denied - const stepUpReplay = await auth.stepUp(boot.session.idHash, code0); + const stepUpReplay = await auth.stepUp(boot.session.idHash, code1); expect(stepUpReplay).toEqual({ ok: false, reason: 'totp_replayed' }); // Enabling Safe Mode clears elevatedUntil immediately @@ -146,18 +152,19 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => { expect(safeSession?.elevatedUntil).toBeNull(); // Step-up is blocked while Safe Mode is ON - vi.setSystemTime(t0 + 31_000); - const code1 = generateTotp(enroll.secretBase32, t0 + 31_000); - const whileSafe = await auth.stepUp(boot.session.idHash, code1); + const t2 = t1 + 31_000; + vi.setSystemTime(t2); + const code2 = generateTotp(enroll.secretBase32, t2); + const whileSafe = await auth.stepUp(boot.session.idHash, code2); expect(whileSafe).toEqual({ ok: false, reason: 'safe_mode_active' }); // Turning Safe Mode OFF allows step-up again auth.setSafeMode(boot.session.idHash, false); - const stepUp2 = await auth.stepUp(boot.session.idHash, code1); + const stepUp2 = await auth.stepUp(boot.session.idHash, code2); expect(stepUp2.ok).toBe(true); // Elevation expires automatically after 5 minutes - vi.setSystemTime(t0 + 31_000 + 5 * 60 * 1000 + 1000); + vi.setSystemTime(t2 + 5 * 60 * 1000 + 1000); const expiredSession = auth.getSessionByToken(boot.sessionToken); expect(expiredSession?.elevatedUntil).toBeNull(); diff --git a/tests/multi-auth-and-recovery.test.ts b/tests/multi-auth-and-recovery.test.ts index 921ce26..60b4710 100644 --- a/tests/multi-auth-and-recovery.test.ts +++ b/tests/multi-auth-and-recovery.test.ts @@ -453,7 +453,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret activeServer = server; api = createApiClient(server); - vi.setSystemTime(t0 + 31_000); + vi.setSystemTime(t0 + 62_000); const relogin = await api.call('/api/auth/login', { method: 'POST', body: { @@ -510,7 +510,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret ).status, ).toBe(200); - vi.setSystemTime(t0 + 62_000); + vi.setSystemTime(t0 + 93_000); expect( (await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, ).toBe(200); diff --git a/tests/passkeys.test.ts b/tests/passkeys.test.ts index 9f5c444..0a9137b 100644 --- a/tests/passkeys.test.ts +++ b/tests/passkeys.test.ts @@ -1,5 +1,6 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; +import http from 'node:http'; import os from 'node:os'; import path from 'node:path'; import * as OTPAuth from 'otpauth'; @@ -152,6 +153,7 @@ function buildSyntheticAuthenticator(rpID: string, expectedOrigin: string) { } afterEach(async () => { + vi.useRealTimers(); while (cleanups.length > 0) { await cleanups.pop()!(); } @@ -172,7 +174,6 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => { fs.rmSync(dataDir, { recursive: true, force: true }); }); - const baseUrl = `http://127.0.0.1:${server.port}`; const origin = `http://localhost:${server.port}`; const jar = new CookieJar(); let csrfToken = ''; @@ -186,16 +187,57 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => { Host: `localhost:${server.port}`, }; if (jar.header()) headers.Cookie = jar.header(); - if (opts.body !== undefined) headers['Content-Type'] = 'application/json'; + const payload = opts.body !== undefined ? JSON.stringify(opts.body) : undefined; + if (payload !== undefined) { + headers['Content-Type'] = 'application/json'; + headers['Content-Length'] = String(Buffer.byteLength(payload)); + } if (csrfToken) headers['X-CSRF-Token'] = csrfToken; - const res = await fetch(`${baseUrl}${pathname}`, { - method: opts.method ?? 'GET', - headers, - body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined, - }); - jar.updateFrom(res); - const data = (await res.json().catch(() => ({}))) as Record; + const res = await new Promise<{ status: number; setCookies: string[]; text: string }>( + (resolve, reject) => { + const req = http.request( + { + host: '127.0.0.1', + port: server.port, + path: pathname, + method: opts.method ?? 'GET', + headers, + }, + (incoming) => { + const chunks: Buffer[] = []; + incoming.on('data', (c) => chunks.push(Buffer.from(c))); + incoming.on('end', () => { + const rawSetCookie = incoming.headers['set-cookie']; + resolve({ + status: incoming.statusCode ?? 0, + setCookies: Array.isArray(rawSetCookie) ? rawSetCookie : [], + text: Buffer.concat(chunks).toString('utf8'), + }); + }); + }, + ); + req.on('error', reject); + if (payload !== undefined) req.write(payload); + req.end(); + }, + ); + for (const line of res.setCookies) { + const first = line.split(';')[0] ?? ''; + const eq = first.indexOf('='); + if (eq > 0) { + const name = first.slice(0, eq).trim(); + const val = first.slice(eq + 1).trim(); + if (val === '') jar['cookies'].delete(name); + else jar['cookies'].set(name, val); + } + } + let data: Record = {}; + try { + data = JSON.parse(res.text) as Record; + } catch { + data = {}; + } if (typeof data.csrfToken === 'string' && data.csrfToken) { csrfToken = data.csrfToken; } @@ -316,7 +358,38 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => { }); expect(loginVerify2.status).toBe(200); - // 3. Step-Up Verification via Passkey + // 3. Step-Up Verification via Passkey requires stepUpMethod === 'passkey' + await api('/api/auth/drop-elevation', { method: 'POST' }); + expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(403); + + const deniedOpts = await api('/api/auth/passkeys/step-up/options', { method: 'POST', body: {} }); + expect(deniedOpts.status).toBe(200); + const deniedVerify = await api('/api/auth/passkeys/step-up/verify', { + method: 'POST', + body: { + challengeId: String(deniedOpts.data.challengeId), + response: authn.createAuthenticationResponse( + String((deniedOpts.data.options as { challenge: string }).challenge), + ), + }, + }); + expect(deniedVerify.status).toBe(403); + expect(deniedVerify.data.reason).toBe('passkey_stepup_not_enabled'); + + // Step up with TOTP in next step, enable stepUpMethod = 'passkey', then drop & verify passkey step-up + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() + 35_000); + expect( + (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, + ).toBe(200); + expect( + ( + await api('/api/auth/security-policy', { + method: 'PUT', + body: { stepUpMethod: 'passkey' }, + }) + ).status, + ).toBe(200); await api('/api/auth/drop-elevation', { method: 'POST' }); expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(403); @@ -335,7 +408,22 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => { expect(typeof stepVerify.data.elevatedUntil).toBe('number'); expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(200); - // 4. Delete passkey factor + // 4. Cannot delete the last passkey while stepUpMethod === 'passkey' + const blockedDel = await api(`/api/auth/factors/passkeys/${encodeURIComponent(authn.credId)}`, { + method: 'DELETE', + }); + expect(blockedDel.status).toBe(400); + + // Switch stepUpMethod back to 'totp', then delete passkey cleanly + expect( + ( + await api('/api/auth/security-policy', { + method: 'PUT', + body: { stepUpMethod: 'totp' }, + }) + ).status, + ).toBe(200); + const delRes = await api(`/api/auth/factors/passkeys/${encodeURIComponent(authn.credId)}`, { method: 'DELETE', }); diff --git a/tests/vault-runtime-and-collectors.test.ts b/tests/vault-runtime-and-collectors.test.ts index 6c1374e..77ee897 100644 --- a/tests/vault-runtime-and-collectors.test.ts +++ b/tests/vault-runtime-and-collectors.test.ts @@ -188,12 +188,12 @@ describe('Always-on background collectors & write-only Vault lock', () => { }); api = createApiClient(activeServer); - // Before ANY user logs in, status is unauthenticated + write-locked, yet runtime collectors run immediately + // Before ANY user logs in, status is unauthenticated and omits internal vault state, yet runtime collectors run immediately const preLoginStatus = await api.call('/api/auth/status'); expect(preLoginStatus.status).toBe(200); expect(preLoginStatus.data.authenticated).toBe(false); - expect(preLoginStatus.data.vaultState).toBe('locked'); - expect(preLoginStatus.data.vaultRuntimeReady).toBe(true); + expect(preLoginStatus.data.vaultState).toBeUndefined(); + expect(preLoginStatus.data.vaultRuntimeReady).toBeUndefined(); const latestBeforeLogin = await waitFor( () => activeServer!.monitoringService.getLatest('srv-1')?.sample,