Repository Public
1import { z } from "zod";2import { sql } from "../db";3import { ApiError, body, clientIp } from "../http";4import { revokeSession, type UserContext } from "../auth";5import { audit } from "../audit";6import { ACCENTS, uuid } from "./schemas";7import type { RouteDef } from "./router";89/** The signed-in account's own security and preferences. Every query is scoped to ctx.userId. */10export const meRoutes: RouteDef<UserContext>[] = [11 ["PATCH", "preferences", async ({ req, ctx }) => {12 const b = await body(req, z.object({ locale: z.enum(["fr", "en"]).optional(), accent: z.enum(ACCENTS).optional(), displayName: z.string().trim().min(1).max(80).optional() }).strict());13 if (b.locale) await sql`UPDATE users SET locale = ${b.locale} WHERE id = ${ctx.userId}`;14 if (b.accent) await sql`UPDATE users SET accent = ${b.accent} WHERE id = ${ctx.userId}`;15 if (b.displayName) await sql`UPDATE users SET display_name = ${b.displayName} WHERE id = ${ctx.userId}`;16 return { ok: true };17 }],18 ["GET", "passkeys", async ({ ctx }) => ({19 items: await sql`SELECT id, name, device_type AS "deviceType", backed_up AS "backedUp", created_at AS "createdAt", last_used_at AS "lastUsedAt" FROM authenticators WHERE user_id = ${ctx.userId} ORDER BY created_at`,20 })],21 ["PATCH", "passkeys/:id", async ({ req, params, ctx }) => {22 const b = await body(req, z.object({ name: z.string().trim().min(1).max(60) }).strict());23 const r = await sql`UPDATE authenticators SET name = ${b.name} WHERE id = ${uuid.parse(params.id)} AND user_id = ${ctx.userId} RETURNING id`;24 if (r.length === 0) throw new ApiError(404, "not_found");25 return { ok: true };26 }],27 ["DELETE", "passkeys/:id", async ({ req, params, ctx }) => {28 const id = uuid.parse(params.id);29 // The last passkey cannot be removed from here: the account would only be reachable through recovery.30 const removed = await sql.begin(async (tx) => {31 const all = await tx<{ id: string }[]>`SELECT id FROM authenticators WHERE user_id = ${ctx.userId} FOR UPDATE`;32 if (!all.some((a) => a.id === id)) throw new ApiError(404, "not_found");33 if (all.length <= 1) throw new ApiError(409, "last_passkey", "Add another passkey before removing the last one");34 return tx`DELETE FROM authenticators WHERE id = ${id} AND user_id = ${ctx.userId} RETURNING id`;35 });36 await audit({ userId: ctx.userId, actor: ctx.role, action: "passkey.revoked", entity: "passkey", entityId: id, ip: clientIp(req) });37 return { ok: removed.length > 0 };38 }],39 ["GET", "sessions", async ({ ctx }) => ({40 items: (await sql<{ id: string }[]>`SELECT id, method, user_agent AS "userAgent", ip, created_at AS "createdAt", last_seen_at AS "lastSeenAt", expires_at AS "expiresAt"41 FROM sessions WHERE user_id = ${ctx.userId} AND revoked_at IS NULL AND expires_at > now() ORDER BY last_seen_at DESC`).map((s) => ({ ...s, current: s.id === ctx.sessionId })),42 })],43 ["DELETE", "sessions/:id", async ({ req, params, ctx }) => {44 const ok = await revokeSession(uuid.parse(params.id), ctx.userId);45 if (!ok) throw new ApiError(404, "not_found");46 await audit({ userId: ctx.userId, actor: ctx.role, action: "session.revoked", ip: clientIp(req) });47 return { ok: true };48 }],49 ["POST", "sessions/revoke-others", async ({ req, ctx }) => {50 const r = await sql`UPDATE sessions SET revoked_at = now() WHERE user_id = ${ctx.userId} AND id <> ${ctx.sessionId} AND revoked_at IS NULL RETURNING id`;51 await audit({ userId: ctx.userId, actor: ctx.role, action: "session.revoked_others", meta: { count: r.length }, ip: clientIp(req) });52 return { revoked: r.length };53 }],54 ["GET", "recovery-codes", async ({ ctx }) => {55 const [r] = await sql<{ n: number }[]>`SELECT count(*)::int AS n FROM recovery_codes WHERE user_id = ${ctx.userId} AND used_at IS NULL`;56 return { remaining: r.n };57 }],58];59