Branchwell

Branchwell / source / src / auth.ts

1// Passkey sign-in (WebAuthn) and push keys. No passwords, no email, no third-party sign-in.
2import {
3 generateRegistrationOptions, verifyRegistrationResponse, generateAuthenticationOptions, verifyAuthenticationResponse,
4} from '@simplewebauthn/server';
5import type { Env } from './env';
6
7export const RP_NAME = 'Branchwell';
8export const VOTE_WAIT_MS = 24 * 3600 * 1000;
9const SESSION_DAYS = 60;
10export interface Account { id: string; handle: string; created_at: number }
11
12const b64u = (b: Uint8Array) => btoa(String.fromCharCode(...b)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
13const unb64u = (s: string) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4)), (c) => c.charCodeAt(0));
14export const randomId = (n = 18) => b64u(crypto.getRandomValues(new Uint8Array(n)));
15export async function sha256(s: string) { return b64u(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s)))); }
16
17function rp(req: Request) { const u = new URL(req.url); return { rpID: u.hostname, origin: u.origin }; }
18export const HANDLE_RE = /^[a-z0-9](?:[a-z0-9-]{1,28}[a-z0-9])$/;
19
20export async function currentAccount(req: Request, env: Env): Promise<Account | null> {
21 const m = (req.headers.get('cookie') || '').match(/(?:^|;\s*)bw_s=([A-Za-z0-9_-]+)/);
22 if (!m) return null;
23 const row = await env.DB.prepare('SELECT a.id, a.handle, a.created_at FROM sessions s JOIN accounts a ON a.id = s.account_id WHERE s.id = ? AND s.expires_at > ?')
24 .bind(await sha256(m[1]), Date.now()).first<Account>();
25 return row || null;
26}
27export const canVote = (a: Account) => Date.now() - a.created_at >= VOTE_WAIT_MS;
28
29async function startSession(env: Env, accountId: string): Promise<string> {
30 const token = randomId(32);
31 const now = Date.now();
32 await env.DB.prepare('INSERT INTO sessions (id, account_id, created_at, expires_at) VALUES (?, ?, ?, ?)').bind(await sha256(token), accountId, now, now + SESSION_DAYS * 864e5).run();
33 return `bw_s=${token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${SESSION_DAYS * 86400}`;
34}
35export const clearCookie = 'bw_s=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0';
36
37const json = (body: unknown, status = 200, headers: Record<string, string> = {}) =>
38 new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', ...headers } });
39
40async function saveChallenge(env: Env, kind: string, challenge: string, data: unknown) {
41 const id = randomId();
42 await env.DB.prepare('DELETE FROM challenges WHERE created_at < ?').bind(Date.now() - 600_000).run();
43 await env.DB.prepare('INSERT INTO challenges (id, challenge, kind, data, created_at) VALUES (?, ?, ?, ?, ?)').bind(id, challenge, kind, JSON.stringify(data ?? null), Date.now()).run();
44 return id;
45}
46async function takeChallenge(env: Env, id: string, kind: string) {
47 const row = await env.DB.prepare('SELECT challenge, data, created_at FROM challenges WHERE id = ? AND kind = ?').bind(id, kind).first<{ challenge: string; data: string; created_at: number }>();
48 await env.DB.prepare('DELETE FROM challenges WHERE id = ?').bind(id).run();
49 if (!row || Date.now() - row.created_at > 600_000) return null;
50 return { challenge: row.challenge, data: JSON.parse(row.data) };
51}
52
53/** /api/auth/* */
54export async function handleAuth(req: Request, env: Env, path: string): Promise<Response> {
55 const { rpID, origin } = rp(req);
56 if (req.method !== 'POST') return json({ error: 'POST only' }, 405);
57 if (req.headers.get('origin') !== origin) return json({ error: 'Bad origin.' }, 403);
58 const body = await req.json<Record<string, unknown>>().catch(() => ({} as Record<string, unknown>));
59 const me = await currentAccount(req, env);
60
61 if (path === 'register/options') {
62 // New account (pick a name) or, when signed in, add another passkey to your account.
63 let handle = me?.handle || String(body.handle || '').trim().toLowerCase();
64 let userId = me?.id;
65 if (!me) {
66 if (!HANDLE_RE.test(handle)) return json({ error: 'Pick a name of 3 to 30 letters, numbers or dashes.' }, 400);
67 if (RESERVED.has(handle)) return json({ error: 'That name is taken. Try another.' }, 400);
68 if (await env.DB.prepare('SELECT 1 FROM accounts WHERE handle = ?').bind(handle).first()) return json({ error: 'That name is taken. Try another.' }, 400);
69 if (await env.DB.prepare('SELECT 1 FROM orgs WHERE handle = ?').bind(handle).first()) return json({ error: 'That name belongs to a company here. Try another.' }, 400);
70 const ipHash = await sha256((req.headers.get('cf-connecting-ip') || '') + (env.IP_SALT || ''));
71 const n = await env.DB.prepare('SELECT COUNT(*) AS n FROM accounts WHERE ip_hash = ? AND created_at > ?').bind(ipHash, Date.now() - 864e5).first<number>('n');
72 if ((n || 0) >= 3) return json({ error: 'Too many new accounts from this network today. Try again tomorrow.' }, 429);
73 userId = crypto.randomUUID();
74 }
75 const opts = await generateRegistrationOptions({
76 rpName: RP_NAME, rpID, userName: handle!, userDisplayName: handle!, userID: new TextEncoder().encode(userId!) as Uint8Array<ArrayBuffer>,
77 attestationType: 'none', authenticatorSelection: { residentKey: 'required', userVerification: 'preferred' },
78 });
79 const cid = await saveChallenge(env, 'reg', opts.challenge, { handle, userId, existing: !!me });
80 return json({ cid, options: opts });
81 }
82
83 if (path === 'register/verify') {
84 const ch = await takeChallenge(env, String(body.cid || ''), 'reg');
85 if (!ch) return json({ error: 'That took too long. Try again.' }, 400);
86 let v;
87 try { v = await verifyRegistrationResponse({ response: body.response as never, expectedChallenge: ch.challenge, expectedOrigin: origin, expectedRPID: rpID, requireUserVerification: false }); }
88 catch (e) { return json({ error: 'Passkey not accepted: ' + (e as Error).message }, 400); }
89 if (!v.verified || !v.registrationInfo) return json({ error: 'Passkey not accepted.' }, 400);
90 const { handle, userId, existing } = ch.data as { handle: string; userId: string; existing: boolean };
91 const now = Date.now();
92 if (!existing) {
93 const ipHash = await sha256((req.headers.get('cf-connecting-ip') || '') + (env.IP_SALT || ''));
94 try { await env.DB.prepare('INSERT INTO accounts (id, handle, created_at, ip_hash) VALUES (?, ?, ?, ?)').bind(userId, handle, now, ipHash).run(); }
95 catch { return json({ error: 'That name was just taken. Try another.' }, 400); }
96 } else if (!me || me.id !== userId) return json({ error: 'Sign in again.' }, 401);
97 const cred = v.registrationInfo.credential;
98 await env.DB.prepare('INSERT INTO passkeys (id, account_id, public_key, counter, transports, created_at) VALUES (?, ?, ?, ?, ?, ?)')
99 .bind(cred.id, userId, b64u(cred.publicKey), cred.counter, JSON.stringify(cred.transports || []), now).run();
100 const headers: Record<string, string> = existing ? {} : { 'set-cookie': await startSession(env, userId) };
101 return json({ ok: true, handle }, 200, headers);
102 }
103
104 if (path === 'login/options') {
105 const opts = await generateAuthenticationOptions({ rpID, userVerification: 'preferred', allowCredentials: [] });
106 const cid = await saveChallenge(env, 'auth', opts.challenge, null);
107 return json({ cid, options: opts });
108 }
109
110 if (path === 'login/verify') {
111 const ch = await takeChallenge(env, String(body.cid || ''), 'auth');
112 if (!ch) return json({ error: 'That took too long. Try again.' }, 400);
113 const resp = body.response as { id: string };
114 const pk = await env.DB.prepare('SELECT id, account_id, public_key, counter, transports FROM passkeys WHERE id = ?').bind(resp?.id || '').first<{ id: string; account_id: string; public_key: string; counter: number; transports: string }>();
115 if (!pk) return json({ error: 'We don\'t know that passkey. Make an account first.' }, 400);
116 let v;
117 try {
118 v = await verifyAuthenticationResponse({ response: body.response as never, expectedChallenge: ch.challenge, expectedOrigin: origin, expectedRPID: rpID, requireUserVerification: false,
119 credential: { id: pk.id, publicKey: unb64u(pk.public_key), counter: pk.counter, transports: JSON.parse(pk.transports || '[]') } });
120 } catch (e) { return json({ error: 'Passkey not accepted: ' + (e as Error).message }, 400); }
121 if (!v.verified) return json({ error: 'Passkey not accepted.' }, 400);
122 await env.DB.prepare('UPDATE passkeys SET counter = ?, last_used = ? WHERE id = ?').bind(v.authenticationInfo.newCounter, Date.now(), pk.id).run();
123 const acct = await env.DB.prepare('SELECT handle FROM accounts WHERE id = ?').bind(pk.account_id).first<string>('handle');
124 return json({ ok: true, handle: acct }, 200, { 'set-cookie': await startSession(env, pk.account_id) });
125 }
126
127 if (path === 'logout') {
128 const m = (req.headers.get('cookie') || '').match(/(?:^|;\s*)bw_s=([A-Za-z0-9_-]+)/);
129 if (m) await env.DB.prepare('DELETE FROM sessions WHERE id = ?').bind(await sha256(m[1])).run();
130 return json({ ok: true }, 200, { 'set-cookie': clearCookie });
131 }
132
133 if (path === 'push-keys/create') {
134 if (!me) return json({ error: 'Sign in first.' }, 401);
135 const count = await env.DB.prepare('SELECT COUNT(*) AS n FROM push_keys WHERE account_id = ?').bind(me.id).first<number>('n');
136 if ((count || 0) >= 10) return json({ error: 'You have 10 push keys. Remove one first.' }, 400);
137 const name = String(body.name || 'My computer').slice(0, 60);
138 const key = 'bw_push_' + randomId(24).replace(/[-_]/g, 'x');
139 await env.DB.prepare('INSERT INTO push_keys (id, account_id, name, hash, created_at) VALUES (?, ?, ?, ?, ?)').bind(randomId(9), me.id, name, await sha256(key), Date.now()).run();
140 return json({ ok: true, key, handle: me.handle });
141 }
142 if (path === 'push-keys/delete') {
143 if (!me) return json({ error: 'Sign in first.' }, 401);
144 await env.DB.prepare('DELETE FROM push_keys WHERE id = ? AND account_id = ?').bind(String(body.id || ''), me.id).run();
145 return json({ ok: true });
146 }
147 return json({ error: 'Not found' }, 404);
148}
149
150/** Git over HTTPS sends "Basic name:push-key". */
151export async function pusherFromBasic(req: Request, env: Env): Promise<Account | null> {
152 const h = req.headers.get('authorization') || '';
153 if (!h.startsWith('Basic ')) return null;
154 let decoded = '';
155 try { decoded = atob(h.slice(6)); } catch { return null; }
156 const i = decoded.indexOf(':');
157 const key = decoded.slice(i + 1);
158 if (!key.startsWith('bw_push_')) return null;
159 const row = await env.DB.prepare('SELECT a.id, a.handle, a.created_at, k.id AS kid FROM push_keys k JOIN accounts a ON a.id = k.account_id WHERE k.hash = ?')
160 .bind(await sha256(key)).first<Account & { kid: string }>();
161 if (!row) return null;
162 await env.DB.prepare('UPDATE push_keys SET last_used = ? WHERE id = ?').bind(Date.now(), row.kid).run();
163 return { id: row.id, handle: row.handle, created_at: row.created_at };
164}
165
166export const RESERVED = new Set(['api', 'assets', 'widget', 'signin', 'signout', 'account', 'new', 'repos', 'how-to-pull', 'how-to-contribute', 'rules',
167 'features', 'feature-vote', 'careers', 'privacy', 'source', 'robots.txt', 'sitemap.xml', 'llms.txt', 'favicon.svg', 'admin', 'branchwell-votes',
168 'about', 'help', 'login', 'logout', 'settings', 'u', 'static', 'www', 'git', 'root', 'system', 'votes', 'search', 'explore', 'companies', 'research', 'projects', 'orgs']);