import type { Ctx, User } from '../env'; import { registrationOptions, signInOptions, verifyRegistration, verifySignIn } from './biolock/server'; import { HttpError, b64url, newId, now, randomToken, sha256Hex } from './util'; /** * BioLock: sign in with the fingerprint or face reader built into your own device. Nothing else: no passwords, * no outside sign-in providers, no security keys, no phone-to-computer sign-in. The checks live in ./biolock/server. */ const CHALLENGE_SECONDS = 300; export const LINK_MINUTES = 10; export type Credential = { id: string; user_id: string; alg: number; public_jwk: string; counter: number; name: string; created_at: number; last_used_at: number | null }; type Challenge = { id: string; challenge: string; kind: string; user_id: string | null; link_hash: string | null; expires_at: number }; export type RegisterMode = 'new' | 'add' | 'link'; function site(c: Ctx): { rpId: string; origin: string } { const u = new URL(c.req.url); return { rpId: u.hostname.replace(/^www\./, ''), origin: u.origin }; } async function saveChallenge(c: Ctx, challenge: string, kind: string, userId: string | null, linkHash: string | null = null): Promise { const id = randomToken(18); const ts = now(); await c.env.DB.batch([ c.env.DB.prepare('DELETE FROM biolock_challenges WHERE expires_at < ?').bind(ts), c.env.DB.prepare('INSERT INTO biolock_challenges (id, challenge, kind, user_id, link_hash, expires_at) VALUES (?,?,?,?,?,?)').bind(id, challenge, kind, userId, linkHash, ts + CHALLENGE_SECONDS), ]); return id; } /** Each challenge works once: it is deleted as it is read. */ async function takeChallenge(c: Ctx, id: unknown): Promise { if (typeof id !== 'string' || !id) throw new HttpError(400, 'That sign-in expired. Try again.'); const row = await c.env.DB.prepare('DELETE FROM biolock_challenges WHERE id = ? RETURNING *').bind(id).first(); if (!row || row.expires_at < now()) throw new HttpError(400, 'That sign-in expired. Try again.'); return row; } export async function credentialsFor(c: Ctx, userId: string): Promise { const r = await c.env.DB.prepare('SELECT * FROM biolock_credentials WHERE user_id = ? ORDER BY created_at').bind(userId).all(); return r.results; } async function linkUser(c: Ctx, token: unknown): Promise<{ hash: string; userId: string }> { if (typeof token !== 'string' || token.length < 20 || token.length > 100) throw new HttpError(400, 'This link is not valid. Make a new one in Settings.'); const hash = await sha256Hex(token); const row = await c.env.DB.prepare('SELECT user_id, expires_at FROM biolock_links WHERE token_hash = ?').bind(hash).first<{ user_id: string; expires_at: number }>(); if (!row || row.expires_at < now()) throw new HttpError(410, 'This link was already used or has expired. Make a new one in Settings.'); return { hash, userId: row.user_id }; } /** Options for adding BioLock on this device: a new account, the signed-in account, or the account a one-time link names. */ export async function startRegistration(c: Ctx, mode: RegisterMode, token?: unknown) { const user = c.get('user'); let userId: string; let label: string; let linkHash: string | null = null; if (mode === 'add') { if (!user) throw new HttpError(401, 'Sign in first.'); userId = user.id; label = user.handle; } else if (mode === 'link') { const link = await linkUser(c, token); userId = link.userId; linkHash = link.hash; const owner = await c.env.DB.prepare('SELECT handle FROM users WHERE id = ?').bind(userId).first<{ handle: string }>(); label = owner?.handle ?? 'skillfarm'; } else { userId = newId(); label = `grower-${userId.slice(0, 5)}`; } const exclude = mode === 'new' ? [] : (await credentialsFor(c, userId)).map((x) => x.id); const { rpId } = site(c); const options = registrationOptions({ rpId, rpName: 'Skillfarm', userId: b64url(new TextEncoder().encode(userId)), userName: label, displayName: label, excludeIds: exclude as never[] }); return { options, challengeId: await saveChallenge(c, options.challenge, mode, userId, linkHash) }; } /** Checks the new device and stores its public key. Returns the account it belongs to and whether that account is new. */ export async function finishRegistration(c: Ctx, challengeId: unknown, response: unknown, name: string): Promise<{ userId: string; created: boolean }> { const ch = await takeChallenge(c, challengeId); if (!['new', 'add', 'link'].includes(ch.kind) || !ch.user_id) throw new HttpError(400, 'That sign-in expired. Try again.'); if (ch.kind === 'add' && c.get('user')?.id !== ch.user_id) throw new HttpError(401, 'Sign in first.'); const { rpId, origin } = site(c); let record: { id: string; alg: number; publicKey: JsonWebKey; counter: number }; try { record = await verifyRegistration({ credential: response, expectedChallenge: ch.challenge, expectedOrigin: origin, rpId }); } catch (e) { throw new HttpError(400, `BioLock could not add this device: ${(e as Error).message}.`); } if (ch.kind === 'link') { // Spend the link now, once. A second use finds nothing to delete. const spent = await c.env.DB.prepare('DELETE FROM biolock_links WHERE token_hash = ? AND expires_at >= ? RETURNING user_id').bind(ch.link_hash, now()).first<{ user_id: string }>(); if (!spent || spent.user_id !== ch.user_id) throw new HttpError(410, 'This link was already used or has expired. Make a new one in Settings.'); } const ts = now(); const insert = c.env.DB.prepare('INSERT INTO biolock_credentials (id, user_id, alg, public_jwk, counter, name, created_at) VALUES (?,?,?,?,?,?,?)').bind( record.id, ch.user_id, record.alg, JSON.stringify(record.publicKey), record.counter, name.slice(0, 40), ts, ); if (ch.kind === 'new') { await c.env.DB.batch([ c.env.DB.prepare("INSERT INTO users (id, handle, display_name, created_at) VALUES (?,?,'New grower',?)").bind(ch.user_id, `grower-${ch.user_id.slice(0, 8)}`, ts), insert, ]); return { userId: ch.user_id, created: true }; } await insert.run(); return { userId: ch.user_id, created: false }; } /** Sign-in options. `ids` are the device IDs this browser added; with none, the device's own reader offers what it holds. */ export async function startSignIn(c: Ctx, ids: unknown) { const list = Array.isArray(ids) ? ids.filter((x): x is string => typeof x === 'string' && /^[A-Za-z0-9_-]{16,400}$/.test(x)).slice(0, 20) : []; const { rpId } = site(c); const options = signInOptions({ rpId, deviceCredentialIds: list as never[] }); return { options, challengeId: await saveChallenge(c, options.challenge, 'signin', null) }; } export async function finishSignIn(c: Ctx, challengeId: unknown, response: unknown): Promise { const ch = await takeChallenge(c, challengeId); if (ch.kind !== 'signin') throw new HttpError(400, 'That sign-in expired. Try again.'); const id = (response as { id?: unknown } | null)?.id; if (typeof id !== 'string') throw new HttpError(400, 'BioLock did not finish. Try again.'); const cred = await c.env.DB.prepare('SELECT * FROM biolock_credentials WHERE id = ?').bind(id).first(); if (!cred) throw new HttpError(401, 'This device has no BioLock for Skillfarm yet. Create an account, or add this device from Settings on a device that is signed in.'); const { rpId, origin } = site(c); let result: { counter: number }; try { result = await verifySignIn({ credential: response, stored: { id: cred.id, alg: cred.alg, publicKey: JSON.parse(cred.public_jwk), counter: cred.counter }, expectedChallenge: ch.challenge, expectedOrigin: origin, rpId }); } catch (e) { throw new HttpError(401, `BioLock could not sign you in: ${(e as Error).message}.`); } await c.env.DB.prepare('UPDATE biolock_credentials SET counter = ?, last_used_at = ? WHERE id = ?').bind(result.counter, now(), cred.id).run(); const user = await c.env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(cred.user_id).first(); if (!user || user.status !== 'active') throw new HttpError(403, 'This account is not active.'); return user; } /** A one-time link that adds BioLock on another device. The code sits in the URL fragment, so servers never log it. */ export async function makeLink(c: Ctx, userId: string): Promise { const token = randomToken(24); const ts = now(); await c.env.DB.batch([ c.env.DB.prepare('DELETE FROM biolock_links WHERE expires_at < ?').bind(ts), c.env.DB.prepare('INSERT INTO biolock_links (token_hash, user_id, expires_at, created_at) VALUES (?,?,?,?)').bind(await sha256Hex(token), userId, ts + LINK_MINUTES * 60, ts), ]); return `${new URL(c.req.url).origin}/biolock/add#${token}`; }