feat(auth): add WebAuthn Passkey registration, one-tap login, and step-up verification
This commit is contained in:
parent
8e37da50eb
commit
874227e3da
3 changed files with 659 additions and 2 deletions
|
|
@ -1,5 +1,9 @@
|
|||
import { Router, type Request, type Response } from 'express';
|
||||
import { z } from 'zod';
|
||||
import type {
|
||||
AuthenticationResponseJSON,
|
||||
RegistrationResponseJSON,
|
||||
} from '@simplewebauthn/server';
|
||||
import type { ConfigManager } from '../../config/config-manager.js';
|
||||
import type { AuditService } from '../../security/audit.js';
|
||||
import { SESSION_COOKIE_NAME, type AuthService } from '../../security/auth.js';
|
||||
|
|
@ -65,6 +69,42 @@ function clearAuthCookies(res: Response, req: Request, trustCloudflare: boolean)
|
|||
res.clearCookie(CSRF_COOKIE_NAME, { path: '/', sameSite: 'strict', secure });
|
||||
}
|
||||
|
||||
class WebAuthnRpError extends Error {
|
||||
readonly code = 'WEBAUTHN_RPID_INVALID';
|
||||
}
|
||||
|
||||
function resolveWebAuthnRp(
|
||||
req: Request,
|
||||
trustCloudflare: boolean,
|
||||
): { rpID: string; expectedOrigin: string } {
|
||||
const originHeader =
|
||||
typeof req.headers.origin === 'string' && req.headers.origin.trim()
|
||||
? req.headers.origin.trim()
|
||||
: '';
|
||||
const proto = isSecureCookie(req, trustCloudflare) ? 'https' : req.protocol || 'http';
|
||||
const hostHeader = String(req.headers.host ?? 'localhost');
|
||||
const candidateOrigin = originHeader || `${proto}://${hostHeader}`;
|
||||
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(candidateOrigin);
|
||||
} catch {
|
||||
throw new WebAuthnRpError('Invalid Origin header for WebAuthn request');
|
||||
}
|
||||
|
||||
const rpID = parsed.hostname;
|
||||
if (/^\d+\.\d+\.\d+\.\d+$/.test(rpID) || rpID.includes(':')) {
|
||||
throw new WebAuthnRpError(
|
||||
`WebAuthn Passkeys require "localhost" or an HTTPS domain name (IP address "${rpID}" is rejected by browsers).`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
rpID,
|
||||
expectedOrigin: parsed.origin,
|
||||
};
|
||||
}
|
||||
|
||||
export function createAuthRouter(deps: AuthRouterDeps): Router {
|
||||
const router = Router();
|
||||
const {
|
||||
|
|
@ -576,6 +616,282 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
},
|
||||
);
|
||||
|
||||
// WebAuthn / Passkey registration, passwordless login & step-up routes
|
||||
router.post(
|
||||
'/factors/passkeys/register/options',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
const parsed = z
|
||||
.object({ label: z.string().min(1).max(64).default('Passkey') })
|
||||
.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const rp = resolveWebAuthnRp(req, trustCloudflare);
|
||||
const data = await authService.beginPasskeyRegistration({
|
||||
label: parsed.data.label,
|
||||
...rp,
|
||||
});
|
||||
res.json(data);
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: err instanceof WebAuthnRpError ? err.code : 'PASSKEY_OPTIONS_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to start passkey registration',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/factors/passkeys/register/verify',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
const parsed = z
|
||||
.object({
|
||||
challengeId: z.string().min(1),
|
||||
response: z.record(z.unknown()),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const added = await authService.completePasskeyRegistration({
|
||||
challengeId: parsed.data.challengeId,
|
||||
response: parsed.data.response as unknown as RegistrationResponseJSON,
|
||||
});
|
||||
auditService.log({
|
||||
action: 'auth.passkey_add',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: added.id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.status(201).json({ passkey: added });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'PASSKEY_VERIFY_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to verify passkey registration',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.delete(
|
||||
'/factors/passkeys/:id',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
try {
|
||||
const removed = authService.removePasskey(id);
|
||||
if (!removed) {
|
||||
res.status(404).json({ error: 'PASSKEY_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
auditService.log({
|
||||
action: 'auth.passkey_remove',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ deleted: true });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'PASSKEY_REMOVE_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to remove passkey',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.post('/passkeys/login/options', async (req, res) => {
|
||||
if (!authService.isBootstrapped()) {
|
||||
res.status(409).json({ error: 'NOT_BOOTSTRAPPED' });
|
||||
return;
|
||||
}
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('login', ip);
|
||||
if (!rate.allowed) {
|
||||
res.setHeader('Retry-After', String(rate.retryAfterSec));
|
||||
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const rp = resolveWebAuthnRp(req, trustCloudflare);
|
||||
const data = await authService.beginPasskeyAuthentication({
|
||||
purpose: 'login',
|
||||
...rp,
|
||||
});
|
||||
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', async (req, res) => {
|
||||
if (!authService.isBootstrapped()) {
|
||||
res.status(409).json({ error: 'NOT_BOOTSTRAPPED' });
|
||||
return;
|
||||
}
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('login', ip);
|
||||
if (!rate.allowed) {
|
||||
res.setHeader('Retry-After', String(rate.retryAfterSec));
|
||||
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
|
||||
return;
|
||||
}
|
||||
|
||||
const parsed = z
|
||||
.object({
|
||||
challengeId: z.string().min(1),
|
||||
response: z.record(z.unknown()),
|
||||
initialSafeMode: z.boolean().optional(),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
rateLimiter.recordFailure('login', ip);
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await authService.loginWithPasskey({
|
||||
challengeId: parsed.data.challengeId,
|
||||
response: parsed.data.response as unknown as AuthenticationResponseJSON,
|
||||
ip,
|
||||
userAgent: String(req.headers['user-agent'] ?? 'unknown'),
|
||||
initialSafeMode: parsed.data.initialSafeMode,
|
||||
});
|
||||
if (!result) {
|
||||
rateLimiter.recordFailure('login', ip);
|
||||
auditService.log({
|
||||
action: 'auth.passkey_login',
|
||||
actorIp: ip,
|
||||
status: 'denied',
|
||||
});
|
||||
res.status(401).json({ error: 'INVALID_PASSKEY_ASSERTION' });
|
||||
return;
|
||||
}
|
||||
|
||||
rateLimiter.recordSuccess('login', ip);
|
||||
setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare);
|
||||
auditService.log({
|
||||
action: 'auth.passkey_login',
|
||||
actorIp: ip,
|
||||
sessionIdHash: result.session.idHash,
|
||||
status: 'ok',
|
||||
});
|
||||
|
||||
res.json({
|
||||
authenticated: true,
|
||||
csrfToken: result.csrfToken,
|
||||
safeMode: result.session.safeMode,
|
||||
elevatedUntil: result.session.elevatedUntil,
|
||||
vaultState: vaultService.state,
|
||||
});
|
||||
});
|
||||
|
||||
router.post(
|
||||
'/passkeys/step-up/options',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
async (req, res) => {
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('step-up', ip);
|
||||
if (!rate.allowed) {
|
||||
res.setHeader('Retry-After', String(rate.retryAfterSec));
|
||||
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const rp = resolveWebAuthnRp(req, trustCloudflare);
|
||||
const data = await authService.beginPasskeyAuthentication({
|
||||
purpose: 'stepup',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
...rp,
|
||||
});
|
||||
res.json(data);
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: err instanceof WebAuthnRpError ? err.code : 'PASSKEY_STEPUP_OPTIONS_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to start passkey verification',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/passkeys/step-up/verify',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
async (req, res) => {
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('step-up', 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()),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
const outcome = await authService.stepUpWithPasskey({
|
||||
idHash: req.authSession!.idHash,
|
||||
challengeId: parsed.data.challengeId,
|
||||
response: parsed.data.response as unknown as AuthenticationResponseJSON,
|
||||
});
|
||||
if (!outcome.ok) {
|
||||
rateLimiter.recordFailure('step-up', ip);
|
||||
auditService.log({
|
||||
action: 'auth.passkey_step_up',
|
||||
actorIp: ip,
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
status: 'denied',
|
||||
details: { reason: outcome.reason },
|
||||
});
|
||||
res.status(outcome.reason === 'safe_mode_active' ? 423 : 403).json({
|
||||
error: 'STEP_UP_FAILED',
|
||||
reason: outcome.reason,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
rateLimiter.recordSuccess('step-up', ip);
|
||||
auditService.log({
|
||||
action: 'auth.passkey_step_up',
|
||||
actorIp: ip,
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ elevatedUntil: outcome.elevatedUntil });
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/recovery-backup/sync',
|
||||
requireAuth(authService),
|
||||
|
|
|
|||
|
|
@ -1,4 +1,13 @@
|
|||
import crypto from 'node:crypto';
|
||||
import {
|
||||
generateAuthenticationOptions,
|
||||
generateRegistrationOptions,
|
||||
verifyAuthenticationResponse,
|
||||
verifyRegistrationResponse,
|
||||
type AuthenticationResponseJSON,
|
||||
type AuthenticatorTransportFuture,
|
||||
type RegistrationResponseJSON,
|
||||
} from '@simplewebauthn/server';
|
||||
import argon2 from 'argon2';
|
||||
import type Database from 'better-sqlite3';
|
||||
import * as OTPAuth from 'otpauth';
|
||||
|
|
@ -14,6 +23,7 @@ import type { VaultService } from './vault.js';
|
|||
const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||
const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
const BOOTSTRAP_TTL_MS = 15 * 60 * 1000;
|
||||
const WEBAUTHN_TTL_MS = 5 * 60 * 1000;
|
||||
const TOTP_PERIOD_SEC = 30;
|
||||
const DEFAULT_SECURITY = SecuritySettingsSchema.parse({});
|
||||
|
||||
|
|
@ -51,10 +61,30 @@ export interface PublicAuthRequirements {
|
|||
totpMode: 'any' | 'all';
|
||||
totpCount: number;
|
||||
totpLabels: Array<{ id: string; label: string }>;
|
||||
passkeyCount: number;
|
||||
stepUpPolicy: StepUpPolicy;
|
||||
stepUpMethod: SecuritySettings['stepUpMethod'];
|
||||
}
|
||||
|
||||
interface WebAuthnRow {
|
||||
id: string;
|
||||
name: string;
|
||||
public_key: Buffer;
|
||||
counter: number;
|
||||
transports: string | null;
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
interface PendingWebAuthnChallenge {
|
||||
challenge: string;
|
||||
purpose: 'register' | 'login' | 'stepup';
|
||||
rpID: string;
|
||||
expectedOrigin: string;
|
||||
label?: string;
|
||||
sessionIdHash?: string;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export type StepUpInput =
|
||||
| string
|
||||
| {
|
||||
|
|
@ -164,6 +194,7 @@ export class AuthService {
|
|||
string,
|
||||
{ label: string; secretBase32: string; createdAt: number }
|
||||
>();
|
||||
private readonly pendingWebAuthn = new Map<string, PendingWebAuthnChallenge>();
|
||||
private readonly getSecurity: () => SecuritySettings;
|
||||
private recoveryStore?: EmergencyRecoveryService;
|
||||
private vaultService?: VaultService;
|
||||
|
|
@ -205,6 +236,11 @@ export class AuthService {
|
|||
const totps = this.db
|
||||
.prepare('SELECT id, label FROM admin_totps ORDER BY created_at ASC, id ASC')
|
||||
.all() as Array<{ id: string; label: string }>;
|
||||
const passkeyCount = (
|
||||
this.db.prepare('SELECT COUNT(*) AS cnt FROM webauthn_credentials').get() as {
|
||||
cnt: number;
|
||||
}
|
||||
).cnt;
|
||||
|
||||
return {
|
||||
requireTotpOnLogin: sec.requireTotpOnLogin,
|
||||
|
|
@ -214,6 +250,7 @@ export class AuthService {
|
|||
totpMode: sec.totpMode,
|
||||
totpCount: totps.length,
|
||||
totpLabels: totps,
|
||||
passkeyCount,
|
||||
stepUpPolicy: sec.stepUpPolicy,
|
||||
stepUpMethod: sec.stepUpMethod,
|
||||
};
|
||||
|
|
@ -474,6 +511,10 @@ export class AuthService {
|
|||
reqObj.passwords ?? (reqObj.password !== undefined ? [reqObj.password] : [])
|
||||
).filter((p) => p.length > 0);
|
||||
|
||||
if (sec.stepUpMethod === 'passkey') {
|
||||
return { ok: false, reason: 'passkey_required' };
|
||||
}
|
||||
|
||||
if (sec.stepUpMethod === 'password' || sec.stepUpMethod === 'both') {
|
||||
if (suppliedPasswords.length === 0) {
|
||||
return { ok: false, reason: 'password_required' };
|
||||
|
|
@ -556,6 +597,7 @@ export class AuthService {
|
|||
listFactors(): {
|
||||
passwords: Array<{ id: string; label: string; createdAt: number }>;
|
||||
totps: Array<{ id: string; label: string; createdAt: number }>;
|
||||
passkeys: Array<{ id: string; name: string; transports: string[]; createdAt: number }>;
|
||||
unusedRecoveryCodes: number;
|
||||
} {
|
||||
const passwords = this.db
|
||||
|
|
@ -564,11 +606,310 @@ export class AuthService {
|
|||
const totps = this.db
|
||||
.prepare('SELECT id, label, created_at AS createdAt FROM admin_totps ORDER BY created_at ASC')
|
||||
.all() as Array<{ id: string; label: string; createdAt: number }>;
|
||||
const passkeyRows = this.db
|
||||
.prepare(
|
||||
'SELECT id, name, transports, created_at AS createdAt FROM webauthn_credentials ORDER BY created_at ASC',
|
||||
)
|
||||
.all() as Array<{ id: string; name: string; transports: string | null; createdAt: number }>;
|
||||
const passkeys = passkeyRows.map((row) => {
|
||||
let transports: string[] = [];
|
||||
if (row.transports) {
|
||||
try {
|
||||
transports = JSON.parse(row.transports) as string[];
|
||||
} catch {
|
||||
transports = [];
|
||||
}
|
||||
}
|
||||
return { id: row.id, name: row.name, transports, createdAt: row.createdAt };
|
||||
});
|
||||
const rec = this.db
|
||||
.prepare('SELECT COUNT(*) AS cnt FROM recovery_codes WHERE used_at IS NULL')
|
||||
.get() as { cnt: number };
|
||||
|
||||
return { passwords, totps, unusedRecoveryCodes: rec.cnt };
|
||||
return { passwords, totps, passkeys, unusedRecoveryCodes: rec.cnt };
|
||||
}
|
||||
|
||||
private sweepWebAuthnChallenges(): void {
|
||||
const cutoff = Date.now() - WEBAUTHN_TTL_MS;
|
||||
for (const [k, v] of this.pendingWebAuthn.entries()) {
|
||||
if (v.createdAt < cutoff) this.pendingWebAuthn.delete(k);
|
||||
}
|
||||
}
|
||||
|
||||
private consumeWebAuthnChallenge(
|
||||
challengeId: string,
|
||||
purpose: PendingWebAuthnChallenge['purpose'],
|
||||
): PendingWebAuthnChallenge | null {
|
||||
this.sweepWebAuthnChallenges();
|
||||
const pending = this.pendingWebAuthn.get(challengeId);
|
||||
if (!pending) return null;
|
||||
this.pendingWebAuthn.delete(challengeId);
|
||||
if (pending.purpose !== purpose) return null;
|
||||
return pending;
|
||||
}
|
||||
|
||||
private listPasskeyRows(): WebAuthnRow[] {
|
||||
return this.db
|
||||
.prepare('SELECT * FROM webauthn_credentials ORDER BY created_at ASC')
|
||||
.all() as WebAuthnRow[];
|
||||
}
|
||||
|
||||
async beginPasskeyRegistration(params: {
|
||||
label: string;
|
||||
rpID: string;
|
||||
expectedOrigin: string;
|
||||
}) {
|
||||
const username = this.getAdminUsername();
|
||||
if (!username) {
|
||||
throw new Error('Admin account is not bootstrapped yet');
|
||||
}
|
||||
const cleanLabel = params.label.trim();
|
||||
if (cleanLabel.length < 1 || cleanLabel.length > 64) {
|
||||
throw new Error('Passkey label must be 1–64 characters');
|
||||
}
|
||||
|
||||
this.sweepWebAuthnChallenges();
|
||||
const existing = this.listPasskeyRows();
|
||||
const options = await generateRegistrationOptions({
|
||||
rpName: 'GCoordinator',
|
||||
rpID: params.rpID,
|
||||
userName: username,
|
||||
userDisplayName: username,
|
||||
attestationType: 'none',
|
||||
excludeCredentials: existing.map((row) => ({
|
||||
id: row.id,
|
||||
transports: row.transports
|
||||
? (JSON.parse(row.transports) as AuthenticatorTransportFuture[])
|
||||
: undefined,
|
||||
})),
|
||||
authenticatorSelection: {
|
||||
residentKey: 'preferred',
|
||||
userVerification: 'preferred',
|
||||
},
|
||||
});
|
||||
|
||||
const challengeId = crypto.randomBytes(16).toString('hex');
|
||||
this.pendingWebAuthn.set(challengeId, {
|
||||
challenge: options.challenge,
|
||||
purpose: 'register',
|
||||
rpID: params.rpID,
|
||||
expectedOrigin: params.expectedOrigin,
|
||||
label: cleanLabel,
|
||||
createdAt: Date.now(),
|
||||
});
|
||||
|
||||
return { challengeId, options };
|
||||
}
|
||||
|
||||
async completePasskeyRegistration(params: {
|
||||
challengeId: string;
|
||||
response: RegistrationResponseJSON;
|
||||
}): Promise<{ id: string; name: string; transports: string[]; createdAt: number }> {
|
||||
const pending = this.consumeWebAuthnChallenge(params.challengeId, 'register');
|
||||
if (!pending) {
|
||||
throw new Error('Passkey registration challenge expired or not found');
|
||||
}
|
||||
|
||||
const verification = await verifyRegistrationResponse({
|
||||
response: params.response,
|
||||
expectedChallenge: pending.challenge,
|
||||
expectedOrigin: pending.expectedOrigin,
|
||||
expectedRPID: pending.rpID,
|
||||
requireUserVerification: false,
|
||||
});
|
||||
|
||||
if (!verification.verified || !verification.registrationInfo) {
|
||||
throw new Error('Passkey registration verification failed');
|
||||
}
|
||||
|
||||
const { credential } = verification.registrationInfo;
|
||||
const transports = credential.transports ?? params.response.response.transports ?? [];
|
||||
const createdAt = Date.now();
|
||||
const label = pending.label ?? 'Passkey';
|
||||
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO webauthn_credentials (id, name, public_key, counter, transports, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(
|
||||
credential.id,
|
||||
label,
|
||||
Buffer.from(credential.publicKey),
|
||||
credential.counter,
|
||||
JSON.stringify(transports),
|
||||
createdAt,
|
||||
);
|
||||
|
||||
return { id: credential.id, name: label, transports, createdAt };
|
||||
}
|
||||
|
||||
removePasskey(id: string): boolean {
|
||||
const sec = this.getSecurity();
|
||||
const count = (
|
||||
this.db.prepare('SELECT COUNT(*) AS cnt FROM webauthn_credentials').get() as {
|
||||
cnt: number;
|
||||
}
|
||||
).cnt;
|
||||
if (count <= 1 && sec.stepUpPolicy !== 'off' && sec.stepUpMethod === 'passkey') {
|
||||
throw new Error(
|
||||
'Cannot remove the last passkey while Step-Up Method is set to passkey',
|
||||
);
|
||||
}
|
||||
const res = this.db.prepare('DELETE FROM webauthn_credentials WHERE id = ?').run(id);
|
||||
return res.changes > 0;
|
||||
}
|
||||
|
||||
async beginPasskeyAuthentication(params: {
|
||||
purpose: 'login' | 'stepup';
|
||||
rpID: string;
|
||||
expectedOrigin: string;
|
||||
sessionIdHash?: string;
|
||||
}) {
|
||||
const rows = this.listPasskeyRows();
|
||||
if (rows.length === 0) {
|
||||
throw new Error('No passkeys registered');
|
||||
}
|
||||
this.sweepWebAuthnChallenges();
|
||||
|
||||
const options = await generateAuthenticationOptions({
|
||||
rpID: params.rpID,
|
||||
allowCredentials: rows.map((row) => ({
|
||||
id: row.id,
|
||||
transports: row.transports
|
||||
? (JSON.parse(row.transports) as AuthenticatorTransportFuture[])
|
||||
: undefined,
|
||||
})),
|
||||
userVerification: 'preferred',
|
||||
});
|
||||
|
||||
const challengeId = crypto.randomBytes(16).toString('hex');
|
||||
this.pendingWebAuthn.set(challengeId, {
|
||||
challenge: options.challenge,
|
||||
purpose: params.purpose,
|
||||
rpID: params.rpID,
|
||||
expectedOrigin: params.expectedOrigin,
|
||||
sessionIdHash: params.sessionIdHash,
|
||||
createdAt: Date.now(),
|
||||
});
|
||||
|
||||
return { challengeId, options };
|
||||
}
|
||||
|
||||
async loginWithPasskey(params: {
|
||||
challengeId: string;
|
||||
response: AuthenticationResponseJSON;
|
||||
ip: string;
|
||||
userAgent: string;
|
||||
initialSafeMode?: boolean;
|
||||
}): Promise<{ sessionToken: string; csrfToken: string; session: AuthSession } | null> {
|
||||
if (!this.isBootstrapped()) return null;
|
||||
const pending = this.consumeWebAuthnChallenge(params.challengeId, 'login');
|
||||
if (!pending) return null;
|
||||
|
||||
const row = this.db
|
||||
.prepare('SELECT * FROM webauthn_credentials WHERE id = ?')
|
||||
.get(params.response.id) as WebAuthnRow | undefined;
|
||||
if (!row) return null;
|
||||
|
||||
try {
|
||||
const verification = await verifyAuthenticationResponse({
|
||||
response: params.response,
|
||||
expectedChallenge: pending.challenge,
|
||||
expectedOrigin: pending.expectedOrigin,
|
||||
expectedRPID: pending.rpID,
|
||||
credential: {
|
||||
id: row.id,
|
||||
publicKey: new Uint8Array(row.public_key),
|
||||
counter: row.counter,
|
||||
transports: row.transports
|
||||
? (JSON.parse(row.transports) as AuthenticatorTransportFuture[])
|
||||
: undefined,
|
||||
},
|
||||
requireUserVerification: false,
|
||||
});
|
||||
if (!verification.verified) return null;
|
||||
|
||||
this.db
|
||||
.prepare('UPDATE webauthn_credentials SET counter = ? WHERE id = ?')
|
||||
.run(verification.authenticationInfo.newCounter, row.id);
|
||||
|
||||
return this.createSession(
|
||||
params.ip,
|
||||
params.userAgent,
|
||||
Boolean(params.initialSafeMode),
|
||||
);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async stepUpWithPasskey(params: {
|
||||
idHash: string;
|
||||
challengeId: string;
|
||||
response: AuthenticationResponseJSON;
|
||||
}): Promise<{ ok: true; elevatedUntil: number | null } | { ok: false; reason: string }> {
|
||||
const session = this.db
|
||||
.prepare('SELECT safe_mode, expires_at FROM sessions WHERE id_hash = ?')
|
||||
.get(params.idHash) as { safe_mode: number; expires_at: number } | undefined;
|
||||
if (!session) return { ok: false, reason: 'invalid_session' };
|
||||
|
||||
const sec = this.getSecurity();
|
||||
if (sec.stepUpPolicy === 'off') {
|
||||
return { ok: true, elevatedUntil: null };
|
||||
}
|
||||
if (session.safe_mode === 1) {
|
||||
return { ok: false, reason: 'safe_mode_active' };
|
||||
}
|
||||
|
||||
const pending = this.consumeWebAuthnChallenge(params.challengeId, 'stepup');
|
||||
if (!pending || pending.sessionIdHash !== params.idHash) {
|
||||
return { ok: false, reason: 'invalid_challenge' };
|
||||
}
|
||||
|
||||
const row = this.db
|
||||
.prepare('SELECT * FROM webauthn_credentials WHERE id = ?')
|
||||
.get(params.response.id) as WebAuthnRow | undefined;
|
||||
if (!row) return { ok: false, reason: 'unknown_passkey' };
|
||||
|
||||
try {
|
||||
const verification = await verifyAuthenticationResponse({
|
||||
response: params.response,
|
||||
expectedChallenge: pending.challenge,
|
||||
expectedOrigin: pending.expectedOrigin,
|
||||
expectedRPID: pending.rpID,
|
||||
credential: {
|
||||
id: row.id,
|
||||
publicKey: new Uint8Array(row.public_key),
|
||||
counter: row.counter,
|
||||
transports: row.transports
|
||||
? (JSON.parse(row.transports) as AuthenticatorTransportFuture[])
|
||||
: undefined,
|
||||
},
|
||||
requireUserVerification: false,
|
||||
});
|
||||
if (!verification.verified) {
|
||||
return { ok: false, reason: 'invalid_assertion' };
|
||||
}
|
||||
|
||||
this.db
|
||||
.prepare('UPDATE webauthn_credentials SET counter = ? WHERE id = ?')
|
||||
.run(verification.authenticationInfo.newCounter, row.id);
|
||||
|
||||
const elevatedUntil = computeElevatedUntil(
|
||||
Date.now(),
|
||||
sec.stepUpPolicy,
|
||||
session.expires_at,
|
||||
false,
|
||||
);
|
||||
this.db
|
||||
.prepare('UPDATE sessions SET elevated_until = ? WHERE id_hash = ?')
|
||||
.run(elevatedUntil, params.idHash);
|
||||
|
||||
return { ok: true, elevatedUntil };
|
||||
} catch {
|
||||
return { ok: false, reason: 'invalid_assertion' };
|
||||
}
|
||||
}
|
||||
|
||||
async addPassword(
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ export const StepUpPolicySchema = z.enum([
|
|||
'session',
|
||||
]);
|
||||
|
||||
export const StepUpMethodSchema = z.enum(['totp', 'password', 'both']);
|
||||
export const StepUpMethodSchema = z.enum(['totp', 'password', 'both', 'passkey']);
|
||||
|
||||
export const SecuritySettingsSchema = z.object({
|
||||
requireTotpOnLogin: z.boolean().default(true),
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue