Repository Public
1// Accounts, passkeys (WebAuthn), sessions, step-up, devices, pairing, recovery, account rekey.2import crypto from "node:crypto";3import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";4import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse } from "@simplewebauthn/server";5import { z } from "zod";6import { ctx, unb64u } from "../../../packages/protocol/src/bytes.ts";7import { verify as ecdsaVerify } from "../../../packages/protocol/src/primitives.ts";8import {9 audit, bad, clientIp, config, COOKIE, createSession, forbidden, HttpError, need, needStrong, notFound, publish, rateLimit, safeEqual,10 setSessionCookie, sha256b64u, sql, type Session, type Sql,11} from "./core.ts";1213const b64 = (bytes: number) => z.string().regex(/^[A-Za-z0-9_-]+$/).length(Math.ceil((bytes * 4) / 3));14const b64var = (min: number, max: number) => z.string().regex(/^[A-Za-z0-9_-]+$/).min(min).max(max);15export const uuid = z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);16const pub = b64(65), sig = b64(64), arkEnvelope = b64(65 + 32 + 16), recoveryEnvelope = b64(12 + 32 + 16), hash = b64(32);17const handle = z.string().regex(/^[a-z0-9][a-z0-9._-]{1,31}$/);18const platform = z.string().regex(/^[A-Za-z0-9 ·.,()_-]{1,48}$/);19const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/);20const keyset = z.object({ nonce: b64(12), ct: b64var(100, 2000) }).strict();21const recovery = z.object({ epoch: z.number().int().min(1), envelope: recoveryEnvelope, authHash: hash }).strict();22const deviceNew = z.object({ deviceId: uuid, encPub: pub, sigPub: pub, createdAt: isoDate, cert: sig, arkEnvelope, platform, hardware: z.boolean() }).strict();23export const envelope = z.object({ v: z.literal(1), alg: z.literal(1), kid: z.number().int().min(1), salt: b64(32), nonce: b64(12), ct: b64var(363, 1_400_000) }).strict();24export const grant = z.object({ vaultId: uuid, epoch: z.number().int().min(1), memberAccountId: uuid, role: z.enum(["owner", "editor", "reader"]), envelope: arkEnvelope, granterAccountId: uuid, sig }).strict();2526export function parse<T extends z.ZodTypeAny>(schema: T, value: unknown): z.infer<T> {27 const r = schema.safeParse(value);28 if (!r.success) throw bad("invalid_request", r.error.issues.slice(0, 3).map((i) => `${i.path.join(".")}: ${i.message}`).join("; "));29 return r.data;30}3132const certMessage = (accountId: string, d: { deviceId: string; encPub: string; sigPub: string; createdAt: string }) => ctx("device-cert", accountId, d.deviceId, d.encPub, d.sigPub, d.createdAt);33async function checkCert(accountSigPub: string, accountId: string, d: { deviceId: string; encPub: string; sigPub: string; createdAt: string; cert: string }) {34 if (!(await ecdsaVerify(unb64u(accountSigPub), certMessage(accountId, d), unb64u(d.cert)))) throw bad("invalid_device_certificate");35}3637async function newChallenge(kind: string, accountId: string | null, challenge: string, data: object = {}, ttlSec = 300): Promise<string> {38 const id = crypto.randomUUID();39 await sql`insert into challenges (id, kind, account_id, challenge, data, expires_at) values (${id}, ${kind}, ${accountId}, ${challenge}, ${sql.json(data as any)}, now() + ${ttlSec} * interval '1 second')`;40 return id;41}42/** Single use: the challenge row is deleted when read. */43async function takeChallenge(id: string, kind: string) {44 const [c] = await sql`delete from challenges where id = ${id} and kind = ${kind} and expires_at > now() returning *`;45 if (!c) throw bad("challenge_expired", "The challenge expired or was already used");46 return c;47}4849async function verifyAssertion(response: any, challenge: string, expectAccount?: string) {50 const credId = String(response?.id ?? "");51 const [cred] = await sql`select * from credentials where id = ${credId}`;52 if (!cred || (expectAccount && cred.account_id !== expectAccount)) throw new HttpError(401, "authentication_failed");53 let result;54 try {55 result = await verifyAuthenticationResponse({56 response, expectedChallenge: challenge, expectedOrigin: config.origin, expectedRPID: config.rpId, requireUserVerification: true,57 credential: { id: cred.id, publicKey: new Uint8Array(cred.public_key), counter: Number(cred.counter), transports: cred.transports },58 });59 } catch { throw new HttpError(401, "authentication_failed"); }60 if (!result.verified) throw new HttpError(401, "authentication_failed");61 await sql`update credentials set counter = ${result.authenticationInfo.newCounter}, last_used_at = now() where id = ${cred.id}`;62 return cred.account_id as string;63}6465async function accountView(db: Sql, accountId: string) {66 const [a] = await db`select id, handle, sig_pub, enc_pub, keyset, recovery_epoch, key_epoch from accounts where id = ${accountId}`;67 return { accountId: a.id, handle: a.handle, sigPub: a.sig_pub, encPub: a.enc_pub, keyset: a.keyset, recoveryEpoch: a.recovery_epoch, keyEpoch: a.key_epoch };68}69const deviceView = (d: any) => ({ deviceId: d.id, encPub: d.enc_pub, sigPub: d.sig_pub, createdAt: d.created_at_signed, cert: d.cert, platform: d.platform, hardware: d.hardware, addedAt: d.created_at, lastSeenAt: d.last_seen_at });7071function sessionReply(req: FastifyRequest, reply: FastifyReply, token: string, body: object) {72 // Browsers get an HttpOnly cookie; native clients ask for the token in the body and send it as a Bearer header.73 if (req.headers["x-spv-client"] === "native") return { ...body, token };74 setSessionCookie(reply, token);75 return body;76}7778export function authRoutes(app: FastifyInstance) {79 // ── registration (invitation → account + first passkey + first device + personal vault, atomically) ────────80 app.post("/api/v1/auth/register/options", async (req) => {81 rateLimit(`reg:${clientIp(req)}`, 10, 600);82 const b = parse(z.object({ invite: z.string().min(20).max(80), handle, accountId: uuid }).strict(), req.body);83 const [inv] = await sql`select 1 from invites where token_hash = ${sha256b64u(b.invite)} and used_at is null and expires_at > now()`;84 if (!inv) throw forbidden("invalid_invite", "This invitation is invalid, expired or already used");85 if ((await sql`select 1 from accounts where handle = ${b.handle} or id = ${b.accountId}`).length) throw new HttpError(409, "handle_taken");86 const options = await generateRegistrationOptions({87 rpName: config.rpName, rpID: config.rpId, userName: b.handle, userDisplayName: b.handle, userID: new TextEncoder().encode(b.accountId),88 attestationType: "none", authenticatorSelection: { residentKey: "required", userVerification: "required" },89 });90 return { challengeId: await newChallenge("register", null, options.challenge, { invite: sha256b64u(b.invite), handle: b.handle, accountId: b.accountId }), options };91 });9293 app.post("/api/v1/auth/register/verify", async (req, reply) => {94 rateLimit(`reg:${clientIp(req)}`, 10, 600);95 const b = parse(z.object({96 challengeId: uuid, response: z.any(), sigPub: pub, encPub: pub, keyset, recovery, device: deviceNew,97 vault: z.object({ vaultId: uuid, grant, meta: z.object({ recordId: uuid, envelope }).strict() }).strict(),98 }).strict(), req.body);99 const c = await takeChallenge(b.challengeId, "register");100 const accountId: string = c.data.accountId;101 let info;102 try {103 const r = await verifyRegistrationResponse({ response: b.response, expectedChallenge: c.challenge, expectedOrigin: config.origin, expectedRPID: config.rpId, requireUserVerification: true });104 if (!r.verified || !r.registrationInfo) throw new Error();105 info = r.registrationInfo;106 } catch { throw bad("registration_failed", "The passkey could not be verified"); }107 await checkCert(b.sigPub, accountId, b.device);108 if (b.vault.grant.vaultId !== b.vault.vaultId || b.vault.grant.memberAccountId !== accountId || b.vault.grant.granterAccountId !== accountId || b.vault.grant.epoch !== 1 || b.vault.grant.role !== "owner" || b.recovery.epoch !== 1) throw bad("invalid_request", "inconsistent initial vault");109 const token = await sql.begin(async (tx) => {110 const used = await tx`update invites set used_at = now(), used_by = ${accountId} where token_hash = ${c.data.invite} and used_at is null and expires_at > now() returning 1`;111 if (!used.length) throw forbidden("invalid_invite");112 await tx`insert into accounts (id, handle, sig_pub, enc_pub, keyset, recovery_epoch, recovery_envelope, recovery_auth_hash)113 values (${accountId}, ${c.data.handle}, ${b.sigPub}, ${b.encPub}, ${tx.json(b.keyset)}, 1, ${b.recovery.envelope}, ${b.recovery.authHash})`;114 await tx`insert into credentials (id, account_id, public_key, counter, transports) values (${info.credential.id}, ${accountId}, ${Buffer.from(info.credential.publicKey)}, ${info.credential.counter}, ${info.credential.transports ?? []})`;115 await insertDevice(tx, accountId, b.device);116 await createVault(tx, accountId, b.device.deviceId, b.vault);117 await audit(tx, accountId, "account.created", { platform: b.device.platform }, b.device.deviceId);118 return createSession(tx, accountId, "device", b.device.deviceId, true);119 });120 return sessionReply(req, reply, token, { account: await accountView(sql, accountId) });121 });122123 // ── login ────────────────────────────────────────────────────────────────────────────────────────────────124 app.post("/api/v1/auth/login/options", async (req) => {125 rateLimit(`login:${clientIp(req)}`, 30, 300);126 const options = await generateAuthenticationOptions({ rpID: config.rpId, userVerification: "required" }); // discoverable credential: no handle, no enumeration127 return { challengeId: await newChallenge("login", null, options.challenge), options };128 });129130 app.post("/api/v1/auth/login/verify", async (req, reply) => {131 rateLimit(`login:${clientIp(req)}`, 30, 300);132 const b = parse(z.object({ challengeId: uuid, response: z.any(), device: z.object({ deviceId: uuid, proof: sig }).strict().optional() }).strict(), req.body);133 const c = await takeChallenge(b.challengeId, "login");134 const accountId = await verifyAssertion(b.response, c.challenge);135 let deviceId: string | null = null, env: string | undefined;136 if (b.device) {137 // A device session needs the passkey AND a signature by the certified device key over this challenge.138 const [d] = await sql`select * from devices where id = ${b.device.deviceId} and account_id = ${accountId} and revoked_at is null`;139 if (!d) {140 // a device enrolled under ANOTHER account must not be told it was revoked (clients erase themselves on device_unknown)141 const [foreign] = await sql`select 1 from devices where id = ${b.device.deviceId} and account_id <> ${accountId}`;142 if (foreign) throw new HttpError(400, "wrong_account", "This passkey belongs to another account than the one enrolled on this device");143 throw new HttpError(401, "device_unknown", "This device is not (or no longer) authorized for the account");144 }145 if (!(await ecdsaVerify(unb64u(d.sig_pub), ctx("login", c.challenge, d.id), unb64u(b.device.proof)))) throw new HttpError(401, "authentication_failed");146 deviceId = d.id; env = d.ark_envelope;147 }148 const token = await createSession(sql, accountId, deviceId ? "device" : "pending", deviceId, !!deviceId);149 if (deviceId) await sql.begin((tx) => audit(tx, accountId, "session.login", {}, deviceId));150 return sessionReply(req, reply, token, { kind: deviceId ? "device" : "pending", account: await accountView(sql, accountId), arkEnvelope: env });151 });152153 app.post("/api/v1/auth/logout", async (req, reply) => {154 const s = await need(req, "device", "pending", "recovery");155 await sql`delete from sessions where token_hash = ${s.tokenHash}`;156 reply.clearCookie(COOKIE(), { path: "/" });157 return { ok: true };158 });159160 app.get("/api/v1/auth/session", async (req) => {161 const s = await need(req, "device", "pending", "recovery");162 return { kind: s.kind, deviceId: s.deviceId, account: await accountView(sql, s.accountId), strong: !!s.strongAt && Date.now() - s.strongAt.getTime() < 300_000 };163 });164165 // ── step-up: fresh passkey assertion (any client) or device-key signature (native clients, biometric-gated key) ──166 app.post("/api/v1/auth/stepup/options", async (req) => {167 const s = await need(req, "device");168 rateLimit(`stepup:${s.accountId}`, 30, 300);169 const creds = await sql`select id, transports from credentials where account_id = ${s.accountId}`;170 const options = await generateAuthenticationOptions({ rpID: config.rpId, userVerification: "required", allowCredentials: creds.map((c) => ({ id: c.id, transports: c.transports })) });171 return { challengeId: await newChallenge("stepup", s.accountId, options.challenge, { session: s.tokenHash }), options };172 });173174 app.post("/api/v1/auth/stepup/verify", async (req) => {175 const s = await need(req, "device");176 const b = parse(z.object({ challengeId: uuid, response: z.any().optional(), deviceProof: sig.optional() }).strict(), req.body);177 const c = await takeChallenge(b.challengeId, "stepup");178 if (c.data.session !== s.tokenHash) throw forbidden();179 let arkEnv: string | undefined;180 if (b.response) await verifyAssertion(b.response, c.challenge, s.accountId);181 else if (b.deviceProof && s.platform && !s.platform.startsWith("Web")) {182 const [d] = await sql`select sig_pub from devices where id = ${s.deviceId}`;183 if (!(await ecdsaVerify(unb64u(d.sig_pub), ctx("stepup", c.challenge, s.deviceId!), unb64u(b.deviceProof)))) throw new HttpError(401, "authentication_failed");184 } else throw bad("invalid_request", "A passkey assertion is required");185 await sql`update sessions set strong_at = now() where token_hash = ${s.tokenHash}`;186 [{ ark_envelope: arkEnv }] = await sql`select ark_envelope from devices where id = ${s.deviceId}` as any;187 return { ok: true, arkEnvelope: arkEnv };188 });189190 // ── passkeys ─────────────────────────────────────────────────────────────────────────────────────────────191 app.get("/api/v1/auth/passkeys", async (req) => {192 const s = await need(req, "device");193 return { passkeys: (await sql`select id, label, created_at, last_used_at from credentials where account_id = ${s.accountId} order by created_at`).map((c) => ({ id: c.id, label: c.label, createdAt: c.created_at, lastUsedAt: c.last_used_at })) };194 });195 app.post("/api/v1/auth/passkeys/options", async (req) => {196 const s = await need(req, "device", "recovery");197 if (s.kind === "device") await needStrong(req);198 const [a] = await sql`select handle from accounts where id = ${s.accountId}`;199 const existing = await sql`select id, transports from credentials where account_id = ${s.accountId}`;200 const options = await generateRegistrationOptions({201 rpName: config.rpName, rpID: config.rpId, userName: a.handle, userDisplayName: a.handle, userID: new TextEncoder().encode(s.accountId), attestationType: "none",202 authenticatorSelection: { residentKey: "required", userVerification: "required" }, excludeCredentials: existing.map((c) => ({ id: c.id, transports: c.transports })),203 });204 return { challengeId: await newChallenge("passkey", s.accountId, options.challenge), options };205 });206 app.post("/api/v1/auth/passkeys/verify", async (req) => {207 const s = await need(req, "device", "recovery");208 const b = parse(z.object({ challengeId: uuid, response: z.any(), label: z.string().max(48).optional() }).strict(), req.body);209 const c = await takeChallenge(b.challengeId, "passkey");210 if (c.account_id !== s.accountId) throw forbidden();211 let info;212 try {213 const r = await verifyRegistrationResponse({ response: b.response, expectedChallenge: c.challenge, expectedOrigin: config.origin, expectedRPID: config.rpId, requireUserVerification: true });214 if (!r.verified || !r.registrationInfo) throw new Error();215 info = r.registrationInfo;216 } catch { throw bad("registration_failed"); }217 await sql.begin(async (tx) => {218 await tx`insert into credentials (id, account_id, public_key, counter, transports, label) values (${info.credential.id}, ${s.accountId}, ${Buffer.from(info.credential.publicKey)}, ${info.credential.counter}, ${info.credential.transports ?? []}, ${b.label ?? ""})`;219 await audit(tx, s.accountId, "passkey.added", {}, s.deviceId);220 });221 return { ok: true };222 });223 app.delete("/api/v1/auth/passkeys/:id", async (req) => {224 const s = await needStrong(req);225 const id = (req.params as any).id as string;226 await sql.begin(async (tx) => {227 const n = await tx`select count(*)::int as n from credentials where account_id = ${s.accountId}`;228 if (n[0]!.n <= 1) throw bad("last_passkey", "The last passkey cannot be removed");229 if (!(await tx`delete from credentials where id = ${id} and account_id = ${s.accountId} returning 1`).length) throw notFound();230 await audit(tx, s.accountId, "passkey.removed", {}, s.deviceId);231 });232 return { ok: true };233 });234235 // ── devices ──────────────────────────────────────────────────────────────────────────────────────────────236 app.get("/api/v1/devices", async (req) => {237 const s = await need(req, "device");238 const rows = await sql`select * from devices where account_id = ${s.accountId} and revoked_at is null order by created_at`;239 return { current: s.deviceId, account: await accountView(sql, s.accountId), devices: rows.map(deviceView) };240 });241242 app.delete("/api/v1/devices/:id", async (req) => {243 const s = await needStrong(req);244 const id = parse(uuid, (req.params as any).id);245 await sql.begin(async (tx) => {246 const r = await tx`update devices set revoked_at = now(), ark_envelope = '' where id = ${id} and account_id = ${s.accountId} and revoked_at is null returning platform`;247 if (!r.length) throw notFound();248 await tx`delete from sessions where device_id = ${id}`;249 await audit(tx, s.accountId, "device.revoked", { device: id, platform: r[0]!.platform }, s.deviceId);250 });251 publish([s.accountId], { type: "devices" });252 return { ok: true };253 });254255 // ── pairing (SPV1 §5) ────────────────────────────────────────────────────────────────────────────────────256 app.post("/api/v1/pairings", async (req) => {257 const s = await need(req, "pending");258 rateLimit(`pair:${s.accountId}`, 10, 600);259 const b = parse(z.object({ pairingId: uuid, deviceId: uuid, encPub: pub, sigPub: pub, createdAt: isoDate, tag: hash, platform, hardware: z.boolean() }).strict(), req.body);260 const id = b.pairingId; // chosen by the device so the tag can bind it (a duplicate id fails on the primary key)261 await sql`insert into pairings (id, account_id, session_hash, device_id, enc_pub, sig_pub, created_at_signed, tag, platform, hardware, expires_at)262 values (${id}, ${s.accountId}, ${s.tokenHash}, ${b.deviceId}, ${b.encPub}, ${b.sigPub}, ${b.createdAt}, ${b.tag}, ${b.platform}, ${b.hardware}, now() + interval '5 minutes')`;263 publish([s.accountId], { type: "pairing", pairingId: id });264 return { pairingId: id, expiresInSec: 300 };265 });266267 app.get("/api/v1/pairings/:id", async (req) => {268 const s = await need(req, "pending", "device");269 const [p] = await sql`select * from pairings where id = ${parse(uuid, (req.params as any).id)} and account_id = ${s.accountId} and expires_at > now()`;270 if (!p) throw notFound();271 if (s.kind === "pending") {272 if (p.session_hash !== s.tokenHash) throw notFound();273 return { status: p.status, ...(p.status === "approved" ? { cert: p.cert, arkEnvelope: p.ark_envelope, account: await accountView(sql, s.accountId) } : {}) };274 }275 return { status: p.status, deviceId: p.device_id, encPub: p.enc_pub, sigPub: p.sig_pub, createdAt: p.created_at_signed, tag: p.tag, platform: p.platform, hardware: p.hardware };276 });277278 app.post("/api/v1/pairings/:id/approve", async (req) => {279 const s = await needStrong(req);280 const b = parse(z.object({ cert: sig, arkEnvelope }).strict(), req.body);281 const id = parse(uuid, (req.params as any).id);282 await sql.begin(async (tx) => {283 const [p] = await tx`select * from pairings where id = ${id} and account_id = ${s.accountId} and status = 'pending' and expires_at > now() for update`;284 if (!p) throw notFound();285 const [a] = await tx`select sig_pub from accounts where id = ${s.accountId}`;286 await checkCert(a.sig_pub, s.accountId, { deviceId: p.device_id, encPub: p.enc_pub, sigPub: p.sig_pub, createdAt: p.created_at_signed, cert: b.cert });287 await tx`update pairings set status = 'approved', cert = ${b.cert}, ark_envelope = ${b.arkEnvelope}, approved_by = ${s.deviceId} where id = ${id}`;288 });289 publish([s.accountId], { type: "pairing", pairingId: id });290 return { ok: true };291 });292293 app.post("/api/v1/pairings/:id/reject", async (req) => {294 const s = await need(req, "device");295 await sql`update pairings set status = 'rejected' where id = ${parse(uuid, (req.params as any).id)} and account_id = ${s.accountId} and status = 'pending'`;296 return { ok: true };297 });298299 /** The new device proves possession of its signing key; its pending session is replaced by a device session. */300 app.post("/api/v1/pairings/:id/complete", async (req, reply) => {301 const s = await need(req, "pending");302 const b = parse(z.object({ proof: sig }).strict(), req.body);303 const id = parse(uuid, (req.params as any).id);304 const token = await sql.begin(async (tx) => {305 const [p] = await tx`select * from pairings where id = ${id} and account_id = ${s.accountId} and session_hash = ${s.tokenHash} and status = 'approved' and expires_at > now() for update`;306 if (!p) throw notFound();307 if (!(await ecdsaVerify(unb64u(p.sig_pub), ctx("pair-complete", id), unb64u(b.proof)))) throw new HttpError(401, "authentication_failed");308 await insertDevice(tx, s.accountId, { deviceId: p.device_id, encPub: p.enc_pub, sigPub: p.sig_pub, createdAt: p.created_at_signed, cert: p.cert, arkEnvelope: p.ark_envelope, platform: p.platform, hardware: p.hardware });309 await tx`update pairings set status = 'completed', ark_envelope = null where id = ${id}`;310 await tx`delete from sessions where token_hash = ${s.tokenHash}`;311 await audit(tx, s.accountId, "device.enrolled", { device: p.device_id, platform: p.platform, via: "pairing", approvedBy: p.approved_by }, p.device_id);312 return createSession(tx, s.accountId, "device", p.device_id, true);313 });314 publish([s.accountId], { type: "devices" });315 return sessionReply(req, reply, token, { ok: true });316 });317318 // ── recovery (SPV1 §2, §5) ───────────────────────────────────────────────────────────────────────────────319 app.post("/api/v1/recovery/start", async (req) => {320 rateLimit(`recover:${clientIp(req)}`, 10, 900);321 const b = parse(z.object({ handle }).strict(), req.body);322 const [a] = await sql`select id, recovery_epoch from accounts where handle = ${b.handle}`;323 if (a) return { accountId: a.id, epoch: a.recovery_epoch };324 // unknown handle: stable decoy so handles cannot be enumerated325 const h = crypto.createHmac("sha256", decoyKey).update(b.handle).digest("hex");326 return { accountId: `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-8${h.slice(17, 20)}-${h.slice(20, 32)}`, epoch: 1 };327 });328329 app.post("/api/v1/recovery/verify", async (req, reply) => {330 rateLimit(`recover:${clientIp(req)}`, 10, 900);331 const b = parse(z.object({ accountId: uuid, auth: hash }).strict(), req.body);332 rateLimit(`recover-acct:${b.accountId}`, 10, 3600);333 const [a] = await sql`select id, recovery_auth_hash, recovery_envelope, recovery_epoch from accounts where id = ${b.accountId}`;334 const ok = safeEqual(sha256b64u(Buffer.from(b.auth, "base64url")), a?.recovery_auth_hash ?? "x".repeat(43));335 if (!a || !ok) throw new HttpError(401, "authentication_failed", "The recovery key does not match");336 const token = await sql.begin(async (tx) => {337 await audit(tx, a.id, "recovery.started", {}, null);338 return createSession(tx, a.id, "recovery", null, false);339 });340 return sessionReply(req, reply, token, { envelope: a.recovery_envelope, epoch: a.recovery_epoch, account: await accountView(sql, a.id) });341 });342343 app.post("/api/v1/recovery/enroll", async (req, reply) => {344 const s = await need(req, "recovery");345 const b = parse(z.object({ device: deviceNew }).strict(), req.body);346 const token = await sql.begin(async (tx) => {347 const [a] = await tx`select sig_pub from accounts where id = ${s.accountId}`;348 await checkCert(a.sig_pub, s.accountId, b.device);349 await insertDevice(tx, s.accountId, b.device);350 await tx`delete from sessions where token_hash = ${s.tokenHash}`;351 await audit(tx, s.accountId, "device.enrolled", { device: b.device.deviceId, platform: b.device.platform, via: "recovery-key" }, b.device.deviceId);352 return createSession(tx, s.accountId, "device", b.device.deviceId, true);353 });354 publish([s.accountId], { type: "devices" });355 return sessionReply(req, reply, token, { ok: true });356 });357358 app.get("/api/v1/recovery", async (req) => {359 const s = await needStrong(req);360 const [a] = await sql`select recovery_epoch, recovery_envelope from accounts where id = ${s.accountId}`;361 return { epoch: a.recovery_epoch, envelope: a.recovery_envelope };362 });363364 app.post("/api/v1/recovery/rotate", async (req) => {365 const s = await needStrong(req);366 const b = parse(recovery, req.body);367 await sql.begin(async (tx) => {368 const r = await tx`update accounts set recovery_epoch = ${b.epoch}, recovery_envelope = ${b.envelope}, recovery_auth_hash = ${b.authHash} where id = ${s.accountId} and recovery_epoch = ${b.epoch - 1} returning 1`;369 if (!r.length) throw new HttpError(409, "conflict", "Recovery epoch mismatch");370 await audit(tx, s.accountId, "recovery.rotated", { epoch: b.epoch }, s.deviceId);371 });372 return { ok: true };373 });374375 // ── account rekey (new ARK): keyset, every device envelope and the recovery material change atomically ─────376 app.post("/api/v1/account/rekey", async (req) => {377 const s = await needStrong(req);378 const b = parse(z.object({ keyEpoch: z.number().int().min(2), keyset, recovery, devices: z.array(z.object({ deviceId: uuid, arkEnvelope }).strict()).min(1).max(100) }).strict(), req.body);379 await sql.begin(async (tx) => {380 const [a] = await tx`select key_epoch, recovery_epoch from accounts where id = ${s.accountId} for update`;381 if (a.key_epoch !== b.keyEpoch - 1 || a.recovery_epoch !== b.recovery.epoch - 1) throw new HttpError(409, "conflict", "Account key epoch mismatch");382 const active = await tx`select id from devices where account_id = ${s.accountId} and revoked_at is null`;383 const given = new Set(b.devices.map((d) => d.deviceId));384 if (active.length !== given.size || active.some((d) => !given.has(d.id))) throw new HttpError(409, "conflict", "The device list changed; retry");385 for (const d of b.devices) await tx`update devices set ark_envelope = ${d.arkEnvelope} where id = ${d.deviceId} and account_id = ${s.accountId}`;386 await tx`update accounts set key_epoch = ${b.keyEpoch}, keyset = ${tx.json(b.keyset)}, recovery_epoch = ${b.recovery.epoch}, recovery_envelope = ${b.recovery.envelope}, recovery_auth_hash = ${b.recovery.authHash} where id = ${s.accountId}`;387 await tx`delete from sessions where account_id = ${s.accountId} and token_hash <> ${s.tokenHash}`;388 await audit(tx, s.accountId, "account.rekeyed", { keyEpoch: b.keyEpoch }, s.deviceId);389 });390 publish([s.accountId], { type: "devices" });391 return { ok: true };392 });393394 app.get("/api/v1/accounts/lookup", async (req) => {395 const s = await need(req, "device");396 rateLimit(`lookup:${s.accountId}`, 30, 300);397 const h = parse(handle, (req.query as any).handle);398 const [a] = await sql`select id, handle, sig_pub, enc_pub from accounts where handle = ${h}`;399 if (!a) throw notFound();400 return { accountId: a.id, handle: a.handle, sigPub: a.sig_pub, encPub: a.enc_pub };401 });402}403404const decoyKey = crypto.randomBytes(32);405406async function insertDevice(tx: Sql, accountId: string, d: z.infer<typeof deviceNew>) {407 if ((await tx`select 1 from devices where id = ${d.deviceId}`).length) throw new HttpError(409, "device_exists");408 await tx`insert into devices (id, account_id, enc_pub, sig_pub, created_at_signed, cert, ark_envelope, platform, hardware, last_seen_at)409 values (${d.deviceId}, ${accountId}, ${d.encPub}, ${d.sigPub}, ${d.createdAt}, ${d.cert}, ${d.arkEnvelope}, ${d.platform}, ${d.hardware}, now())`;410}411412export async function createVault(tx: Sql, accountId: string, deviceId: string | null, v: { vaultId: string; grant: z.infer<typeof grant>; meta: { recordId: string; envelope: z.infer<typeof envelope> } }) {413 if ((await tx`select 1 from vaults where id = ${v.vaultId}`).length) throw new HttpError(409, "vault_exists");414 await tx`insert into vaults (id, owner_id, epoch, seq) values (${v.vaultId}, ${accountId}, 1, 1)`;415 await tx`insert into vault_members (vault_id, account_id, role) values (${v.vaultId}, ${accountId}, 'owner')`;416 await tx`insert into vault_grants (vault_id, epoch, member_id, role, envelope, granter_id, sig) values (${v.vaultId}, 1, ${accountId}, 'owner', ${v.grant.envelope}, ${accountId}, ${v.grant.sig})`;417 await tx`insert into records (vault_id, id, type, rev, envelope, seq, device_id) values (${v.vaultId}, ${v.meta.recordId}, 'vault-meta', 1, ${tx.json(v.meta.envelope)}, 1, ${deviceId})`;418}419420export type { Session };421