Branchwell

Become a Pro / website · becomeapro.ai / src / lib / biolock / routes.ts

1import { createHash } from "node:crypto";
2import { sessionUser } from "@/lib/session-server";
3import { createResourceAuth, resourceAuthSettings, type AuthDatabase } from "@/lib/d1-auth";
4import * as B from "./server.js";
5
6// BioLock routes under /api/auth/biolock/*: sign in, create an account, add a device, list and remove devices.
7const COOKIE = "__Host-airesource-biolock";
8const CHALLENGE_AGE = 300;
9const LINK_MINUTES = 10;
10const sha = (value: string) => createHash("sha256").update(value).digest("hex");
11const now = () => Math.floor(Date.now() / 1000);
12
13type Stored = { id: string; user_id: string; public_key: string; alg: number; counter: number; name: string; created_at: number; last_used: number | null };
14type Body = { mode?: unknown; ids?: unknown; name?: unknown; token?: unknown; credential?: unknown; deviceName?: unknown; id?: unknown };
15
16function json(data: unknown, status = 200, headers = new Headers()) {
17 headers.set("Cache-Control", "no-store");
18 return Response.json(data, { status, headers });
19}
20const fail = (message: string, status = 400) => json({ error: message }, status);
21const cookie = (value: string, age: number) => `${COOKIE}=${value}; Path=/; Max-Age=${age}; Secure; HttpOnly; SameSite=Strict`;
22const text = (value: unknown, max: number) => typeof value === "string" && value.trim() && value.trim().length <= max ? value.trim() : null;
23
24async function readBody(request: Request): Promise<Body | null> {
25 if (!request.headers.get("content-type")?.startsWith("application/json")) return null;
26 const raw = await request.text();
27 if (raw.length > 40_000) return null;
28 try { return JSON.parse(raw) as Body; } catch { return null; }
29}
30
31async function openLink(db: AuthDatabase, token: unknown) {
32 if (typeof token !== "string" || !/^[\w-]{20,100}$/.test(token)) return null;
33 return db.prepare("SELECT user_id FROM biolock_link WHERE token_hash = ? AND used = 0 AND expires_at > ?")
34 .bind(sha(token), now()).first<{ user_id: string }>();
35}
36
37export async function biolockRoute(request: Request, step: string): Promise<Response> {
38 const settings = resourceAuthSettings();
39 const { db, origin } = settings;
40 const rpId = new URL(origin).hostname;
41 if (request.method === "POST" && request.headers.get("origin") !== origin) return fail("Request origin was rejected.", 403);
42
43 if (step === "devices" && request.method === "GET") {
44 const user = await sessionUser(request);
45 if (!user) return fail("Sign in to continue.", 401);
46 const { results } = await db.prepare("SELECT id, name, created_at, last_used FROM biolock_credential WHERE user_id = ? ORDER BY created_at")
47 .bind(user.id).all<Pick<Stored, "id" | "name" | "created_at" | "last_used">>();
48 return json({ devices: results });
49 }
50 if (request.method !== "POST") return fail("Not found.", 404);
51 const body = await readBody(request);
52 if (!body) return fail("Invalid request.");
53
54 if (step === "remove") {
55 const user = await sessionUser(request);
56 if (!user) return fail("Sign in to continue.", 401);
57 const count = await db.prepare("SELECT count(*) AS n FROM biolock_credential WHERE user_id = ?").bind(user.id).first<{ n: number }>();
58 if ((count?.n ?? 0) <= 1) return fail("This is your only device. Add another before removing it.");
59 await db.prepare("DELETE FROM biolock_credential WHERE id = ? AND user_id = ?").bind(String(body.id ?? ""), user.id).run();
60 return json({ removed: true });
61 }
62
63 if (step === "link") {
64 const user = await sessionUser(request);
65 if (!user) return fail("Sign in to continue.", 401);
66 const token = B.randomB64u(32);
67 const expires = now() + LINK_MINUTES * 60;
68 await db.batch([
69 db.prepare("DELETE FROM biolock_link WHERE expires_at <= ? OR used = 1").bind(now()),
70 db.prepare("INSERT INTO biolock_link (token_hash, user_id, expires_at) VALUES (?, ?, ?)").bind(sha(token), user.id, expires),
71 ]);
72 return json({ url: `${origin}/login?add=${token}`, expiresAt: expires });
73 }
74
75 const mode = body.mode;
76 if (mode !== "signin" && mode !== "create" && mode !== "link") return fail("Invalid request.");
77
78 if (step === "options") {
79 let options;
80 if (mode === "signin") {
81 const ids = Array.isArray(body.ids) ? body.ids.filter((id): id is string => typeof id === "string" && id.length < 400).slice(0, 20) : [];
82 if (!ids.length) return fail("This device is not set up yet.", 409);
83 options = B.signInOptions({ rpId, deviceCredentialIds: ids });
84 } else if (mode === "create") {
85 const name = text(body.name, 80);
86 if (!name) return fail("Enter your name.");
87 options = B.registrationOptions({ rpId, rpName: "Become a Pro", userName: name, displayName: name });
88 } else {
89 const link = await openLink(db, body.token);
90 if (!link) return fail("This link has expired or was already used. Make a new one from your account page.", 410);
91 const { results } = await db.prepare("SELECT id FROM biolock_credential WHERE user_id = ?").bind(link.user_id).all<{ id: string }>();
92 options = B.registrationOptions({ rpId, rpName: "Become a Pro", userName: "Become a Pro member", excludeIds: results.map((r) => r.id) });
93 }
94 await db.batch([
95 db.prepare("DELETE FROM sign_in_challenge WHERE expires_at <= ?").bind(now()),
96 db.prepare("INSERT INTO sign_in_challenge (digest, expires_at) VALUES (?, ?)").bind(sha(options.challenge), now() + CHALLENGE_AGE),
97 ]);
98 return json(options, 200, new Headers({ "Set-Cookie": cookie(options.challenge, CHALLENGE_AGE) }));
99 }
100
101 if (step !== "verify") return fail("Not found.", 404);
102 const challenge = request.headers.get("cookie")?.split(";").map((v) => v.trim())
103 .find((v) => v.startsWith(COOKIE + "="))?.slice(COOKIE.length + 1);
104 if (!challenge || !/^[\w-]{20,100}$/.test(challenge)) return fail("Sign-in expired. Try again.", 401);
105 const used = await db.prepare("DELETE FROM sign_in_challenge WHERE digest = ? AND expires_at > ? RETURNING digest").bind(sha(challenge), now()).first();
106 if (!used) return fail("Sign-in expired. Try again.", 401);
107 const headers = new Headers({ "Set-Cookie": cookie("", 0) });
108 const credential = body.credential as { id?: unknown } | undefined;
109 if (!credential || typeof credential.id !== "string") return fail("Invalid request.");
110 const check = { credential, expectedChallenge: challenge, expectedOrigin: origin, rpId };
111
112 let userId: string | undefined;
113 let newName: string | undefined;
114 let record: Awaited<ReturnType<typeof B.verifyRegistration>> | null = null;
115 const deviceName = text(body.deviceName, 60) ?? "This device";
116 try {
117 if (mode === "signin") {
118 const stored = await db.prepare("SELECT * FROM biolock_credential WHERE id = ?").bind(credential.id).first<Stored>();
119 if (!stored) return json({ error: "This device was removed. Add it again from your account page on another device.", removed: credential.id }, 404, headers);
120 const result = await B.verifySignIn({ ...check, stored: { id: stored.id, alg: stored.alg, publicKey: JSON.parse(stored.public_key), counter: stored.counter } });
121 await db.prepare("UPDATE biolock_credential SET counter = ?, last_used = ? WHERE id = ?").bind(result.counter, now(), stored.id).run();
122 userId = stored.user_id;
123 } else {
124 if (mode === "create") {
125 newName = text(body.name, 80) ?? undefined;
126 if (!newName) return fail("Enter your name.");
127 } else {
128 const link = await openLink(db, body.token);
129 if (!link) return fail("This link has expired or was already used.", 410);
130 userId = link.user_id;
131 }
132 record = await B.verifyRegistration(check);
133 }
134 } catch (error) {
135 return json({ error: "BioLock check failed: " + (error instanceof Error ? error.message : "try again") + "." }, 401, headers);
136 }
137
138 const auth = createResourceAuth(db, origin, settings.secret);
139 const started = await auth.api.biolockStartSession({ body: { userId, newName }, headers: request.headers, asResponse: true });
140 if (!started.ok) return json({ error: "Could not sign you in. Try again." }, 500, headers);
141 const { userId: accountId } = await started.json() as { userId: string };
142 if (record) {
143 const statements = [db.prepare("INSERT INTO biolock_credential (id, user_id, public_key, alg, counter, name, created_at, last_used) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
144 .bind(record.id, accountId, JSON.stringify(record.publicKey), record.alg, record.counter, deviceName, now(), now())];
145 if (mode === "link") statements.push(db.prepare("UPDATE biolock_link SET used = 1 WHERE token_hash = ?").bind(sha(String(body.token))));
146 await db.batch(statements);
147 }
148 for (const value of started.headers.getSetCookie()) headers.append("Set-Cookie", value);
149 return json({ signedIn: true }, 200, headers);
150}