feat(auth): add WebAuthn Passkey registration, one-tap login, and step-up verification

This commit is contained in:
tyuXX 2026-11-26 22:06:49 +00:00
parent 8e37da50eb
commit 874227e3da
3 changed files with 659 additions and 2 deletions

View file

@ -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(