security(auth,ws): fix Auth/TOTP/WebAuthn/bootstrap vulnerabilities, session idle TTL & real-time WS revocation

This commit is contained in:
tyuXX 2026-11-27 22:31:37 +00:00
parent e3f716d24f
commit 1b2e425a00
13 changed files with 1248 additions and 477 deletions

View file

@ -284,7 +284,7 @@ async function syncStatusAndRender(): Promise<void> {
authenticated: boolean; authenticated: boolean;
safeMode?: boolean; safeMode?: boolean;
elevatedUntil?: number | null; elevatedUntil?: number | null;
vaultState: ClientState['vaultState']; vaultState?: ClientState['vaultState'];
vaultRuntimeReady?: boolean; vaultRuntimeReady?: boolean;
isPanicLocked?: boolean; isPanicLocked?: boolean;
defaultMobileSafeMode: boolean; defaultMobileSafeMode: boolean;
@ -295,8 +295,8 @@ async function syncStatusAndRender(): Promise<void> {
state.bootstrapped = status.bootstrapped; state.bootstrapped = status.bootstrapped;
state.authenticated = status.authenticated; state.authenticated = status.authenticated;
state.vaultState = status.vaultState; state.vaultState = status.vaultState ?? 'locked';
state.vaultRuntimeReady = status.vaultRuntimeReady ?? status.vaultState === 'unlocked'; state.vaultRuntimeReady = status.vaultRuntimeReady ?? false;
state.isPanicLocked = Boolean(status.isPanicLocked); state.isPanicLocked = Boolean(status.isPanicLocked);
state.defaultMobileSafeMode = status.defaultMobileSafeMode; state.defaultMobileSafeMode = status.defaultMobileSafeMode;
state.elevatedUntil = status.elevatedUntil ?? null; state.elevatedUntil = status.elevatedUntil ?? null;

View file

@ -85,13 +85,13 @@ export interface ClientAuthRequirements {
requireTotpOnLogin: boolean; requireTotpOnLogin: boolean;
passwordMode: 'any' | 'all'; passwordMode: 'any' | 'all';
passwordCount: number; passwordCount: number;
passwordLabels: Array<{ id: string; label: string }>; passwordLabels?: Array<{ id: string; label: string }>;
totpMode: 'any' | 'all'; totpMode: 'any' | 'all';
totpCount: number; totpCount: number;
totpLabels: Array<{ id: string; label: string }>; totpLabels?: Array<{ id: string; label: string }>;
passkeyCount: number; passkeyCount: number;
stepUpPolicy: ClientSecuritySettings['stepUpPolicy']; stepUpPolicy?: ClientSecuritySettings['stepUpPolicy'];
stepUpMethod: ClientSecuritySettings['stepUpMethod']; stepUpMethod?: ClientSecuritySettings['stepUpMethod'];
} }
export interface ClientState { export interface ClientState {

View file

@ -7,9 +7,11 @@ import {
import { getPasskeyAssertion, isWebAuthnSupported } from '../webauthn.js'; import { getPasskeyAssertion, isWebAuthnSupported } from '../webauthn.js';
interface BootstrapData { interface BootstrapData {
bootstrapToken?: string;
secretBase32: string; secretBase32: string;
otpauthUri: string; otpauthUri: string;
qrSvg: string; qrSvg: string;
qrDataUri?: string;
} }
export async function renderAuthView( export async function renderAuthView(
@ -87,9 +89,11 @@ export async function renderAuthView(
}); });
let secretBase32 = ''; let secretBase32 = '';
let bootstrapToken = '';
try { try {
const data = await apiFetch<BootstrapData>('/api/auth/bootstrap'); const data = await apiFetch<BootstrapData>('/api/auth/bootstrap');
secretBase32 = data.secretBase32; secretBase32 = data.secretBase32;
bootstrapToken = data.bootstrapToken ?? '';
const doc = new DOMParser().parseFromString(data.qrSvg, 'image/svg+xml'); const doc = new DOMParser().parseFromString(data.qrSvg, 'image/svg+xml');
if (doc.documentElement.nodeName === 'svg') { if (doc.documentElement.nodeName === 'svg') {
qrContainer.append(document.importNode(doc.documentElement, true)); qrContainer.append(document.importNode(doc.documentElement, true));
@ -134,6 +138,7 @@ export async function renderAuthView(
password: passInput.value, password: passInput.value,
totpCode: codeInput.value.trim(), totpCode: codeInput.value.trim(),
secretBase32, secretBase32,
...(bootstrapToken ? { bootstrapToken } : {}),
initialSafeMode, initialSafeMode,
securityPreset: presetSelect.value, securityPreset: presetSelect.value,
}, },
@ -283,7 +288,7 @@ export async function renderAuthView(
form.append(el('label', { for: 'login-username' }, 'Username'), userInput); form.append(el('label', { for: 'login-username' }, 'Username'), userInput);
const passwordInputs: HTMLInputElement[] = []; 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++) { for (let i = 0; i < pwCount; i++) {
const labelText = const labelText =
pwMode === 'all' ? `Password — ${pwLabels[i]?.label ?? `#${i + 1}`}` : 'Password'; pwMode === 'all' ? `Password — ${pwLabels[i]?.label ?? `#${i + 1}`}` : 'Password';
@ -310,7 +315,7 @@ export async function renderAuthView(
const codeInputs: HTMLInputElement[] = []; const codeInputs: HTMLInputElement[] = [];
if (requireTotp) { 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++) { for (let i = 0; i < totpCount; i++) {
const labelText = const labelText =
totpMode === 'all' totpMode === 'all'

View file

@ -837,7 +837,10 @@ export async function renderSettingsView(
dlBackupBtn.addEventListener('click', async () => { dlBackupBtn.addEventListener('click', async () => {
bMsg.textContent = ''; bMsg.textContent = '';
try { 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`], { const blob = new Blob([`${JSON.stringify(res.bundle, null, 2)}\n`], {
type: 'application/json', type: 'application/json',
}); });

View file

@ -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 { z } from 'zod';
import type { import type {
AuthenticationResponseJSON, AuthenticationResponseJSON,
RegistrationResponseJSON, RegistrationResponseJSON,
} from '@simplewebauthn/server'; } from '@simplewebauthn/server';
import { SecuritySettingsSchema } from '../../../shared/schemas/settings.schema.js';
import type { ConfigManager } from '../../config/config-manager.js'; import type { ConfigManager } from '../../config/config-manager.js';
import type { AuditService } from '../../security/audit.js'; import type { AuditService } from '../../security/audit.js';
import { SESSION_COOKIE_NAME, type AuthService } from '../../security/auth.js';
import { import {
AuthOverloadError,
SESSION_COOKIE_NAME,
type AuthService,
} from '../../security/auth.js';
import {
asyncHandler,
createStepUpGuard, createStepUpGuard,
enforceSafeMode, enforceSafeMode,
extractCookies, extractCookies,
@ -28,6 +34,8 @@ export interface AuthRouterDeps {
recoveryStore: EmergencyRecoveryService; recoveryStore: EmergencyRecoveryService;
rateLimiter: RateLimiter; rateLimiter: RateLimiter;
trustCloudflare: boolean; trustCloudflare: boolean;
webauthnRpId?: string;
webauthnOrigins?: string[];
} }
function isSecureCookie(req: Request, trustCloudflare: boolean): boolean { function isSecureCookie(req: Request, trustCloudflare: boolean): boolean {
@ -44,9 +52,10 @@ function setAuthCookies(
sessionToken: string, sessionToken: string,
csrfToken: string, csrfToken: string,
trustCloudflare: boolean, trustCloudflare: boolean,
sessionTtlHours = 168,
): void { ): void {
const secure = isSecureCookie(req, trustCloudflare); 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, { res.cookie(SESSION_COOKIE_NAME, sessionToken, {
httpOnly: true, httpOnly: true,
sameSite: 'strict', sameSite: 'strict',
@ -76,6 +85,8 @@ class WebAuthnRpError extends Error {
function resolveWebAuthnRp( function resolveWebAuthnRp(
req: Request, req: Request,
trustCloudflare: boolean, trustCloudflare: boolean,
configuredRpId?: string,
configuredOrigins?: string[],
): { rpID: string; expectedOrigin: string } { ): { rpID: string; expectedOrigin: string } {
const originHeader = const originHeader =
typeof req.headers.origin === 'string' && req.headers.origin.trim() typeof req.headers.origin === 'string' && req.headers.origin.trim()
@ -92,10 +103,35 @@ function resolveWebAuthnRp(
throw new WebAuthnRpError('Invalid Origin header for WebAuthn request'); throw new WebAuthnRpError('Invalid Origin header for WebAuthn request');
} }
const rpID = parsed.hostname; if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
if (/^\d+\.\d+\.\d+\.\d+$/.test(rpID) || rpID.includes(':')) { 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( 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, recoveryStore,
rateLimiter, rateLimiter,
trustCloudflare, trustCloudflare,
webauthnRpId,
webauthnOrigins,
} = deps; } = deps;
const stepUpGuard = createStepUpGuard( const stepUpGuard = createStepUpGuard(
@ -133,11 +171,16 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
res.json({ res.json({
bootstrapped, bootstrapped,
authenticated: false, authenticated: false,
vaultState: vaultService.state,
vaultRuntimeReady: vaultService.isRuntimeReady,
defaultMobileSafeMode: settings.defaultMobileSafeMode, defaultMobileSafeMode: settings.defaultMobileSafeMode,
theme: settings.theme, theme: settings.theme,
authRequirements, authRequirements: {
requireTotpOnLogin: authRequirements.requireTotpOnLogin,
passwordMode: authRequirements.passwordMode,
passwordCount: authRequirements.passwordCount,
totpMode: authRequirements.totpMode,
totpCount: authRequirements.totpCount,
passkeyCount: authRequirements.passkeyCount,
},
}); });
return; return;
} }
@ -148,196 +191,231 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
safeMode: session.safeMode, safeMode: session.safeMode,
elevatedUntil: session.elevatedUntil, elevatedUntil: session.elevatedUntil,
vaultState: vaultService.state, vaultState: vaultService.state,
sealState: vaultService.sealState,
vaultRuntimeReady: vaultService.isRuntimeReady, vaultRuntimeReady: vaultService.isRuntimeReady,
isPanicLocked: vaultService.isPanicLocked, isPanicLocked: vaultService.isPanicLocked,
defaultMobileSafeMode: settings.defaultMobileSafeMode, defaultMobileSafeMode: settings.defaultMobileSafeMode,
theme: settings.theme, theme: settings.theme,
security: settings.security, security: settings.security,
runtime: settings.runtime,
authRequirements, authRequirements,
}); });
}); });
router.get('/bootstrap', async (req, res) => { router.get(
if (authService.isBootstrapped()) { '/bootstrap',
res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); asyncHandler(async (req, res) => {
return; if (authService.isBootstrapped()) {
} res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' });
const username = return;
typeof req.query.username === 'string' && req.query.username.trim() }
? req.query.username.trim() const rawUser =
: 'admin'; typeof req.query.username === 'string' && req.query.username.trim()
const data = await authService.beginBootstrap(username); ? req.query.username.trim().slice(0, 64)
res.json(data); : 'admin';
}); const data = await authService.beginBootstrap(rawUser);
res.json(data);
}),
);
router.post('/bootstrap', async (req, res) => { router.post(
if (authService.isBootstrapped()) { '/bootstrap',
res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); asyncHandler(async (req, res) => {
return; if (authService.isBootstrapped()) {
} res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' });
const ip = req.clientIp ?? 'unknown'; return;
const rate = rateLimiter.check('bootstrap', ip); }
if (!rate.allowed) { const ip = req.clientIp ?? 'unknown';
res.setHeader('Retry-After', String(rate.retryAfterSec)); const rate = rateLimiter.check('bootstrap', ip);
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); if (!rate.allowed) {
return; 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}`,
);
} }
const result = await authService.completeBootstrap({ const bodySchema = z.object({
...parsed.data, username: z.string().trim().min(2).max(64).default('admin'),
ip, password: z.string().min(10).max(256),
userAgent: String(req.headers['user-agent'] ?? 'unknown'), totpCode: z.string().regex(/^\d{6}$/, 'TOTP code must be 6 digits'),
}); secretBase32: z.string().max(128).optional(),
rateLimiter.recordSuccess('bootstrap', ip); bootstrapToken: z.string().min(16).max(128).optional(),
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(),
initialSafeMode: z.boolean().optional(), initialSafeMode: z.boolean().optional(),
}) securityPreset: z.enum(['relaxed', 'balanced', 'strict']).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',
}); });
res.status(401).json({ error: 'INVALID_CREDENTIALS' }); const parsed = bodySchema.safeParse(req.body);
return; if (!parsed.success) {
} rateLimiter.recordFailure('bootstrap', ip);
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return;
}
rateLimiter.recordSuccess('login', ip); try {
setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare); const result = await authService.completeBootstrap({
auditService.log({ ...parsed.data,
action: 'auth.login', ip,
actorIp: ip, userAgent: String(req.headers['user-agent'] ?? 'unknown'),
sessionIdHash: result.session.idHash, });
target: parsed.data.username ?? 'admin',
status: 'ok',
});
res.json({ if (parsed.data.securityPreset) {
authenticated: true, const cur = configManager.getSettings();
csrfToken: result.csrfToken, const presetSecurity =
safeMode: result.session.safeMode, parsed.data.securityPreset === 'relaxed'
elevatedUntil: result.session.elevatedUntil, ? {
vaultState: vaultService.state, ...cur.security,
vaultRuntimeReady: vaultService.isRuntimeReady, 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 // Exempt from enforceSafeMode
router.post('/logout', requireAuth(authService), requireCsrf, (req, res) => { router.post('/logout', requireAuth(authService), requireCsrf, (req, res) => {
@ -383,7 +461,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
requireAuth(authService), requireAuth(authService),
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
async (req, res) => { asyncHandler(async (req, res) => {
const ip = req.clientIp ?? 'unknown'; const ip = req.clientIp ?? 'unknown';
const rate = rateLimiter.check('step-up', ip); const rate = rateLimiter.check('step-up', ip);
if (!rate.allowed) { if (!rate.allowed) {
@ -394,10 +472,10 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
const parsed = z const parsed = z
.object({ .object({
code: z.string().optional(), code: z.string().max(64).optional(),
codes: z.array(z.string()).optional(), codes: z.array(z.string().max(64)).max(16).optional(),
password: z.string().optional(), password: z.string().max(256).optional(),
passwords: z.array(z.string()).optional(), passwords: z.array(z.string().max(256)).max(16).optional(),
}) })
.safeParse(req.body ?? {}); .safeParse(req.body ?? {});
if (!parsed.success) { if (!parsed.success) {
@ -407,7 +485,12 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
const outcome = await authService.stepUp(req.authSession!.idHash, parsed.data); const outcome = await authService.stepUp(req.authSession!.idHash, parsed.data);
if (!outcome.ok) { 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({ auditService.log({
action: 'auth.step_up', action: 'auth.step_up',
actorIp: ip, actorIp: ip,
@ -430,7 +513,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
status: 'ok', status: 'ok',
}); });
res.json({ elevatedUntil: outcome.elevatedUntil }); res.json({ elevatedUntil: outcome.elevatedUntil });
}, }),
); );
router.post('/drop-elevation', requireAuth(authService), requireCsrf, (req, res) => { router.post('/drop-elevation', requireAuth(authService), requireCsrf, (req, res) => {
@ -627,7 +710,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
stepUpGuard, stepUpGuard,
async (req, res) => { asyncHandler(async (req, res) => {
const parsed = z const parsed = z
.object({ label: z.string().min(1).max(64).default('Passkey') }) .object({ label: z.string().min(1).max(64).default('Passkey') })
.safeParse(req.body ?? {}); .safeParse(req.body ?? {});
@ -636,7 +719,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
return; return;
} }
try { try {
const rp = resolveWebAuthnRp(req, trustCloudflare); const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins);
const data = await authService.beginPasskeyRegistration({ const data = await authService.beginPasskeyRegistration({
label: parsed.data.label, label: parsed.data.label,
...rp, ...rp,
@ -648,7 +731,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
message: err instanceof Error ? err.message : 'Unable to start passkey registration', message: err instanceof Error ? err.message : 'Unable to start passkey registration',
}); });
} }
}, }),
); );
router.post( router.post(
@ -657,10 +740,10 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
stepUpGuard, stepUpGuard,
async (req, res) => { asyncHandler(async (req, res) => {
const parsed = z const parsed = z
.object({ .object({
challengeId: z.string().min(1), challengeId: z.string().min(1).max(128),
response: z.record(z.unknown()), response: z.record(z.unknown()),
}) })
.safeParse(req.body ?? {}); .safeParse(req.body ?? {});
@ -687,7 +770,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
message: err instanceof Error ? err.message : 'Unable to verify passkey registration', message: err instanceof Error ? err.message : 'Unable to verify passkey registration',
}); });
} }
}, }),
); );
router.delete( router.delete(
@ -721,102 +804,115 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
}, },
); );
router.post('/passkeys/login/options', async (req, res) => { router.post(
if (!authService.isBootstrapped()) { '/passkeys/login/options',
res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); asyncHandler(async (req, res) => {
return; if (!authService.isBootstrapped()) {
} res.status(409).json({ error: 'NOT_BOOTSTRAPPED' });
const ip = req.clientIp ?? 'unknown'; return;
const rate = rateLimiter.check('login', ip); }
if (!rate.allowed) { const ip = req.clientIp ?? 'unknown';
res.setHeader('Retry-After', String(rate.retryAfterSec)); const rate = rateLimiter.check('login', ip);
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); if (!rate.allowed) {
return; res.setHeader('Retry-After', String(rate.retryAfterSec));
} res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
try { return;
const rp = resolveWebAuthnRp(req, trustCloudflare); }
const data = await authService.beginPasskeyAuthentication({ try {
purpose: 'login', const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins);
...rp, 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); if (!result) {
} catch (err) { const failState = rateLimiter.recordFailure('login', ip);
res.status(400).json({ if (failState.lockedUntil > 0 || failState.globalTriggered) {
error: err instanceof WebAuthnRpError ? err.code : 'PASSKEY_LOGIN_OPTIONS_FAILED', authService.emitSecurityEvent('auth.lockout', ip, {
message: err instanceof Error ? err.message : 'No passkeys available', 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) => { const ttlHours = configManager.getSettings().security.sessionTtlHours;
if (!authService.isBootstrapped()) { rateLimiter.recordSuccess('login', ip);
res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare, ttlHours);
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);
auditService.log({ auditService.log({
action: 'auth.passkey_login', action: 'auth.passkey_login',
actorIp: ip, actorIp: ip,
status: 'denied', sessionIdHash: result.session.idHash,
status: 'ok',
}); });
res.status(401).json({ error: 'INVALID_PASSKEY_ASSERTION' });
return;
}
rateLimiter.recordSuccess('login', ip); res.json({
setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare); authenticated: true,
auditService.log({ csrfToken: result.csrfToken,
action: 'auth.passkey_login', safeMode: result.session.safeMode,
actorIp: ip, elevatedUntil: result.session.elevatedUntil,
sessionIdHash: result.session.idHash, vaultState: vaultService.state,
status: 'ok', 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( router.post(
'/passkeys/step-up/options', '/passkeys/step-up/options',
requireAuth(authService), requireAuth(authService),
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
async (req, res) => { asyncHandler(async (req, res) => {
const ip = req.clientIp ?? 'unknown'; const ip = req.clientIp ?? 'unknown';
const rate = rateLimiter.check('step-up', ip); const rate = rateLimiter.check('step-up', ip);
if (!rate.allowed) { if (!rate.allowed) {
@ -825,7 +921,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
return; return;
} }
try { try {
const rp = resolveWebAuthnRp(req, trustCloudflare); const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins);
const data = await authService.beginPasskeyAuthentication({ const data = await authService.beginPasskeyAuthentication({
purpose: 'stepup', purpose: 'stepup',
sessionIdHash: req.authSession!.idHash, 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', message: err instanceof Error ? err.message : 'Unable to start passkey verification',
}); });
} }
}, }),
); );
router.post( router.post(
@ -846,7 +942,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
requireAuth(authService), requireAuth(authService),
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
async (req, res) => { asyncHandler(async (req, res) => {
const ip = req.clientIp ?? 'unknown'; const ip = req.clientIp ?? 'unknown';
const rate = rateLimiter.check('step-up', ip); const rate = rateLimiter.check('step-up', ip);
if (!rate.allowed) { if (!rate.allowed) {
@ -856,7 +952,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
} }
const parsed = z const parsed = z
.object({ .object({
challengeId: z.string().min(1), challengeId: z.string().min(1).max(128),
response: z.record(z.unknown()), response: z.record(z.unknown()),
}) })
.safeParse(req.body ?? {}); .safeParse(req.body ?? {});
@ -894,6 +990,46 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
status: 'ok', status: 'ok',
}); });
res.json({ elevatedUntil: outcome.elevatedUntil }); 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<string, unknown>)
: 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', '/recovery-backup/export',
requireAuth(authService), requireAuth(authService),
requireCsrf,
enforceSafeMode,
stepUpGuard, stepUpGuard,
(req, res) => { (req, res) => {
const settings = configManager.getSettings(); 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; return router;
} }

View file

@ -5,10 +5,18 @@ import {
ClientWsFrameSchema, ClientWsFrameSchema,
type ServerWsFrame, type ServerWsFrame,
} from '../../shared/ws-protocol.js'; } 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 { extractCookies } from '../security/guards.js';
import type { VaultService } from '../security/vault.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 { interface WsClientMeta {
ws: WebSocket; ws: WebSocket;
sessionToken: string; sessionToken: string;
@ -42,25 +50,41 @@ export interface WsAiHandlers {
} }
export class WsHub { 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<WsClientMeta>(); private readonly clients = new Set<WsClientMeta>();
private readonly pingTimer: NodeJS.Timeout; private readonly pingTimer: NodeJS.Timeout;
private readonly upgradeHandlers: Array<{ prefix: string; handler: WsUpgradeHandler }> = []; private readonly upgradeHandlers: Array<{ prefix: string; handler: WsUpgradeHandler }> = [];
private readonly subscribeListeners = new Set<WsSubscribeListener>(); private readonly subscribeListeners = new Set<WsSubscribeListener>();
private ptyHandlers: WsPtyHandlers | null = null; private ptyHandlers: WsPtyHandlers | null = null;
private aiHandlers: WsAiHandlers | null = null; private aiHandlers: WsAiHandlers | null = null;
private readonly trustCloudflare: boolean;
constructor( constructor(
httpServer: HttpServer, httpServer: HttpServer,
private readonly authService: AuthService, private readonly authService: AuthService,
private readonly vaultService: VaultService, private readonly vaultService: VaultService,
options: { trustCloudflare?: boolean } = {},
) { ) {
this.trustCloudflare = Boolean(options.trustCloudflare);
httpServer.on('upgrade', (req, socket, head) => { httpServer.on('upgrade', (req, socket, head) => {
this.handleUpgrade(req, socket, head); this.handleUpgrade(req, socket, head);
}); });
this.pingTimer = setInterval(() => { this.pingTimer = setInterval(() => {
for (const client of this.clients) { 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) { if (!client.alive) {
client.ws.terminate(); client.ws.terminate();
this.clients.delete(client); this.clients.delete(client);
@ -73,6 +97,24 @@ export class WsHub {
this.pingTimer.unref(); 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 { registerUpgradeHandler(prefix: string, handler: WsUpgradeHandler): void {
this.upgradeHandlers.push({ prefix, handler }); this.upgradeHandlers.push({ prefix, handler });
} }
@ -118,21 +160,18 @@ export class WsHub {
broadcastAll(frame: ServerWsFrame): void { broadcastAll(frame: ServerWsFrame): void {
const text = JSON.stringify(frame); const text = JSON.stringify(frame);
const critical = frame.type === 'security:panic-lock' || frame.type === 'vault:state';
for (const client of this.clients) { for (const client of this.clients) {
if (client.ws.readyState === WebSocket.OPEN) { this.safeSendRaw(client, text, critical);
client.ws.send(text);
}
} }
} }
broadcastChannel(channel: string, frame: ServerWsFrame): void { broadcastChannel(channel: string, frame: ServerWsFrame): void {
const text = JSON.stringify(frame); const text = JSON.stringify(frame);
const critical = frame.type === 'pty:exit' || frame.type === 'error';
for (const client of this.clients) { for (const client of this.clients) {
if ( if (client.channels.has(channel)) {
client.ws.readyState === WebSocket.OPEN && this.safeSendRaw(client, text, critical);
(client.channels.has(channel) || client.channels.has('*'))
) {
client.ws.send(text);
} }
} }
} }
@ -155,13 +194,29 @@ export class WsHub {
return; 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 origin = req.headers.origin;
const host = req.headers.host; const host = req.headers.host;
if (origin && host) { if (origin) {
try { try {
const originUrl = new URL(origin); 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.write('HTTP/1.1 403 Forbidden\r\n\r\n');
socket.destroy(); socket.destroy();
return; 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) => { this.wss.handleUpgrade(req, socket, head, (ws) => {
const meta: WsClientMeta = { const meta: WsClientMeta = {
ws, ws,
@ -193,13 +239,17 @@ export class WsHub {
}; };
this.clients.add(meta); this.clients.add(meta);
this.sendFrame(ws, { this.sendFrame(
type: 'hello', ws,
vaultState: this.vaultService.state, {
vaultRuntimeReady: this.vaultService.isRuntimeReady, type: 'hello',
safeMode: session.safeMode, vaultState: this.vaultService.state,
elevatedUntil: session.elevatedUntil, vaultRuntimeReady: this.vaultService.isRuntimeReady,
}); safeMode: session.safeMode,
elevatedUntil: session.elevatedUntil,
},
true,
);
ws.on('pong', () => { ws.on('pong', () => {
meta.alive = true; 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 { private onMessage(meta: WsClientMeta, raw: unknown): void {
let parsedJson: unknown; let parsedJson: unknown;
try { try {
const text = typeof raw === 'string' ? raw : Buffer.from(raw as Buffer).toString('utf8'); const text = typeof raw === 'string' ? raw : Buffer.from(raw as Buffer).toString('utf8');
parsedJson = JSON.parse(text); parsedJson = JSON.parse(text);
} catch { } catch {
this.sendFrame(meta.ws, { this.sendFrame(
type: 'error', meta.ws,
code: 'BAD_JSON', {
message: 'Invalid WebSocket JSON frame', type: 'error',
}); code: 'BAD_JSON',
message: 'Invalid WebSocket JSON frame',
},
true,
);
return; return;
} }
const result = ClientWsFrameSchema.safeParse(parsedJson); const result = ClientWsFrameSchema.safeParse(parsedJson);
if (!result.success) { if (!result.success) {
this.sendFrame(meta.ws, { this.sendFrame(
type: 'error', meta.ws,
code: 'INVALID_FRAME', {
message: 'Unrecognized or malformed WebSocket frame', type: 'error',
}); code: 'INVALID_FRAME',
message: 'Unrecognized or malformed WebSocket frame',
},
true,
);
return; return;
} }
const frame = result.data; const frame = result.data;
switch (frame.type) { switch (frame.type) {
case 'ping': case 'ping': {
this.sendFrame(meta.ws, { if (!this.ensureActiveSession(meta)) return;
type: 'pong', this.sendFrame(
ts: frame.ts, meta.ws,
serverTs: Date.now(), {
}); type: 'pong',
ts: frame.ts,
serverTs: Date.now(),
},
true,
);
break; break;
}
case 'sub': { case 'sub': {
if (!this.ensureActiveSession(meta)) return;
const ctx = { const ctx = {
send: (outFrame: ServerWsFrame) => this.sendFrame(meta.ws, outFrame), send: (outFrame: ServerWsFrame) => this.sendFrame(meta.ws, outFrame),
sessionIdHash: meta.sessionIdHash, sessionIdHash: meta.sessionIdHash,
@ -274,44 +353,78 @@ export class WsHub {
meta.channels.delete(ch); meta.channels.delete(ch);
} }
break; break;
case 'safe-mode': case 'safe-mode': {
meta.clientSafeMode = frame.enabled; const latestSession = this.ensureActiveSession(meta);
if (!latestSession) return;
meta.clientSafeMode = latestSession.safeMode || frame.enabled;
break; break;
}
case 'pty:input': { case 'pty:input': {
const latestSession = this.authService.getSessionByToken(meta.sessionToken); const latestSession = this.ensureActiveSession(meta);
if (!latestSession) { if (!latestSession) return;
meta.ws.close(4001, 'Session expired');
return;
}
if (latestSession.safeMode || meta.clientSafeMode) { if (latestSession.safeMode || meta.clientSafeMode) {
this.sendFrame(meta.ws, { this.sendFrame(
type: 'error', meta.ws,
code: 'SAFE_MODE_ACTIVE', {
message: 'Safe / Read-Only Mode blocks terminal input.', type: 'error',
}); code: 'SAFE_MODE_ACTIVE',
message: 'Safe / Read-Only Mode blocks terminal input.',
},
true,
);
return; return;
} }
this.ptyHandlers?.onInput(frame.sessionId, frame.data); this.ptyHandlers?.onInput(frame.sessionId, frame.data);
break; break;
} }
case 'pty:resize': { case 'pty:resize': {
const latestSession = this.authService.getSessionByToken(meta.sessionToken); if (!this.ensureActiveSession(meta)) return;
if (!latestSession) {
meta.ws.close(4001, 'Session expired');
return;
}
this.ptyHandlers?.onResize(frame.sessionId, frame.cols, frame.rows); this.ptyHandlers?.onResize(frame.sessionId, frame.cols, frame.rows);
break; 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); this.aiHandlers?.onCancel(frame.chatId);
break; break;
}
} }
} }
private sendFrame(ws: WebSocket, frame: ServerWsFrame): void { private safeSendRaw(client: WsClientMeta, payload: string, critical = false): void {
if (ws.readyState === WebSocket.OPEN) { if (client.ws.readyState !== WebSocket.OPEN) return;
ws.send(JSON.stringify(frame)); 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));
} }
} }

View file

@ -56,6 +56,7 @@ export interface ServerOptions {
publicDir?: string; publicDir?: string;
secretFilePath?: string; secretFilePath?: string;
envMasterKey?: string; envMasterKey?: string;
envDbKey?: string;
trustCloudflare?: boolean; trustCloudflare?: boolean;
trustedProxyCidrs?: string[]; trustedProxyCidrs?: string[];
allowLanTunnels?: boolean; allowLanTunnels?: boolean;
@ -135,8 +136,11 @@ export async function createGCoordinatorServer(
const authService = new AuthService(db, { const authService = new AuthService(db, {
getSecuritySettings: () => configManager.getSettings().security, getSecuritySettings: () => configManager.getSettings().security,
getRuntimeLimits,
recoveryStore, recoveryStore,
vaultService, vaultService,
dataDir,
envDbKey: options.envDbKey,
}); });
const backupKey = configManager.getSettings().security.enableEmergencySecretsBackup const backupKey = configManager.getSettings().security.enableEmergencySecretsBackup
@ -163,7 +167,10 @@ export async function createGCoordinatorServer(
} }
const httpServer = http.createServer(app); 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 knownHosts = new KnownHostsService(db, auditService);
const sshPool = new SSHPool(configManager, vaultService, knownHosts); const sshPool = new SSHPool(configManager, vaultService, knownHosts);
@ -374,8 +381,8 @@ export async function createGCoordinatorServer(
tunnelManager.stopAll(); tunnelManager.stopAll();
ptyManager.closeAll(true); ptyManager.closeAll(true);
sshPool.closeAll('panic_lock'); sshPool.closeAll('panic_lock');
authService.revokeAllSessions();
wsHub.handlePanicLock(); wsHub.handlePanicLock();
authService.revokeAllSessions();
}); });
configManager.onChange((event) => { configManager.onChange((event) => {
@ -437,6 +444,8 @@ export async function createGCoordinatorServer(
recoveryStore, recoveryStore,
rateLimiter, rateLimiter,
trustCloudflare, trustCloudflare,
webauthnRpId: options.webauthnRpId,
webauthnOrigins: options.webauthnOrigins,
}), }),
); );
@ -628,6 +637,7 @@ export async function createGCoordinatorServer(
tunnelManager.stopAll(); tunnelManager.stopAll();
ptyManager.close(); ptyManager.close();
sshPool.closeAll('shutdown'); sshPool.closeAll('shutdown');
authService.close();
wsHub.close(); wsHub.close();
await configManager.close(); await configManager.close();
await new Promise<void>((resolve) => { await new Promise<void>((resolve) => {

View file

@ -20,6 +20,7 @@ async function main(): Promise<void> {
const secretFilePath = const secretFilePath =
process.env.GCOORD_MASTER_KEY_FILE ?? '/run/secrets/gcoord_master_key'; process.env.GCOORD_MASTER_KEY_FILE ?? '/run/secrets/gcoord_master_key';
const envMasterKey = process.env.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 proxyPortRaw = process.env.GCOORD_PROXY_PORT ? Number(process.env.GCOORD_PROXY_PORT) : undefined;
const instance = await createGCoordinatorServer({ const instance = await createGCoordinatorServer({
@ -28,6 +29,7 @@ async function main(): Promise<void> {
host, host,
secretFilePath, secretFilePath,
envMasterKey, envMasterKey,
envDbKey,
trustCloudflare, trustCloudflare,
trustedProxyCidrs, trustedProxyCidrs,
allowLanTunnels: process.env.GCOORD_ALLOW_LAN_TUNNELS === 'true', allowLanTunnels: process.env.GCOORD_ALLOW_LAN_TUNNELS === 'true',

View file

@ -1,4 +1,6 @@
import crypto from 'node:crypto'; import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { import {
generateAuthenticationOptions, generateAuthenticationOptions,
generateRegistrationOptions, generateRegistrationOptions,
@ -17,18 +19,120 @@ import {
type SecuritySettings, type SecuritySettings,
type StepUpPolicy, type StepUpPolicy,
} from '../../shared/schemas/settings.schema.js'; } from '../../shared/schemas/settings.schema.js';
import type { RuntimeLimits } from '../config/runtime-limits.js';
import type { EmergencyRecoveryService, SavedTotpEntry } from './recovery-store.js'; import type { EmergencyRecoveryService, SavedTotpEntry } from './recovery-store.js';
import type { VaultService } from './vault.js'; import type { VaultService } from './vault.js';
const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000;
const BOOTSTRAP_TTL_MS = 15 * 60 * 1000; const BOOTSTRAP_TTL_MS = 15 * 60 * 1000;
const WEBAUTHN_TTL_MS = 5 * 60 * 1000; const WEBAUTHN_TTL_MS = 5 * 60 * 1000;
const SESSION_REAPER_MS = 5 * 60 * 1000;
const TOTP_PERIOD_SEC = 30; const TOTP_PERIOD_SEC = 30;
const DEFAULT_SECURITY = SecuritySettingsSchema.parse({}); const DEFAULT_SECURITY = SecuritySettingsSchema.parse({});
export const SESSION_COOKIE_NAME = 'gcoord_sid'; 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 { export interface AuthSession {
idHash: string; idHash: string;
csrfTokenHash: string; csrfTokenHash: string;
@ -96,8 +200,16 @@ export type StepUpInput =
export interface AuthServiceOptions { export interface AuthServiceOptions {
getSecuritySettings?: () => SecuritySettings; getSecuritySettings?: () => SecuritySettings;
getRuntimeLimits?: () => RuntimeLimits;
recoveryStore?: EmergencyRecoveryService; recoveryStore?: EmergencyRecoveryService;
vaultService?: VaultService; vaultService?: VaultService;
dataDir?: string;
envDbKey?: string;
onSecurityEvent?: (event: {
type: string;
ip?: string;
details?: Record<string, unknown>;
}) => void;
} }
interface AdminRow { interface AdminRow {
@ -120,8 +232,10 @@ interface TotpRow {
id: string; id: string;
label: string; label: string;
secret_base32: string; secret_base32: string;
secret_enc: string | null;
last_login_step: number | null; last_login_step: number | null;
last_stepup_step: number | null; last_stepup_step: number | null;
last_used_step: number | null;
created_at: number; created_at: number;
} }
@ -191,13 +305,21 @@ function computeElevatedUntil(
} }
export class AuthService { 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< private readonly pendingEnrollments = new Map<
string, string,
{ label: string; secretBase32: string; createdAt: number } { label: string; secretBase32: string; createdAt: number }
>(); >();
private readonly pendingWebAuthn = new Map<string, PendingWebAuthnChallenge>(); private readonly pendingWebAuthn = new Map<string, PendingWebAuthnChallenge>();
private readonly sessionRevokedListeners = new Set<(idHashes: string[]) => void>();
private readonly getSecurity: () => SecuritySettings; 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 recoveryStore?: EmergencyRecoveryService;
private vaultService?: VaultService; private vaultService?: VaultService;
@ -206,8 +328,169 @@ export class AuthService {
options: AuthServiceOptions = {}, options: AuthServiceOptions = {},
) { ) {
this.getSecurity = options.getSecuritySettings ?? (() => DEFAULT_SECURITY); this.getSecurity = options.getSecuritySettings ?? (() => DEFAULT_SECURITY);
this.getRuntimeLimits = options.getRuntimeLimits;
this.onSecurityEvent = options.onSecurityEvent;
this.recoveryStore = options.recoveryStore; this.recoveryStore = options.recoveryStore;
this.vaultService = options.vaultService; 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<string, unknown>): 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<T>(task: (memoryCost: number) => Promise<T>): Promise<T> {
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<void>((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<string> {
return this.runArgon2((memoryCost) =>
argon2.hash(password, {
type: argon2.argon2id,
memoryCost,
timeCost: 3,
parallelism: 1,
}),
);
}
private verifyPasswordHash(hash: string, candidate: string): Promise<boolean> {
return this.runArgon2(() => argon2.verify(hash, candidate).catch(() => false));
}
private async verifyDummyPassword(candidate: string): Promise<void> {
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( attachRecoveryDependencies(
@ -259,9 +542,11 @@ export class AuthService {
} }
async beginBootstrap(username = 'admin'): Promise<{ async beginBootstrap(username = 'admin'): Promise<{
bootstrapToken: string;
secretBase32: string; secretBase32: string;
otpauthUri: string; otpauthUri: string;
qrSvg: string; qrSvg: string;
qrDataUri: string;
}> { }> {
if (this.isBootstrapped()) { if (this.isBootstrapped()) {
throw new Error('Admin account is already configured'); throw new Error('Admin account is already configured');
@ -274,17 +559,24 @@ export class AuthService {
const secret = new OTPAuth.Secret({ size: 20 }); const secret = new OTPAuth.Secret({ size: 20 });
this.pendingBootstrap = { this.pendingBootstrap = {
secretBase32: secret.base32, secretBase32: secret.base32,
token: crypto.randomBytes(24).toString('base64url'),
createdAt: Date.now(), 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 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 { return {
bootstrapToken: this.pendingBootstrap.token,
secretBase32: this.pendingBootstrap.secretBase32, secretBase32: this.pendingBootstrap.secretBase32,
otpauthUri, otpauthUri,
qrSvg, qrSvg,
qrDataUri,
}; };
} }
@ -293,6 +585,7 @@ export class AuthService {
password: string; password: string;
totpCode: string; totpCode: string;
secretBase32?: string; secretBase32?: string;
bootstrapToken?: string;
ip: string; ip: string;
userAgent: string; userAgent: string;
initialSafeMode?: boolean; initialSafeMode?: boolean;
@ -313,11 +606,30 @@ export class AuthService {
throw new Error('Password must be at least 10 characters'); throw new Error('Password must be at least 10 characters');
} }
const secretBase32 = params.secretBase32 ?? this.pendingBootstrap?.secretBase32; if (
if (!secretBase32) { !this.pendingBootstrap ||
Date.now() - this.pendingBootstrap.createdAt > BOOTSTRAP_TTL_MS
) {
this.pendingBootstrap = null;
throw new Error('Bootstrap enrollment session expired; reload setup'); 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 nowMs = Date.now();
const totp = buildTotp(secretBase32, username); const totp = buildTotp(secretBase32, username);
const delta = totp.validate({ const delta = totp.validate({
@ -330,12 +642,8 @@ export class AuthService {
} }
const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta; const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta;
const passwordHash = await argon2.hash(params.password, { const passwordHash = await this.hashPassword(params.password);
type: argon2.argon2id, const secretEnc = encryptTotpSecret(this.dbKey, 'totp-primary', secretBase32);
memoryCost: 65536,
timeCost: 3,
parallelism: 1,
});
const recoveryCodes: string[] = []; const recoveryCodes: string[] = [];
for (let i = 0; i < 8; i++) { for (let i = 0; i < 8; i++) {
@ -346,9 +654,9 @@ export class AuthService {
this.db this.db
.prepare( .prepare(
`INSERT INTO admin_users (id, username, password_hash, totp_secret, last_login_totp_step, last_stepup_totp_step, created_at, updated_at) `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 this.db
.prepare( .prepare(
@ -358,10 +666,10 @@ export class AuthService {
this.db this.db
.prepare( .prepare(
`INSERT INTO admin_totps (id, label, secret_base32, last_login_step, last_stepup_step, created_at) `INSERT INTO admin_totps (id, label, secret_base32, secret_enc, last_login_step, last_stepup_step, last_used_step, created_at)
VALUES (?, ?, ?, ?, NULL, ?)`, VALUES (?, ?, '', ?, ?, ?, ?, ?)`,
) )
.run('totp-primary', 'Primary Authenticator', secretBase32, matchedStep, nowMs); .run('totp-primary', 'Primary Authenticator', secretEnc, matchedStep, matchedStep, matchedStep, nowMs);
const insertRec = this.db.prepare( const insertRec = this.db.prepare(
'INSERT INTO recovery_codes (code_hash, used_at) VALUES (?, NULL)', 'INSERT INTO recovery_codes (code_hash, used_at) VALUES (?, NULL)',
@ -399,28 +707,35 @@ export class AuthService {
const admin = this.db const admin = this.db
.prepare('SELECT * FROM admin_users WHERE id = 1') .prepare('SELECT * FROM admin_users WHERE id = 1')
.get() as AdminRow | undefined; .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; return null;
} }
const sec = this.getSecurity(); 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); const pwOk = await this.verifyPasswords(suppliedPasswords, sec.passwordMode);
if (!pwOk) return null; if (!pwOk) return null;
const totpRows = this.listTotpRows(); if (sec.requireTotpOnLogin) {
if (sec.requireTotpOnLogin && totpRows.length > 0) {
const suppliedCodes = ( const suppliedCodes = (
params.codes ?? (params.code !== undefined ? [params.code] : []) params.codes ?? (params.code !== undefined ? [params.code] : [])
) )
.map((c) => c.trim()) .map((c) => c.trim())
.filter((c) => c.length > 0); .filter((c) => c.length > 0)
.slice(0, 16);
if (suppliedCodes.length === 0) return null; if (suppliedCodes.length === 0) return null;
@ -429,6 +744,7 @@ export class AuthService {
sec.totpMode, sec.totpMode,
'login', 'login',
admin.username, admin.username,
params.ip,
); );
if (!mfaOk) return null; if (!mfaOk) return null;
} }
@ -451,10 +767,24 @@ export class AuthService {
const now = Date.now(); const now = Date.now();
if (row.expires_at <= now) { if (row.expires_at <= now) {
this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash); this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash);
this.notifySessionsRevoked([idHash]);
return null; 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 this.db
.prepare('UPDATE sessions SET last_seen_at = ? WHERE id_hash = ?') .prepare('UPDATE sessions SET last_seen_at = ? WHERE id_hash = ?')
.run(now, idHash); .run(now, idHash);
@ -522,20 +852,17 @@ export class AuthService {
} }
if (sec.stepUpMethod === 'totp' || sec.stepUpMethod === 'both') { if (sec.stepUpMethod === 'totp' || sec.stepUpMethod === 'both') {
const totpRows = this.listTotpRows(); if (suppliedCodes.length === 0) {
if (totpRows.length > 0) { return { ok: false, reason: 'invalid_totp' };
if (suppliedCodes.length === 0) { }
return { ok: false, reason: 'invalid_totp' }; const totpResult = this.verifyTotpRows(
} suppliedCodes,
const totpResult = this.verifyTotpRows( sec.totpMode,
suppliedCodes, 'stepup',
sec.totpMode, admin.username,
'stepup', );
admin.username, if (!totpResult.ok) {
); return { ok: false, reason: totpResult.reason };
if (!totpResult.ok) {
return { ok: false, reason: totpResult.reason };
}
} }
} }
@ -680,7 +1007,7 @@ export class AuthService {
})), })),
authenticatorSelection: { authenticatorSelection: {
residentKey: 'preferred', residentKey: 'preferred',
userVerification: 'preferred', userVerification: 'required',
}, },
}); });
@ -711,7 +1038,7 @@ export class AuthService {
expectedChallenge: pending.challenge, expectedChallenge: pending.challenge,
expectedOrigin: pending.expectedOrigin, expectedOrigin: pending.expectedOrigin,
expectedRPID: pending.rpID, expectedRPID: pending.rpID,
requireUserVerification: false, requireUserVerification: true,
}); });
if (!verification.verified || !verification.registrationInfo) { if (!verification.verified || !verification.registrationInfo) {
@ -776,7 +1103,7 @@ export class AuthService {
? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[])
: undefined, : undefined,
})), })),
userVerification: 'preferred', userVerification: 'required',
}); });
const challengeId = crypto.randomBytes(16).toString('hex'); const challengeId = crypto.randomBytes(16).toString('hex');
@ -802,6 +1129,14 @@ export class AuthService {
if (!this.isBootstrapped()) return null; if (!this.isBootstrapped()) return null;
const pending = this.consumeWebAuthnChallenge(params.challengeId, 'login'); const pending = this.consumeWebAuthnChallenge(params.challengeId, 'login');
if (!pending) return null; 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 const row = this.db
.prepare('SELECT * FROM webauthn_credentials WHERE id = ?') .prepare('SELECT * FROM webauthn_credentials WHERE id = ?')
@ -822,7 +1157,7 @@ export class AuthService {
? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[])
: undefined, : undefined,
}, },
requireUserVerification: false, requireUserVerification: true,
}); });
if (!verification.verified) return null; if (!verification.verified) return null;
@ -857,11 +1192,22 @@ export class AuthService {
if (session.safe_mode === 1) { if (session.safe_mode === 1) {
return { ok: false, reason: 'safe_mode_active' }; 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'); const pending = this.consumeWebAuthnChallenge(params.challengeId, 'stepup');
if (!pending || pending.sessionIdHash !== params.idHash) { if (!pending || pending.sessionIdHash !== params.idHash) {
return { ok: false, reason: 'invalid_challenge' }; 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 const row = this.db
.prepare('SELECT * FROM webauthn_credentials WHERE id = ?') .prepare('SELECT * FROM webauthn_credentials WHERE id = ?')
@ -882,7 +1228,7 @@ export class AuthService {
? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[])
: undefined, : undefined,
}, },
requireUserVerification: false, requireUserVerification: true,
}); });
if (!verification.verified) { if (!verification.verified) {
return { ok: false, reason: 'invalid_assertion' }; return { ok: false, reason: 'invalid_assertion' };
@ -922,12 +1268,7 @@ export class AuthService {
const id = `pw-${crypto.randomBytes(4).toString('hex')}`; const id = `pw-${crypto.randomBytes(4).toString('hex')}`;
const createdAt = Date.now(); const createdAt = Date.now();
const hash = await argon2.hash(password, { const hash = await this.hashPassword(password);
type: argon2.argon2id,
memoryCost: 65536,
timeCost: 3,
parallelism: 1,
});
this.db this.db
.prepare( .prepare(
@ -962,6 +1303,7 @@ export class AuthService {
secretBase32: string; secretBase32: string;
otpauthUri: string; otpauthUri: string;
qrSvg: string; qrSvg: string;
qrDataUri: string;
}> { }> {
const cleanLabel = label.trim(); const cleanLabel = label.trim();
if (cleanLabel.length < 1 || cleanLabel.length > 64) { if (cleanLabel.length < 1 || cleanLabel.length > 64) {
@ -985,13 +1327,17 @@ export class AuthService {
const username = this.getAdminUsername() ?? 'admin'; const username = this.getAdminUsername() ?? 'admin';
const totp = buildTotp(secret.base32, `${username} (${cleanLabel})`); const totp = buildTotp(secret.base32, `${username} (${cleanLabel})`);
const otpauthUri = totp.toString(); 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 { return {
enrollmentId, enrollmentId,
label: cleanLabel, label: cleanLabel,
secretBase32: secret.base32, secretBase32: secret.base32,
otpauthUri, otpauthUri,
qrSvg, qrSvg,
qrDataUri,
}; };
} }
@ -1019,12 +1365,13 @@ export class AuthService {
const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta; const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta;
const id = `totp-${crypto.randomBytes(4).toString('hex')}`; const id = `totp-${crypto.randomBytes(4).toString('hex')}`;
const secretEnc = encryptTotpSecret(this.dbKey, id, pending.secretBase32);
this.db this.db
.prepare( .prepare(
`INSERT INTO admin_totps (id, label, secret_base32, last_login_step, last_stepup_step, created_at) `INSERT INTO admin_totps (id, label, secret_base32, secret_enc, last_login_step, last_stepup_step, last_used_step, created_at)
VALUES (?, ?, ?, ?, ?, ?)`, VALUES (?, ?, '', ?, ?, ?, ?, ?)`,
) )
.run(id, pending.label, pending.secretBase32, matchedStep, matchedStep, nowMs); .run(id, pending.label, secretEnc, matchedStep, matchedStep, matchedStep, nowMs);
this.pendingEnrollments.delete(enrollmentId); this.pendingEnrollments.delete(enrollmentId);
this.syncRecovery({ snapshotReason: 'totp-added' }); 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') .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 }>; .all() as Array<{ id: string; label: string; createdAt: number }>;
const totpRows = this.listTotpRows(); const totpRows = this.listTotpRows();
const totps: SavedTotpEntry[] = totpRows.map((t) => ({ const totps: SavedTotpEntry[] = totpRows.map((t) => {
id: t.id, const secretBase32 = this.getTotpSecret(t);
label: t.label, return {
secretBase32: t.secret_base32, id: t.id,
otpauthUri: buildTotp( label: t.label,
t.secret_base32, secretBase32,
username ? `${username} (${t.label})` : t.label, otpauthUri: buildTotp(
).toString(), secretBase32,
createdAt: new Date(t.created_at).toISOString(), username ? `${username} (${t.label})` : t.label,
})); ).toString(),
createdAt: new Date(t.created_at).toISOString(),
};
});
this.recoveryStore.syncState({ this.recoveryStore.syncState({
enabled: sec.enableEmergencySecretsBackup, enabled: sec.enableEmergencySecretsBackup,
@ -1134,24 +1484,43 @@ export class AuthService {
} }
revokeSessionByHash(idHash: string): void { 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 { revokeSessionByPrefix(prefix: string): number {
if (!/^[0-9a-f]{8,64}$/i.test(prefix)) return 0; 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 const result = this.db
.prepare('DELETE FROM sessions WHERE id_hash LIKE ?') .prepare('DELETE FROM sessions WHERE id_hash LIKE ?')
.run(`${prefix}%`); .run(`${prefix}%`);
if (result.changes > 0) {
this.notifySessionsRevoked(rows.map((r) => r.id_hash));
}
return result.changes; return result.changes;
} }
revokeAllSessions(exceptIdHash?: string): number { revokeAllSessions(exceptIdHash?: string): number {
if (exceptIdHash) { const rows = (
return this.db exceptIdHash
.prepare('DELETE FROM sessions WHERE id_hash != ?') ? this.db
.run(exceptIdHash).changes; .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[] { private listTotpRows(): TotpRow[] {
@ -1172,7 +1541,7 @@ export class AuthService {
if (mode === 'any') { if (mode === 'any') {
for (const row of rows) { for (const row of rows) {
for (const candidate of suppliedPasswords) { for (const candidate of suppliedPasswords) {
if (await argon2.verify(row.password_hash, candidate)) { if (await this.verifyPasswordHash(row.password_hash, candidate)) {
return true; return true;
} }
} }
@ -1184,7 +1553,7 @@ export class AuthService {
for (const row of rows) { for (const row of rows) {
let rowMatched = false; let rowMatched = false;
for (const candidate of suppliedPasswords) { for (const candidate of suppliedPasswords) {
if (await argon2.verify(row.password_hash, candidate)) { if (await this.verifyPasswordHash(row.password_hash, candidate)) {
rowMatched = true; rowMatched = true;
break; break;
} }
@ -1199,8 +1568,9 @@ export class AuthService {
mode: 'any' | 'all', mode: 'any' | 'all',
purpose: 'login' | 'stepup', purpose: 'login' | 'stepup',
username: string, username: string,
ip?: string,
): boolean { ): boolean {
const totpRes = this.verifyTotpRows(suppliedCodes, mode, purpose, username); const totpRes = this.verifyTotpRows(suppliedCodes, mode, purpose, username, ip);
if (totpRes.ok) return true; if (totpRes.ok) return true;
// In 'any' mode, a single-use recovery code may replace TOTP // 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', 'UPDATE recovery_codes SET used_at = ? WHERE code_hash = ? AND used_at IS NULL',
) )
.run(Date.now(), sha256Hex(normalized)); .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; 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( private verifyTotpRows(
suppliedCodes: string[], suppliedCodes: string[],
mode: 'any' | 'all', mode: 'any' | 'all',
purpose: 'login' | 'stepup', purpose: 'login' | 'stepup',
username: string, username: string,
ip?: string,
): { ok: true } | { ok: false; reason: string } { ): { ok: true } | { ok: false; reason: string } {
const rows = this.listTotpRows(); 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)); const numericCodes = suppliedCodes.filter((c) => /^\d{6}$/.test(c));
if (numericCodes.length === 0) return { ok: false, reason: 'invalid_totp' }; if (numericCodes.length === 0) return { ok: false, reason: 'invalid_totp' };
const nowMs = Date.now(); const nowMs = Date.now();
const stepCol = purpose === 'login' ? 'last_login_step' : 'last_stepup_step';
if (mode === 'any') { if (mode === 'any') {
let sawReplay = false; let sawReplay = false;
for (const row of rows) { for (const row of rows) {
const totp = buildTotp(row.secret_base32, username); const secret = this.getTotpSecret(row);
const lastStep = const totp = buildTotp(secret, username);
purpose === 'login' ? row.last_login_step : row.last_stepup_step; const lastStep = this.getRowLastUsedStep(row);
for (const code of numericCodes) { for (const code of numericCodes) {
const delta = totp.validate({ token: code, window: 1, timestamp: nowMs }); const delta = totp.validate({ token: code, window: 1, timestamp: nowMs });
if (delta === null) continue; if (delta === null) continue;
@ -1250,20 +1635,25 @@ export class AuthService {
continue; continue;
} }
this.db this.db
.prepare(`UPDATE admin_totps SET ${stepCol} = ? WHERE id = ?`) .prepare(
.run(matchedStep, row.id); 'UPDATE admin_totps SET last_used_step = ?, last_login_step = ?, last_stepup_step = ? WHERE id = ?',
)
.run(matchedStep, matchedStep, matchedStep, row.id);
return { ok: true }; return { ok: true };
} }
} }
if (sawReplay) {
this.emitSecurityEvent('auth.totp_replay', ip, { purpose });
}
return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' }; return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' };
} }
// 'all': every configured TOTP authenticator must match a supplied valid non-replayed code // 'all': every configured TOTP authenticator must match a supplied valid non-replayed code
const matchedUpdates: Array<{ id: string; step: number }> = []; const matchedUpdates: Array<{ id: string; step: number }> = [];
for (const row of rows) { for (const row of rows) {
const totp = buildTotp(row.secret_base32, username); const secret = this.getTotpSecret(row);
const lastStep = const totp = buildTotp(secret, username);
purpose === 'login' ? row.last_login_step : row.last_stepup_step; const lastStep = this.getRowLastUsedStep(row);
let rowStep: number | null = null; let rowStep: number | null = null;
let sawReplay = false; let sawReplay = false;
@ -1280,15 +1670,20 @@ export class AuthService {
} }
if (rowStep === null) { if (rowStep === null) {
if (sawReplay) {
this.emitSecurityEvent('auth.totp_replay', ip, { purpose });
}
return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' }; return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' };
} }
matchedUpdates.push({ id: row.id, step: rowStep }); matchedUpdates.push({ id: row.id, step: rowStep });
} }
const tx = this.db.transaction(() => { 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) { for (const upd of matchedUpdates) {
stmt.run(upd.step, upd.id); stmt.run(upd.step, upd.step, upd.step, upd.id);
} }
}); });
tx(); tx();
@ -1305,8 +1700,9 @@ export class AuthService {
const idHash = sha256Hex(sessionToken); const idHash = sha256Hex(sessionToken);
const csrfTokenHash = sha256Hex(csrfToken); const csrfTokenHash = sha256Hex(csrfToken);
const now = Date.now(); const now = Date.now();
const expiresAt = now + SESSION_TTL_MS;
const sec = this.getSecurity(); const sec = this.getSecurity();
const ttlMs = (sec.sessionTtlHours ?? 168) * 60 * 60 * 1000;
const expiresAt = now + ttlMs;
const shouldElevate = const shouldElevate =
sec.elevateOnLogin && (!safeMode || sec.keepElevationOnSafeMode); sec.elevateOnLogin && (!safeMode || sec.keepElevationOnSafeMode);

View file

@ -129,15 +129,21 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
}); });
expect(boot.session.elevatedUntil).toBeNull(); expect(boot.session.elevatedUntil).toBeNull();
// Step-up tracks replay independently from login step // Unified monotonic TOTP step blocks replaying bootstrap code for step-up
const stepUp1 = await auth.stepUp(boot.session.idHash, code0); 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({ expect(stepUp1).toEqual({
ok: true, ok: true,
elevatedUntil: t0 + 5 * 60 * 1000, elevatedUntil: t1 + 5 * 60 * 1000,
}); });
// Replaying exact same step-up code is denied // 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' }); expect(stepUpReplay).toEqual({ ok: false, reason: 'totp_replayed' });
// Enabling Safe Mode clears elevatedUntil immediately // Enabling Safe Mode clears elevatedUntil immediately
@ -146,18 +152,19 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
expect(safeSession?.elevatedUntil).toBeNull(); expect(safeSession?.elevatedUntil).toBeNull();
// Step-up is blocked while Safe Mode is ON // Step-up is blocked while Safe Mode is ON
vi.setSystemTime(t0 + 31_000); const t2 = t1 + 31_000;
const code1 = generateTotp(enroll.secretBase32, t0 + 31_000); vi.setSystemTime(t2);
const whileSafe = await auth.stepUp(boot.session.idHash, code1); const code2 = generateTotp(enroll.secretBase32, t2);
const whileSafe = await auth.stepUp(boot.session.idHash, code2);
expect(whileSafe).toEqual({ ok: false, reason: 'safe_mode_active' }); expect(whileSafe).toEqual({ ok: false, reason: 'safe_mode_active' });
// Turning Safe Mode OFF allows step-up again // Turning Safe Mode OFF allows step-up again
auth.setSafeMode(boot.session.idHash, false); 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); expect(stepUp2.ok).toBe(true);
// Elevation expires automatically after 5 minutes // 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); const expiredSession = auth.getSessionByToken(boot.sessionToken);
expect(expiredSession?.elevatedUntil).toBeNull(); expect(expiredSession?.elevatedUntil).toBeNull();

View file

@ -453,7 +453,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
activeServer = server; activeServer = server;
api = createApiClient(server); api = createApiClient(server);
vi.setSystemTime(t0 + 31_000); vi.setSystemTime(t0 + 62_000);
const relogin = await api.call('/api/auth/login', { const relogin = await api.call('/api/auth/login', {
method: 'POST', method: 'POST',
body: { body: {
@ -510,7 +510,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
).status, ).status,
).toBe(200); ).toBe(200);
vi.setSystemTime(t0 + 62_000); vi.setSystemTime(t0 + 93_000);
expect( expect(
(await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, (await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200); ).toBe(200);

View file

@ -1,5 +1,6 @@
import crypto from 'node:crypto'; import crypto from 'node:crypto';
import fs from 'node:fs'; import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import * as OTPAuth from 'otpauth'; import * as OTPAuth from 'otpauth';
@ -152,6 +153,7 @@ function buildSyntheticAuthenticator(rpID: string, expectedOrigin: string) {
} }
afterEach(async () => { afterEach(async () => {
vi.useRealTimers();
while (cleanups.length > 0) { while (cleanups.length > 0) {
await cleanups.pop()!(); await cleanups.pop()!();
} }
@ -172,7 +174,6 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => {
fs.rmSync(dataDir, { recursive: true, force: true }); fs.rmSync(dataDir, { recursive: true, force: true });
}); });
const baseUrl = `http://127.0.0.1:${server.port}`;
const origin = `http://localhost:${server.port}`; const origin = `http://localhost:${server.port}`;
const jar = new CookieJar(); const jar = new CookieJar();
let csrfToken = ''; let csrfToken = '';
@ -186,16 +187,57 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => {
Host: `localhost:${server.port}`, Host: `localhost:${server.port}`,
}; };
if (jar.header()) headers.Cookie = jar.header(); 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; if (csrfToken) headers['X-CSRF-Token'] = csrfToken;
const res = await fetch(`${baseUrl}${pathname}`, { const res = await new Promise<{ status: number; setCookies: string[]; text: string }>(
method: opts.method ?? 'GET', (resolve, reject) => {
headers, const req = http.request(
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined, {
}); host: '127.0.0.1',
jar.updateFrom(res); port: server.port,
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>; 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<string, unknown> = {};
try {
data = JSON.parse(res.text) as Record<string, unknown>;
} catch {
data = {};
}
if (typeof data.csrfToken === 'string' && data.csrfToken) { if (typeof data.csrfToken === 'string' && data.csrfToken) {
csrfToken = data.csrfToken; csrfToken = data.csrfToken;
} }
@ -316,7 +358,38 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => {
}); });
expect(loginVerify2.status).toBe(200); 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' }); await api('/api/auth/drop-elevation', { method: 'POST' });
expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(403); 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(typeof stepVerify.data.elevatedUntil).toBe('number');
expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(200); 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)}`, { const delRes = await api(`/api/auth/factors/passkeys/${encodeURIComponent(authn.credId)}`, {
method: 'DELETE', method: 'DELETE',
}); });

View file

@ -188,12 +188,12 @@ describe('Always-on background collectors & write-only Vault lock', () => {
}); });
api = createApiClient(activeServer); 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'); const preLoginStatus = await api.call('/api/auth/status');
expect(preLoginStatus.status).toBe(200); expect(preLoginStatus.status).toBe(200);
expect(preLoginStatus.data.authenticated).toBe(false); expect(preLoginStatus.data.authenticated).toBe(false);
expect(preLoginStatus.data.vaultState).toBe('locked'); expect(preLoginStatus.data.vaultState).toBeUndefined();
expect(preLoginStatus.data.vaultRuntimeReady).toBe(true); expect(preLoginStatus.data.vaultRuntimeReady).toBeUndefined();
const latestBeforeLogin = await waitFor( const latestBeforeLogin = await waitFor(
() => activeServer!.monitoringService.getLatest('srv-1')?.sample, () => activeServer!.monitoringService.getLatest('srv-1')?.sample,