Branchwell

Skillfarm / website · skillfarm.ai / src / lib / biolock.ts

Raw 8.6 KB on 89e3b0386808cd2c72180a107bf17e8f384b21a3
1import type { Ctx, User } from '../env';
2import { registrationOptions, signInOptions, verifyRegistration, verifySignIn } from './biolock/server';
3import { HttpError, b64url, newId, now, randomToken, sha256Hex } from './util';
4
5/**
6 * BioLock: sign in with the fingerprint or face reader built into your own device. Nothing else: no passwords,
7 * no outside sign-in providers, no security keys, no phone-to-computer sign-in. The checks live in ./biolock/server.
8 */
9
10const CHALLENGE_SECONDS = 300;
11export const LINK_MINUTES = 10;
12
13export type Credential = { id: string; user_id: string; alg: number; public_jwk: string; counter: number; name: string; created_at: number; last_used_at: number | null };
14type Challenge = { id: string; challenge: string; kind: string; user_id: string | null; link_hash: string | null; expires_at: number };
15export type RegisterMode = 'new' | 'add' | 'link';
16
17function site(c: Ctx): { rpId: string; origin: string } {
18 const u = new URL(c.req.url);
19 return { rpId: u.hostname.replace(/^www\./, ''), origin: u.origin };
20}
21
22async function saveChallenge(c: Ctx, challenge: string, kind: string, userId: string | null, linkHash: string | null = null): Promise<string> {
23 const id = randomToken(18);
24 const ts = now();
25 await c.env.DB.batch([
26 c.env.DB.prepare('DELETE FROM biolock_challenges WHERE expires_at < ?').bind(ts),
27 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),
28 ]);
29 return id;
30}
31
32/** Each challenge works once: it is deleted as it is read. */
33async function takeChallenge(c: Ctx, id: unknown): Promise<Challenge> {
34 if (typeof id !== 'string' || !id) throw new HttpError(400, 'That sign-in expired. Try again.');
35 const row = await c.env.DB.prepare('DELETE FROM biolock_challenges WHERE id = ? RETURNING *').bind(id).first<Challenge>();
36 if (!row || row.expires_at < now()) throw new HttpError(400, 'That sign-in expired. Try again.');
37 return row;
38}
39
40export async function credentialsFor(c: Ctx, userId: string): Promise<Credential[]> {
41 const r = await c.env.DB.prepare('SELECT * FROM biolock_credentials WHERE user_id = ? ORDER BY created_at').bind(userId).all<Credential>();
42 return r.results;
43}
44
45async function linkUser(c: Ctx, token: unknown): Promise<{ hash: string; userId: string }> {
46 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.');
47 const hash = await sha256Hex(token);
48 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 }>();
49 if (!row || row.expires_at < now()) throw new HttpError(410, 'This link was already used or has expired. Make a new one in Settings.');
50 return { hash, userId: row.user_id };
51}
52
53/** Options for adding BioLock on this device: a new account, the signed-in account, or the account a one-time link names. */
54export async function startRegistration(c: Ctx, mode: RegisterMode, token?: unknown) {
55 const user = c.get('user');
56 let userId: string;
57 let label: string;
58 let linkHash: string | null = null;
59 if (mode === 'add') {
60 if (!user) throw new HttpError(401, 'Sign in first.');
61 userId = user.id;
62 label = user.handle;
63 } else if (mode === 'link') {
64 const link = await linkUser(c, token);
65 userId = link.userId;
66 linkHash = link.hash;
67 const owner = await c.env.DB.prepare('SELECT handle FROM users WHERE id = ?').bind(userId).first<{ handle: string }>();
68 label = owner?.handle ?? 'skillfarm';
69 } else {
70 userId = newId();
71 label = `grower-${userId.slice(0, 5)}`;
72 }
73 const exclude = mode === 'new' ? [] : (await credentialsFor(c, userId)).map((x) => x.id);
74 const { rpId } = site(c);
75 const options = registrationOptions({ rpId, rpName: 'Skillfarm', userId: b64url(new TextEncoder().encode(userId)), userName: label, displayName: label, excludeIds: exclude as never[] });
76 return { options, challengeId: await saveChallenge(c, options.challenge, mode, userId, linkHash) };
77}
78
79/** Checks the new device and stores its public key. Returns the account it belongs to and whether that account is new. */
80export async function finishRegistration(c: Ctx, challengeId: unknown, response: unknown, name: string): Promise<{ userId: string; created: boolean }> {
81 const ch = await takeChallenge(c, challengeId);
82 if (!['new', 'add', 'link'].includes(ch.kind) || !ch.user_id) throw new HttpError(400, 'That sign-in expired. Try again.');
83 if (ch.kind === 'add' && c.get('user')?.id !== ch.user_id) throw new HttpError(401, 'Sign in first.');
84 const { rpId, origin } = site(c);
85 let record: { id: string; alg: number; publicKey: JsonWebKey; counter: number };
86 try {
87 record = await verifyRegistration({ credential: response, expectedChallenge: ch.challenge, expectedOrigin: origin, rpId });
88 } catch (e) {
89 throw new HttpError(400, `BioLock could not add this device: ${(e as Error).message}.`);
90 }
91 if (ch.kind === 'link') {
92 // Spend the link now, once. A second use finds nothing to delete.
93 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 }>();
94 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.');
95 }
96 const ts = now();
97 const insert = c.env.DB.prepare('INSERT INTO biolock_credentials (id, user_id, alg, public_jwk, counter, name, created_at) VALUES (?,?,?,?,?,?,?)').bind(
98 record.id, ch.user_id, record.alg, JSON.stringify(record.publicKey), record.counter, name.slice(0, 40), ts,
99 );
100 if (ch.kind === 'new') {
101 await c.env.DB.batch([
102 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),
103 insert,
104 ]);
105 return { userId: ch.user_id, created: true };
106 }
107 await insert.run();
108 return { userId: ch.user_id, created: false };
109}
110
111/** Sign-in options. `ids` are the device IDs this browser added; with none, the device's own reader offers what it holds. */
112export async function startSignIn(c: Ctx, ids: unknown) {
113 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) : [];
114 const { rpId } = site(c);
115 const options = signInOptions({ rpId, deviceCredentialIds: list as never[] });
116 return { options, challengeId: await saveChallenge(c, options.challenge, 'signin', null) };
117}
118
119export async function finishSignIn(c: Ctx, challengeId: unknown, response: unknown): Promise<User> {
120 const ch = await takeChallenge(c, challengeId);
121 if (ch.kind !== 'signin') throw new HttpError(400, 'That sign-in expired. Try again.');
122 const id = (response as { id?: unknown } | null)?.id;
123 if (typeof id !== 'string') throw new HttpError(400, 'BioLock did not finish. Try again.');
124 const cred = await c.env.DB.prepare('SELECT * FROM biolock_credentials WHERE id = ?').bind(id).first<Credential>();
125 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.');
126 const { rpId, origin } = site(c);
127 let result: { counter: number };
128 try {
129 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 });
130 } catch (e) {
131 throw new HttpError(401, `BioLock could not sign you in: ${(e as Error).message}.`);
132 }
133 await c.env.DB.prepare('UPDATE biolock_credentials SET counter = ?, last_used_at = ? WHERE id = ?').bind(result.counter, now(), cred.id).run();
134 const user = await c.env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(cred.user_id).first<User>();
135 if (!user || user.status !== 'active') throw new HttpError(403, 'This account is not active.');
136 return user;
137}
138
139/** A one-time link that adds BioLock on another device. The code sits in the URL fragment, so servers never log it. */
140export async function makeLink(c: Ctx, userId: string): Promise<string> {
141 const token = randomToken(24);
142 const ts = now();
143 await c.env.DB.batch([
144 c.env.DB.prepare('DELETE FROM biolock_links WHERE expires_at < ?').bind(ts),
145 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),
146 ]);
147 return `${new URL(c.req.url).origin}/biolock/add#${token}`;
148}