import { createHash } from "node:crypto";
import { sessionUser } from "@/lib/session-server";
import { createResourceAuth, resourceAuthSettings, type AuthDatabase } from "@/lib/d1-auth";
import * as B from "./server.js";
// BioLock routes under /api/auth/biolock/*: sign in, create an account, add a device, list and remove devices.
const COOKIE = "__Host-airesource-biolock";
const CHALLENGE_AGE = 300;
const LINK_MINUTES = 10;
const sha = (value: string) => createHash("sha256").update(value).digest("hex");
const now = () => Math.floor(Date.now() / 1000);
type Stored = { id: string; user_id: string; public_key: string; alg: number; counter: number; name: string; created_at: number; last_used: number | null };
type Body = { mode?: unknown; ids?: unknown; name?: unknown; token?: unknown; credential?: unknown; deviceName?: unknown; id?: unknown };
function json(data: unknown, status = 200, headers = new Headers()) {
headers.set("Cache-Control", "no-store");
return Response.json(data, { status, headers });
}
const fail = (message: string, status = 400) => json({ error: message }, status);
const cookie = (value: string, age: number) => `${COOKIE}=${value}; Path=/; Max-Age=${age}; Secure; HttpOnly; SameSite=Strict`;
const text = (value: unknown, max: number) => typeof value === "string" && value.trim() && value.trim().length <= max ? value.trim() : null;
async function readBody(request: Request): Promise
{
if (!request.headers.get("content-type")?.startsWith("application/json")) return null;
const raw = await request.text();
if (raw.length > 40_000) return null;
try { return JSON.parse(raw) as Body; } catch { return null; }
}
async function openLink(db: AuthDatabase, token: unknown) {
if (typeof token !== "string" || !/^[\w-]{20,100}$/.test(token)) return null;
return db.prepare("SELECT user_id FROM biolock_link WHERE token_hash = ? AND used = 0 AND expires_at > ?")
.bind(sha(token), now()).first<{ user_id: string }>();
}
export async function biolockRoute(request: Request, step: string): Promise {
const settings = resourceAuthSettings();
const { db, origin } = settings;
const rpId = new URL(origin).hostname;
if (request.method === "POST" && request.headers.get("origin") !== origin) return fail("Request origin was rejected.", 403);
if (step === "devices" && request.method === "GET") {
const user = await sessionUser(request);
if (!user) return fail("Sign in to continue.", 401);
const { results } = await db.prepare("SELECT id, name, created_at, last_used FROM biolock_credential WHERE user_id = ? ORDER BY created_at")
.bind(user.id).all>();
return json({ devices: results });
}
if (request.method !== "POST") return fail("Not found.", 404);
const body = await readBody(request);
if (!body) return fail("Invalid request.");
if (step === "remove") {
const user = await sessionUser(request);
if (!user) return fail("Sign in to continue.", 401);
const count = await db.prepare("SELECT count(*) AS n FROM biolock_credential WHERE user_id = ?").bind(user.id).first<{ n: number }>();
if ((count?.n ?? 0) <= 1) return fail("This is your only device. Add another before removing it.");
await db.prepare("DELETE FROM biolock_credential WHERE id = ? AND user_id = ?").bind(String(body.id ?? ""), user.id).run();
return json({ removed: true });
}
if (step === "link") {
const user = await sessionUser(request);
if (!user) return fail("Sign in to continue.", 401);
const token = B.randomB64u(32);
const expires = now() + LINK_MINUTES * 60;
await db.batch([
db.prepare("DELETE FROM biolock_link WHERE expires_at <= ? OR used = 1").bind(now()),
db.prepare("INSERT INTO biolock_link (token_hash, user_id, expires_at) VALUES (?, ?, ?)").bind(sha(token), user.id, expires),
]);
return json({ url: `${origin}/login?add=${token}`, expiresAt: expires });
}
const mode = body.mode;
if (mode !== "signin" && mode !== "create" && mode !== "link") return fail("Invalid request.");
if (step === "options") {
let options;
if (mode === "signin") {
const ids = Array.isArray(body.ids) ? body.ids.filter((id): id is string => typeof id === "string" && id.length < 400).slice(0, 20) : [];
if (!ids.length) return fail("This device is not set up yet.", 409);
options = B.signInOptions({ rpId, deviceCredentialIds: ids });
} else if (mode === "create") {
const name = text(body.name, 80);
if (!name) return fail("Enter your name.");
options = B.registrationOptions({ rpId, rpName: "Become a Pro", userName: name, displayName: name });
} else {
const link = await openLink(db, body.token);
if (!link) return fail("This link has expired or was already used. Make a new one from your account page.", 410);
const { results } = await db.prepare("SELECT id FROM biolock_credential WHERE user_id = ?").bind(link.user_id).all<{ id: string }>();
options = B.registrationOptions({ rpId, rpName: "Become a Pro", userName: "Become a Pro member", excludeIds: results.map((r) => r.id) });
}
await db.batch([
db.prepare("DELETE FROM sign_in_challenge WHERE expires_at <= ?").bind(now()),
db.prepare("INSERT INTO sign_in_challenge (digest, expires_at) VALUES (?, ?)").bind(sha(options.challenge), now() + CHALLENGE_AGE),
]);
return json(options, 200, new Headers({ "Set-Cookie": cookie(options.challenge, CHALLENGE_AGE) }));
}
if (step !== "verify") return fail("Not found.", 404);
const challenge = request.headers.get("cookie")?.split(";").map((v) => v.trim())
.find((v) => v.startsWith(COOKIE + "="))?.slice(COOKIE.length + 1);
if (!challenge || !/^[\w-]{20,100}$/.test(challenge)) return fail("Sign-in expired. Try again.", 401);
const used = await db.prepare("DELETE FROM sign_in_challenge WHERE digest = ? AND expires_at > ? RETURNING digest").bind(sha(challenge), now()).first();
if (!used) return fail("Sign-in expired. Try again.", 401);
const headers = new Headers({ "Set-Cookie": cookie("", 0) });
const credential = body.credential as { id?: unknown } | undefined;
if (!credential || typeof credential.id !== "string") return fail("Invalid request.");
const check = { credential, expectedChallenge: challenge, expectedOrigin: origin, rpId };
let userId: string | undefined;
let newName: string | undefined;
let record: Awaited> | null = null;
const deviceName = text(body.deviceName, 60) ?? "This device";
try {
if (mode === "signin") {
const stored = await db.prepare("SELECT * FROM biolock_credential WHERE id = ?").bind(credential.id).first();
if (!stored) return json({ error: "This device was removed. Add it again from your account page on another device.", removed: credential.id }, 404, headers);
const result = await B.verifySignIn({ ...check, stored: { id: stored.id, alg: stored.alg, publicKey: JSON.parse(stored.public_key), counter: stored.counter } });
await db.prepare("UPDATE biolock_credential SET counter = ?, last_used = ? WHERE id = ?").bind(result.counter, now(), stored.id).run();
userId = stored.user_id;
} else {
if (mode === "create") {
newName = text(body.name, 80) ?? undefined;
if (!newName) return fail("Enter your name.");
} else {
const link = await openLink(db, body.token);
if (!link) return fail("This link has expired or was already used.", 410);
userId = link.user_id;
}
record = await B.verifyRegistration(check);
}
} catch (error) {
return json({ error: "BioLock check failed: " + (error instanceof Error ? error.message : "try again") + "." }, 401, headers);
}
const auth = createResourceAuth(db, origin, settings.secret);
const started = await auth.api.biolockStartSession({ body: { userId, newName }, headers: request.headers, asResponse: true });
if (!started.ok) return json({ error: "Could not sign you in. Try again." }, 500, headers);
const { userId: accountId } = await started.json() as { userId: string };
if (record) {
const statements = [db.prepare("INSERT INTO biolock_credential (id, user_id, public_key, alg, counter, name, created_at, last_used) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
.bind(record.id, accountId, JSON.stringify(record.publicKey), record.alg, record.counter, deviceName, now(), now())];
if (mode === "link") statements.push(db.prepare("UPDATE biolock_link SET used = 1 WHERE token_hash = ?").bind(sha(String(body.token))));
await db.batch(statements);
}
for (const value of started.headers.getSetCookie()) headers.append("Set-Cookie", value);
return json({ signedIn: true }, 200, headers);
}