Repository Public
1// SP Identity: WebAuthn passkeys (no passwords), opaque bearer sessions bound to a registered device,2// recovery by a client-held recovery key. Biometrics never reach the server: the platform authenticator3// performs user verification and the server only checks the signed assertion.4import { randomBytes, scryptSync } from "node:crypto";5import type { FastifyInstance, FastifyRequest } from "fastify";6import {7 generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse,8} from "@simplewebauthn/server";9import type { Config } from "./config.ts";10import { transaction, type DB } from "./db.ts";11import { HttpError, OpsLog, RateLimiter, hmac, now, randomId, safeEqual, sha256 } from "./util.ts";1213export interface AuthContext { userId: string; deviceId: string; tokenHash: string; reauthAt: number | null }14export interface Deps { config: Config; db: DB; log: OpsLog; limiter: RateLimiter }1516const CHALLENGE_TTL = 5 * 60_000;17const REAUTH_WINDOW = 10 * 60_000;18const PLATFORMS = ["macos", "ios", "ipados"];1920export function clientKey(deps: Deps, request: FastifyRequest): string {21 return hmac(deps.config.serverSecret, request.ip).slice(0, 24);22}2324function limit(deps: Deps, request: FastifyRequest, bucket: string, max: number, windowMs: number): void {25 const wait = deps.limiter.check(`${bucket}:${clientKey(deps, request)}`, max * deps.config.authRateMultiplier, windowMs);26 if (wait) throw new HttpError(429, "rate_limited", "Too many requests", { retryAfter: wait });27}2829/** Resolves the bearer session, or null. Expired and revoked sessions are rejected; idle time slides the expiry. */30export function sessionFrom(deps: Deps, request: FastifyRequest): AuthContext | null {31 const header = request.headers.authorization ?? "";32 if (!header.startsWith("Bearer ")) return null;33 const tokenHash = sha256(header.slice(7).trim());34 const row = deps.db.prepare(`35 SELECT s.user_id, s.device_id, s.expires_at, s.last_used_at, s.reauth_at, d.revoked_at36 FROM sessions s JOIN devices d ON d.id = s.device_id WHERE s.token_hash = ?`).get(tokenHash) as any;37 if (!row) return null;38 const t = now();39 if (row.expires_at < t || row.revoked_at) {40 deps.db.prepare("DELETE FROM sessions WHERE token_hash = ?").run(tokenHash);41 return null;42 }43 if (t - row.last_used_at > 60_000) {44 const expires = Math.max(row.expires_at, t + deps.config.sessionDays * 86400_000 / 2);45 deps.db.prepare("UPDATE sessions SET last_used_at = ?, expires_at = ? WHERE token_hash = ?").run(t, expires, tokenHash);46 deps.db.prepare("UPDATE devices SET last_seen_at = ? WHERE id = ?").run(t, row.device_id);47 }48 return { userId: row.user_id, deviceId: row.device_id, tokenHash, reauthAt: row.reauth_at };49}5051export function requireSession(deps: Deps, request: FastifyRequest): AuthContext {52 const session = sessionFrom(deps, request);53 if (!session) throw new HttpError(401, "unauthenticated", "Sign in required");54 return session;55}5657function requireRecentAuth(session: AuthContext): void {58 if (!session.reauthAt || now() - session.reauthAt > REAUTH_WINDOW) {59 throw new HttpError(403, "reauth_required", "Confirm with your passkey to continue");60 }61}6263function putChallenge(db: DB, kind: string, challenge: string, userId: string | null, data: unknown): string {64 db.prepare("DELETE FROM challenges WHERE expires_at < ?").run(now());65 const id = randomId();66 db.prepare("INSERT INTO challenges(id, kind, challenge, user_id, data, expires_at) VALUES(?,?,?,?,?,?)")67 .run(id, kind, challenge, userId, JSON.stringify(data ?? null), now() + CHALLENGE_TTL);68 return id;69}7071/** Challenges are single use: fetched and deleted in one step. */72function takeChallenge(db: DB, id: unknown, kind: string): { challenge: string; userId: string | null; data: any } {73 if (typeof id !== "string") throw new HttpError(400, "invalid_challenge", "challengeId missing");74 const row = db.prepare("SELECT * FROM challenges WHERE id = ? AND kind = ?").get(id, kind) as any;75 db.prepare("DELETE FROM challenges WHERE id = ?").run(id);76 if (!row || row.expires_at < now()) throw new HttpError(400, "challenge_expired", "This request expired. Try again.");77 return { challenge: row.challenge, userId: row.user_id, data: JSON.parse(row.data ?? "null") };78}7980interface DeviceInput { id?: string; name: string; platform: string; model: string; appVersion: string; encPublicKey: string }8182function parseDevice(raw: any): DeviceInput {83 if (!raw || typeof raw !== "object") throw new HttpError(400, "invalid_device", "device description missing");84 const name = typeof raw.name === "string" ? raw.name.trim().slice(0, 80) : "";85 if (!name) throw new HttpError(400, "invalid_device", "device name missing");86 if (!PLATFORMS.includes(raw.platform)) throw new HttpError(400, "invalid_device", "unknown platform");87 const encPublicKey = typeof raw.encPublicKey === "string" ? raw.encPublicKey : "";88 if (!/^[A-Za-z0-9+/=_-]{40,200}$/.test(encPublicKey)) throw new HttpError(400, "invalid_device", "device public key missing");89 return {90 id: typeof raw.id === "string" ? raw.id : undefined, name, platform: raw.platform,91 model: typeof raw.model === "string" ? raw.model.slice(0, 60) : "",92 appVersion: typeof raw.appVersion === "string" ? raw.appVersion.slice(0, 20) : "",93 encPublicKey,94 };95}9697/** Reuses the caller's device when it presents its own id and the same key; otherwise registers a new one. */98function upsertDevice(db: DB, userId: string, input: DeviceInput): string {99 const t = now();100 if (input.id) {101 const row = db.prepare("SELECT id, enc_public_key, revoked_at FROM devices WHERE id = ? AND user_id = ?").get(input.id, userId) as any;102 if (row && !row.revoked_at && row.enc_public_key === input.encPublicKey) {103 db.prepare("UPDATE devices SET name = ?, model = ?, app_version = ?, last_seen_at = ? WHERE id = ?").run(input.name, input.model, input.appVersion, t, row.id);104 return row.id;105 }106 }107 const id = randomId();108 db.prepare("INSERT INTO devices(id, user_id, name, platform, model, app_version, enc_public_key, created_at, last_seen_at) VALUES(?,?,?,?,?,?,?,?,?)")109 .run(id, userId, input.name, input.platform, input.model, input.appVersion, input.encPublicKey, t, t);110 return id;111}112113function createSession(deps: Deps, request: FastifyRequest, userId: string, deviceId: string): { token: string; expiresAt: number } {114 const token = "spb_" + randomBytes(32).toString("base64url");115 const t = now();116 const expiresAt = t + deps.config.sessionDays * 86400_000;117 // One live session per device: signing in again replaces the previous token.118 deps.db.prepare("DELETE FROM sessions WHERE device_id = ?").run(deviceId);119 deps.db.prepare("INSERT INTO sessions(token_hash, user_id, device_id, created_at, last_used_at, expires_at, reauth_at, ip_hash) VALUES(?,?,?,?,?,?,?,?)")120 .run(sha256(token), userId, deviceId, t, t, expiresAt, t, clientKey(deps, request));121 return { token, expiresAt };122}123124function accountKeyState(db: DB, userId: string, deviceId: string) {125 const key = db.prepare("SELECT key_version, key_check FROM account_keys WHERE user_id = ?").get(userId) as any;126 const device = db.prepare("SELECT key_envelope FROM devices WHERE id = ?").get(deviceId) as any;127 return { initialized: !!key, keyVersion: key?.key_version ?? null, keyCheck: key?.key_check ?? null, hasEnvelope: !!device?.key_envelope };128}129130function sessionPayload(deps: Deps, userId: string, deviceId: string, session: { token: string; expiresAt: number }) {131 const user = deps.db.prepare("SELECT id, display_name, created_at FROM users WHERE id = ?").get(userId) as any;132 return {133 sessionToken: session.token, expiresAt: session.expiresAt,134 user: { id: user.id, displayName: user.display_name, createdAt: user.created_at },135 deviceId, sync: accountKeyState(deps.db, userId, deviceId),136 };137}138139function recoveryHash(secret: string, salt: string): string {140 return scryptSync(secret, Buffer.from(salt, "hex"), 32, { N: 16384, r: 8, p: 1 }).toString("hex");141}142143export function setRecovery(db: DB, userId: string, recoveryAuth: unknown): void {144 if (typeof recoveryAuth !== "string" || recoveryAuth.length < 32 || recoveryAuth.length > 200) throw new HttpError(400, "invalid_recovery", "recovery authenticator missing");145 const salt = randomBytes(16).toString("hex");146 db.prepare("UPDATE users SET recovery_hash = ?, recovery_salt = ? WHERE id = ?").run(recoveryHash(recoveryAuth, salt), salt, userId);147}148149export function registerAuthRoutes(app: FastifyInstance, deps: Deps): void {150 const { config, db, log } = deps;151 const origin = config.publicOrigin;152153 async function registrationOptions(userId: string, handle: Uint8Array, displayName: string) {154 const existing = db.prepare("SELECT id, transports FROM credentials WHERE user_id = ?").all(userId) as any[];155 return generateRegistrationOptions({156 rpName: config.rpName, rpID: config.rpID,157 userID: handle as Uint8Array<ArrayBuffer>, userName: displayName, userDisplayName: displayName,158 attestationType: "none",159 excludeCredentials: existing.map((c) => ({ id: c.id, transports: c.transports ? JSON.parse(c.transports) : undefined })),160 authenticatorSelection: { residentKey: "required", userVerification: "required" },161 });162 }163164 async function verifyRegistration(response: any, expectedChallenge: string) {165 let result;166 try {167 result = await verifyRegistrationResponse({ response, expectedChallenge, expectedOrigin: origin, expectedRPID: config.rpID, requireUserVerification: true });168 } catch {169 throw new HttpError(400, "passkey_rejected", "The passkey registration could not be verified");170 }171 if (!result.verified || !result.registrationInfo) throw new HttpError(400, "passkey_rejected", "The passkey registration could not be verified");172 return result.registrationInfo;173 }174175 function storeCredential(userId: string, info: Awaited<ReturnType<typeof verifyRegistration>>, label: string): void {176 const c = info.credential;177 db.prepare("INSERT INTO credentials(id, user_id, public_key, counter, transports, device_type, backed_up, label, created_at) VALUES(?,?,?,?,?,?,?,?,?)")178 .run(c.id, userId, Buffer.from(c.publicKey), c.counter, JSON.stringify(c.transports ?? []), info.credentialDeviceType, info.credentialBackedUp ? 1 : 0, label.slice(0, 80), now());179 }180181 async function verifyAssertion(response: any, expectedChallenge: string, expectedUserId: string | null): Promise<string> {182 const credentialId = typeof response?.id === "string" ? response.id : "";183 const row = db.prepare("SELECT * FROM credentials WHERE id = ?").get(credentialId) as any;184 if (!row || (expectedUserId && row.user_id !== expectedUserId)) throw new HttpError(401, "unknown_passkey", "This passkey is not registered");185 let result;186 try {187 result = await verifyAuthenticationResponse({188 response, expectedChallenge, expectedOrigin: origin, expectedRPID: config.rpID, requireUserVerification: true,189 credential: { id: row.id, publicKey: new Uint8Array(row.public_key), counter: row.counter, transports: row.transports ? JSON.parse(row.transports) : undefined },190 });191 } catch {192 throw new HttpError(401, "passkey_rejected", "The passkey could not be verified");193 }194 if (!result.verified) throw new HttpError(401, "passkey_rejected", "The passkey could not be verified");195 db.prepare("UPDATE credentials SET counter = ?, last_used_at = ?, backed_up = ? WHERE id = ?")196 .run(result.authenticationInfo.newCounter, now(), result.authenticationInfo.credentialBackedUp ? 1 : 0, row.id);197 return row.user_id;198 }199200 // ---- Registration (new account) ----201 app.post("/api/auth/register/options", async (request) => {202 limit(deps, request, "register", 10, 3600_000);203 const body = request.body as any;204 const displayName = typeof body?.displayName === "string" ? body.displayName.trim().slice(0, 60) : "";205 if (!displayName) throw new HttpError(400, "invalid_name", "A name for the account is required");206 let inviteHash: string | null = null;207 if (!config.openRegistration) {208 const code = typeof body?.inviteCode === "string" ? body.inviteCode.trim().toUpperCase().replace(/[^A-Z0-9]/g, "") : "";209 inviteHash = sha256(code);210 const invite = db.prepare("SELECT used_at FROM invites WHERE code_hash = ?").get(inviteHash) as any;211 if (!code || !invite || invite.used_at) throw new HttpError(403, "invite_required", "A valid invitation code is required to create an account");212 }213 const userId = randomId();214 const handle = randomBytes(32);215 const options = await registrationOptions(userId, handle, displayName);216 const challengeId = putChallenge(db, "register", options.challenge, null, { userId, handle: handle.toString("base64url"), displayName, inviteHash });217 return { challengeId, options };218 });219220 app.post("/api/auth/register/verify", async (request) => {221 limit(deps, request, "register", 10, 3600_000);222 const body = request.body as any;223 const device = parseDevice(body?.device);224 const pending = takeChallenge(db, body?.challengeId, "register");225 const info = await verifyRegistration(body?.credential, pending.challenge);226 const { userId, handle, displayName, inviteHash } = pending.data;227 const deviceId = transaction(db, () => {228 if (inviteHash) {229 const used = db.prepare("UPDATE invites SET used_at = ?, used_by = ? WHERE code_hash = ? AND used_at IS NULL").run(now(), userId, inviteHash);230 if (used.changes !== 1) throw new HttpError(403, "invite_required", "This invitation code was already used");231 }232 db.prepare("INSERT INTO users(id, handle, display_name, created_at) VALUES(?,?,?,?)").run(userId, Buffer.from(handle, "base64url"), displayName, now());233 storeCredential(userId, info, device.name);234 return upsertDevice(db, userId, { ...device, id: undefined });235 });236 log.add("info", "identity", "account created");237 return sessionPayload(deps, userId, deviceId, createSession(deps, request, userId, deviceId));238 });239240 // ---- Sign in (discoverable credential: the passkey itself identifies the account) ----241 app.post("/api/auth/login/options", async (request) => {242 limit(deps, request, "login", 30, 600_000);243 const options = await generateAuthenticationOptions({ rpID: config.rpID, userVerification: "required", allowCredentials: [] });244 return { challengeId: putChallenge(db, "login", options.challenge, null, null), options };245 });246247 app.post("/api/auth/login/verify", async (request) => {248 limit(deps, request, "login", 30, 600_000);249 const body = request.body as any;250 const device = parseDevice(body?.device);251 const pending = takeChallenge(db, body?.challengeId, "login");252 const userId = await verifyAssertion(body?.credential, pending.challenge, null);253 const deviceId = upsertDevice(db, userId, device);254 return sessionPayload(deps, userId, deviceId, createSession(deps, request, userId, deviceId));255 });256257 // ---- Step-up confirmation for destructive actions ----258 app.post("/api/auth/reauth/options", async (request) => {259 const session = requireSession(deps, request);260 const credentials = db.prepare("SELECT id, transports FROM credentials WHERE user_id = ?").all(session.userId) as any[];261 const options = await generateAuthenticationOptions({262 rpID: config.rpID, userVerification: "required",263 allowCredentials: credentials.map((c) => ({ id: c.id, transports: c.transports ? JSON.parse(c.transports) : undefined })),264 });265 return { challengeId: putChallenge(db, "reauth", options.challenge, session.userId, null), options };266 });267268 app.post("/api/auth/reauth/verify", async (request) => {269 const session = requireSession(deps, request);270 const body = request.body as any;271 const pending = takeChallenge(db, body?.challengeId, "reauth");272 if (pending.userId !== session.userId) throw new HttpError(400, "invalid_challenge", "challenge mismatch");273 await verifyAssertion(body?.credential, pending.challenge, session.userId);274 db.prepare("UPDATE sessions SET reauth_at = ? WHERE token_hash = ?").run(now(), session.tokenHash);275 return { ok: true };276 });277278 // ---- Additional passkeys ----279 app.post("/api/auth/passkeys/options", async (request) => {280 const session = requireSession(deps, request);281 const user = db.prepare("SELECT handle, display_name FROM users WHERE id = ?").get(session.userId) as any;282 const options = await registrationOptions(session.userId, new Uint8Array(user.handle), user.display_name);283 return { challengeId: putChallenge(db, "add-passkey", options.challenge, session.userId, null), options };284 });285286 app.post("/api/auth/passkeys/verify", async (request) => {287 const session = requireSession(deps, request);288 const body = request.body as any;289 const pending = takeChallenge(db, body?.challengeId, "add-passkey");290 if (pending.userId !== session.userId) throw new HttpError(400, "invalid_challenge", "challenge mismatch");291 const info = await verifyRegistration(body?.credential, pending.challenge);292 storeCredential(session.userId, info, typeof body?.label === "string" ? body.label : "");293 log.add("info", "identity", "passkey added");294 return { ok: true, credentialId: info.credential.id };295 });296297 app.delete("/api/auth/passkeys/:id", async (request) => {298 const session = requireSession(deps, request);299 requireRecentAuth(session);300 const id = (request.params as any).id as string;301 const count = (db.prepare("SELECT COUNT(*) AS n FROM credentials WHERE user_id = ?").get(session.userId) as any).n;302 if (count <= 1) throw new HttpError(409, "last_passkey", "The last passkey cannot be removed");303 const result = db.prepare("DELETE FROM credentials WHERE id = ? AND user_id = ?").run(id, session.userId);304 if (!result.changes) throw new HttpError(404, "not_found", "Passkey not found");305 return { ok: true };306 });307308 // ---- Recovery: lost every passkey, still holding the recovery key ----309 app.post("/api/auth/recover/options", async (request) => {310 limit(deps, request, "recover", 5, 3600_000);311 const body = request.body as any;312 const user = typeof body?.userId === "string" ? db.prepare("SELECT id, handle, display_name, recovery_hash, recovery_salt FROM users WHERE id = ?").get(body.userId) as any : null;313 const supplied = typeof body?.recoveryAuth === "string" ? body.recoveryAuth : "";314 // Same work and same answer whether the account exists or not.315 const expected = user?.recovery_hash ?? "0".repeat(64);316 const ok = safeEqual(recoveryHash(supplied, user?.recovery_salt ?? "00".repeat(16)), expected) && !!user?.recovery_hash;317 if (!ok) {318 log.add("warn", "identity", "recovery attempt refused");319 throw new HttpError(403, "recovery_refused", "This recovery key is not valid");320 }321 const options = await registrationOptions(user.id, new Uint8Array(user.handle), user.display_name);322 options.excludeCredentials = []; // the lost passkeys may still be listed on this device323 return { challengeId: putChallenge(db, "recover", options.challenge, user.id, null), options };324 });325326 app.post("/api/auth/recover/verify", async (request) => {327 limit(deps, request, "recover", 5, 3600_000);328 const body = request.body as any;329 const device = parseDevice(body?.device);330 const pending = takeChallenge(db, body?.challengeId, "recover");331 const info = await verifyRegistration(body?.credential, pending.challenge);332 const userId = pending.userId!;333 storeCredential(userId, info, device.name);334 const deviceId = upsertDevice(db, userId, device);335 log.add("warn", "identity", "account recovered with recovery key; new passkey registered");336 return sessionPayload(deps, userId, deviceId, createSession(deps, request, userId, deviceId));337 });338339 // ---- Account, devices, sessions ----340 app.get("/api/account", async (request) => {341 const session = requireSession(deps, request);342 const user = db.prepare("SELECT id, display_name, created_at, recovery_hash FROM users WHERE id = ?").get(session.userId) as any;343 const devices = db.prepare(`344 SELECT d.id, d.name, d.platform, d.model, d.app_version, d.created_at, d.last_seen_at, d.last_sync_at, d.enc_public_key,345 d.key_envelope IS NOT NULL AS has_key,346 (SELECT COUNT(*) FROM sessions s WHERE s.device_id = d.id AND s.expires_at > ?) AS sessions347 FROM devices d WHERE d.user_id = ? AND d.revoked_at IS NULL ORDER BY d.last_seen_at DESC`).all(now(), session.userId) as any[];348 const passkeys = db.prepare("SELECT id, label, device_type, backed_up, created_at, last_used_at FROM credentials WHERE user_id = ? ORDER BY created_at").all(session.userId) as any[];349 const sessions = db.prepare("SELECT device_id, created_at, last_used_at, expires_at FROM sessions WHERE user_id = ? AND expires_at > ? ORDER BY last_used_at DESC").all(session.userId, now()) as any[];350 const records = (db.prepare("SELECT COUNT(*) AS n FROM sync_records WHERE user_id = ? AND deleted = 0").get(session.userId) as any).n;351 return {352 user: { id: user.id, displayName: user.display_name, createdAt: user.created_at, hasRecovery: !!user.recovery_hash },353 currentDeviceId: session.deviceId,354 devices: devices.map((d) => ({355 id: d.id, name: d.name, platform: d.platform, model: d.model, appVersion: d.app_version, createdAt: d.created_at,356 lastSeenAt: d.last_seen_at, lastSyncAt: d.last_sync_at, hasSyncKey: !!d.has_key, activeSessions: d.sessions,357 isCurrent: d.id === session.deviceId, encPublicKey: d.enc_public_key,358 })),359 passkeys: passkeys.map((p) => ({ id: p.id, label: p.label, synced: !!p.backed_up, deviceType: p.device_type, createdAt: p.created_at, lastUsedAt: p.last_used_at })),360 sessions: sessions.map((s) => ({ deviceId: s.device_id, createdAt: s.created_at, lastUsedAt: s.last_used_at, expiresAt: s.expires_at, isCurrent: s.device_id === session.deviceId })),361 sync: { ...accountKeyState(db, session.userId, session.deviceId), records },362 };363 });364365 app.patch("/api/account", async (request) => {366 const session = requireSession(deps, request);367 const name = typeof (request.body as any)?.displayName === "string" ? (request.body as any).displayName.trim().slice(0, 60) : "";368 if (!name) throw new HttpError(400, "invalid_name", "name missing");369 db.prepare("UPDATE users SET display_name = ? WHERE id = ?").run(name, session.userId);370 return { ok: true };371 });372373 app.post("/api/auth/logout", async (request) => {374 const session = requireSession(deps, request);375 db.prepare("DELETE FROM sessions WHERE token_hash = ?").run(session.tokenHash);376 return { ok: true };377 });378379 app.post("/api/auth/logout-all", async (request) => {380 const session = requireSession(deps, request);381 const result = db.prepare("DELETE FROM sessions WHERE user_id = ?").run(session.userId);382 log.add("info", "identity", "signed out of all devices");383 return { ok: true, revoked: Number(result.changes) };384 });385386 /** Removes a device: its sessions end and its copy of the wrapped account key is discarded. */387 app.delete("/api/devices/:id", async (request) => {388 const session = requireSession(deps, request);389 const id = (request.params as any).id as string;390 const device = db.prepare("SELECT id FROM devices WHERE id = ? AND user_id = ? AND revoked_at IS NULL").get(id, session.userId);391 if (!device) throw new HttpError(404, "not_found", "Device not found");392 transaction(db, () => {393 db.prepare("DELETE FROM sessions WHERE device_id = ?").run(id);394 db.prepare("UPDATE devices SET revoked_at = ?, key_envelope = NULL WHERE id = ?").run(now(), id);395 // Its open-tabs record disappears from the other devices.396 const seq = (db.prepare("UPDATE users SET seq = seq + 1 WHERE id = ? RETURNING seq").get(session.userId) as any).seq;397 db.prepare("UPDATE sync_records SET deleted = 1, payload = '', seq = ?, updated_at = ? WHERE user_id = ? AND collection IN ('tabs','closed') AND id = ?")398 .run(seq, now(), session.userId, id);399 });400 log.add("info", "identity", "device removed");401 return { ok: true, signedOutSelf: id === session.deviceId };402 });403404 app.delete("/api/account", async (request) => {405 const session = requireSession(deps, request);406 requireRecentAuth(session);407 // Foreign keys cascade: credentials, devices, sessions, sync records and key material all go.408 db.prepare("DELETE FROM users WHERE id = ?").run(session.userId);409 log.add("warn", "identity", "account and synchronized data deleted");410 return { ok: true };411 });412}413