Repository Public
1import type { FastifyInstance, FastifyRequest } from "fastify"2import {3 generateAuthenticationOptions,4 generateRegistrationOptions,5 verifyAuthenticationResponse,6 verifyRegistrationResponse,7} from "@simplewebauthn/server"8import { z } from "zod"9import { config } from "./config.js"10import { sql } from "./db.js"11import { hub } from "./hub.js"12import { clearSessionCookie, createSession, requireSession } from "./session.js"13import { audit, bad, limitReq, parse, sha256, uuidBytes, zUuid } from "./util.js"1415const zHandle = z.string().trim().toLowerCase().regex(/^[a-z0-9_.-]{2,32}$/)16const zName = z.string().trim().min(1).max(64)17const zToken = z.string().min(20).max(120)1819async function newChallenge(kind: string, challenge: string, userId: string | null, data: Record<string, unknown>) {20 const [row] = await sql`21 insert into challenges (kind, challenge, user_id, data, expires_at)22 values (${kind}, ${challenge}, ${userId}, ${sql.json(data as never)}, now() + interval '5 minutes') returning id`23 return row.id as string24}25/** Challenges are single use: the row is deleted when it is read. */26async function takeChallenge(id: string, kind: string) {27 const [row] = await sql`delete from challenges where id = ${id} and kind = ${kind} and expires_at > now() returning *`28 if (!row) throw bad("challenge_expired", 400)29 return row30}3132type Gate =33 | { type: "invite"; id: string; createdBy: string | null; requireApproval: boolean }34 | { type: "bootstrap"; hash: Buffer }3536/** Resolves an invitation or bootstrap token to the right to create one account. */37async function checkGate(token: string, bootstrap: boolean): Promise<Gate> {38 const hash = sha256(token)39 if (bootstrap) {40 const [b] = await sql`select 1 from bootstrap_tokens where token_hash = ${hash} and used_at is null and expires_at > now()`41 if (!b) throw bad("invalid_bootstrap_token", 403)42 return { type: "bootstrap", hash }43 }44 const [inv] = await sql`45 select id, created_by, require_approval from invitations46 where token_hash = ${hash} and revoked_at is null and expires_at > now() and uses < max_uses`47 if (!inv) throw bad("invalid_invitation", 403)48 return { type: "invite", id: inv.id, createdBy: inv.created_by, requireApproval: inv.require_approval }49}5051export function authRoutes(app: FastifyInstance) {52 app.get("/api/me", async (req) => {53 const a = await requireSession(req)54 const [u] = await sql`55 select id, handle, display_name, role, status, identity_key, quota_bytes, used_bytes, presence_opt_in, invited_by56 from users where id = ${a.userId}`57 const devices = await sql`select id, label, status, enrolled_via, created_at, last_seen_at from devices where user_id = ${a.userId} and status <> 'revoked' order by created_at`58 const [bk] = await sql`select 1 from key_backups where user_id = ${a.userId}`59 return {60 user: { ...u, identity_key: u.identity_key ? Buffer.from(u.identity_key).toString("base64") : null },61 session: { id: a.sessionId, device_id: a.deviceId },62 devices,63 has_backup: !!bk,64 }65 })6667 // ---- invitation preview (token travels in the request body, never in a URL path)68 app.post("/api/invitations/check", async (req) => {69 limitReq(req, "invite-check", 20)70 const { token, bootstrap } = parse(z.object({ token: zToken, bootstrap: z.boolean().optional() }), req.body)71 const gate = await checkGate(token, !!bootstrap)72 if (gate.type === "bootstrap") return { kind: "bootstrap" }73 const [inviter] = gate.createdBy ? await sql`select display_name, handle from users where id = ${gate.createdBy}` : [null]74 const [inv] = await sql`select recipient, expires_at from invitations where id = ${gate.id}`75 return { kind: "invite", inviter: inviter ?? null, require_approval: gate.requireApproval, recipient: inv.recipient, expires_at: inv.expires_at }76 })7778 // ---- registration (invitation or one-time bootstrap)79 app.post("/api/register/options", async (req) => {80 limitReq(req, "register", 10)81 const body = parse(z.object({ token: zToken, bootstrap: z.boolean().optional(), handle: zHandle, display_name: zName }), req.body)82 await checkGate(body.token, !!body.bootstrap)83 const [taken] = await sql`select 1 from users where handle = ${body.handle}`84 if (taken) throw bad("handle_taken", 409)85 const userId = crypto.randomUUID()86 const options = await generateRegistrationOptions({87 rpName: config.rpName,88 rpID: config.rpId,89 userName: body.handle,90 userDisplayName: body.display_name,91 userID: new Uint8Array(uuidBytes(userId)),92 attestationType: "none",93 authenticatorSelection: { residentKey: "required", userVerification: "required" },94 })95 const id = await newChallenge("register", options.challenge, null, { ...body, userId })96 return { challenge_id: id, options }97 })9899 app.post("/api/register/verify", async (req, reply) => {100 limitReq(req, "register", 10)101 const body = parse(z.object({ challenge_id: zUuid, response: z.any(), label: z.string().max(60).optional() }), req.body)102 const ch = await takeChallenge(body.challenge_id, "register")103 const d = ch.data as { token: string; bootstrap?: boolean; handle: string; display_name: string; userId: string }104 const v = await verifyRegistrationResponse({105 response: body.response,106 expectedChallenge: ch.challenge,107 expectedOrigin: config.origin,108 expectedRPID: config.rpId,109 requireUserVerification: true,110 }).catch(() => null)111 if (!v?.verified) throw bad("passkey_verification_failed", 400)112 const cred = v.registrationInfo.credential113114 const status = await sql.begin(async (tx) => {115 // The gate is consumed in the same transaction that creates the account.116 let invitedBy: string | null = null117 let invitationId: string | null = null118 let role = "member"119 let st = "active"120 if (d.bootstrap) {121 const used = await tx`update bootstrap_tokens set used_at = now() where token_hash = ${sha256(d.token)} and used_at is null and expires_at > now() returning 1`122 if (!used.length) throw bad("invalid_bootstrap_token", 403)123 role = "admin"124 } else {125 const [inv] = await tx`126 update invitations set uses = uses + 1127 where token_hash = ${sha256(d.token)} and revoked_at is null and expires_at > now() and uses < max_uses128 returning id, created_by, require_approval`129 if (!inv) throw bad("invalid_invitation", 403)130 invitedBy = inv.created_by131 invitationId = inv.id132 if (inv.require_approval) st = "pending"133 }134 const [taken] = await tx`select 1 from users where handle = ${d.handle}`135 if (taken) throw bad("handle_taken", 409)136 await tx`insert into users (id, handle, display_name, role, status, invited_by, invitation_id)137 values (${d.userId}, ${d.handle}, ${d.display_name}, ${role}, ${st}, ${invitedBy}, ${invitationId})`138 await tx`insert into passkeys (id, user_id, public_key, counter, transports, device_type, backed_up, label)139 values (${cred.id}, ${d.userId}, ${Buffer.from(cred.publicKey)}, ${cred.counter}, ${cred.transports ?? []},140 ${v.registrationInfo.credentialDeviceType}, ${v.registrationInfo.credentialBackedUp}, ${body.label ?? "Passkey"})`141 return st142 })143 await createSession(req, reply, d.userId, cred.id)144 await audit(req, d.userId, d.bootstrap ? "admin.bootstrap" : "user.register", d.userId, { handle: d.handle, status })145 if (status === "pending") {146 const admins = await sql`select id from users where role = 'admin' and status = 'active'`147 hub.toUsers(admins.map((a) => a.id), { t: "admin", what: "pending-user" })148 }149 return { ok: true, status }150 })151152 // ---- sign in (discoverable credential: no username is asked)153 app.post("/api/login/options", async (req) => {154 limitReq(req, "login", 30)155 const options = await generateAuthenticationOptions({ rpID: config.rpId, userVerification: "required" })156 const id = await newChallenge("login", options.challenge, null, {})157 return { challenge_id: id, options }158 })159160 app.post("/api/login/verify", async (req, reply) => {161 limitReq(req, "login", 30)162 const body = parse(z.object({ challenge_id: zUuid, response: z.any() }), req.body)163 const ch = await takeChallenge(body.challenge_id, "login")164 const credId = String(body.response?.id ?? "")165 const [pk] = await sql`select p.*, u.status from passkeys p join users u on u.id = p.user_id where p.id = ${credId}`166 if (!pk) throw bad("unknown_passkey", 401)167 const v = await verifyAuthenticationResponse({168 response: body.response,169 expectedChallenge: ch.challenge,170 expectedOrigin: config.origin,171 expectedRPID: config.rpId,172 requireUserVerification: true,173 credential: { id: pk.id, publicKey: new Uint8Array(pk.public_key), counter: Number(pk.counter), transports: pk.transports },174 }).catch(() => null)175 if (!v?.verified) {176 await audit(req, pk.user_id, "login.failed", pk.user_id)177 throw bad("passkey_verification_failed", 401)178 }179 if (pk.status === "disabled" || pk.status === "rejected") throw bad("account_disabled", 403)180 await sql`update passkeys set counter = ${v.authenticationInfo.newCounter}, last_used_at = now(), backed_up = ${v.authenticationInfo.credentialBackedUp} where id = ${pk.id}`181 await createSession(req, reply, pk.user_id, pk.id)182 await audit(req, pk.user_id, "login", pk.user_id)183 return { ok: true }184 })185186 app.post("/api/logout", async (req, reply) => {187 const a = await requireSession(req)188 await sql`update sessions set revoked_at = now() where id = ${a.sessionId}`189 hub.closeSession(a.sessionId)190 clearSessionCookie(reply)191 return { ok: true }192 })193194 // ---- passkey management195 app.get("/api/passkeys", async (req) => {196 const a = await requireSession(req)197 return sql`select id, label, device_type, backed_up, created_at, last_used_at from passkeys where user_id = ${a.userId} order by created_at`198 })199 app.post("/api/passkeys/options", async (req) => {200 const a = await requireSession(req)201 const [u] = await sql`select handle, display_name from users where id = ${a.userId}`202 const existing = await sql`select id, transports from passkeys where user_id = ${a.userId}`203 const options = await generateRegistrationOptions({204 rpName: config.rpName,205 rpID: config.rpId,206 userName: u.handle,207 userDisplayName: u.display_name,208 userID: new Uint8Array(uuidBytes(a.userId)),209 attestationType: "none",210 excludeCredentials: existing.map((e) => ({ id: e.id, transports: e.transports })),211 authenticatorSelection: { residentKey: "required", userVerification: "required" },212 })213 const id = await newChallenge("add-passkey", options.challenge, a.userId, {})214 return { challenge_id: id, options }215 })216 app.post("/api/passkeys/verify", async (req) => {217 const a = await requireSession(req)218 const body = parse(z.object({ challenge_id: zUuid, response: z.any(), label: z.string().trim().min(1).max(60) }), req.body)219 const ch = await takeChallenge(body.challenge_id, "add-passkey")220 if (ch.user_id !== a.userId) throw bad("forbidden", 403)221 const v = await verifyRegistrationResponse({222 response: body.response,223 expectedChallenge: ch.challenge,224 expectedOrigin: config.origin,225 expectedRPID: config.rpId,226 requireUserVerification: true,227 }).catch(() => null)228 if (!v?.verified) throw bad("passkey_verification_failed", 400)229 const cred = v.registrationInfo.credential230 await sql`insert into passkeys (id, user_id, public_key, counter, transports, device_type, backed_up, label)231 values (${cred.id}, ${a.userId}, ${Buffer.from(cred.publicKey)}, ${cred.counter}, ${cred.transports ?? []},232 ${v.registrationInfo.credentialDeviceType}, ${v.registrationInfo.credentialBackedUp}, ${body.label})`233 await audit(req, a.userId, "passkey.add", cred.id)234 return { ok: true }235 })236 app.delete("/api/passkeys/:id", async (req) => {237 const a = await requireSession(req)238 const { id } = req.params as { id: string }239 const [{ n }] = await sql`select count(*)::int as n from passkeys where user_id = ${a.userId}`240 if (n <= 1) throw bad("last_passkey", 409, "The last passkey cannot be removed")241 const r = await sql`delete from passkeys where id = ${id} and user_id = ${a.userId} returning 1`242 if (!r.length) throw bad("not_found", 404)243 await sql`update sessions set revoked_at = now() where passkey_id = ${id} and id <> ${a.sessionId} and revoked_at is null`244 await audit(req, a.userId, "passkey.remove", id)245 return { ok: true }246 })247248 // ---- own sessions249 app.get("/api/sessions", async (req) => {250 const a = await requireSession(req)251 const rows = await sql`252 select s.id, s.ip, s.user_agent, s.created_at, s.last_seen_at, s.device_id, d.label as device_label253 from sessions s left join devices d on d.id = s.device_id254 where s.user_id = ${a.userId} and s.revoked_at is null and s.expires_at > now()255 and s.last_seen_at > now() - make_interval(days => ${config.sessionIdleDays})256 order by s.last_seen_at desc`257 return rows.map((r) => ({ ...r, current: r.id === a.sessionId }))258 })259 app.delete("/api/sessions/:id", async (req) => {260 const a = await requireSession(req)261 const { id } = parse(z.object({ id: zUuid }), req.params)262 const r = await sql`update sessions set revoked_at = now() where id = ${id} and user_id = ${a.userId} and revoked_at is null returning 1`263 if (!r.length) throw bad("not_found", 404)264 hub.closeSession(id)265 await audit(req, a.userId, "session.revoke", id)266 return { ok: true }267 })268269 app.patch("/api/profile", async (req) => {270 const a = await requireSession(req)271 const body = parse(z.object({ display_name: zName.optional(), presence_opt_in: z.boolean().optional() }), req.body)272 if (body.display_name !== undefined) await sql`update users set display_name = ${body.display_name} where id = ${a.userId}`273 if (body.presence_opt_in !== undefined) await sql`update users set presence_opt_in = ${body.presence_opt_in} where id = ${a.userId}`274 return { ok: true }275 })276}277278export type { FastifyRequest }279