SPB Git

Repository Public

auth.ts 15.7 KB 255 lines typescript

1import type { FastifyInstance } from "fastify"2import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse } from "@simplewebauthn/server"3import { z } from "zod"4import { config } from "./config.js"5import { sql } from "./db.js"6import { clearSessionCookie, createSession, requireUser, type ClientInfo } from "./session.js"7import { audit, bad, limitReq, parse, sha256, uuidBytes, zUuid } from "./util.js"89const zHandle = z.string().trim().toLowerCase().regex(/^[a-z0-9_.-]{2,32}$/)10const zName = z.string().trim().min(1).max(64)11const zToken = z.string().min(20).max(120)12const zClient = z.object({ kind: z.enum(["web", "native"]), deviceName: z.string().max(80).optional(), platform: z.string().max(40).optional() }).optional()13const clientOf = (c: z.infer<typeof zClient>): ClientInfo => c ?? { kind: "web" }1415async function newChallenge(kind: string, challenge: string, userId: string | null, data: Record<string, unknown>) {16  const [row] = await sql`insert into challenges (kind, challenge, user_id, data, expires_at)17    values (${kind}, ${challenge}, ${userId}, ${sql.json(data as never)}, now() + interval '5 minutes') returning id`18  return row.id as string19}20/** Un défi ne sert qu'une fois : la ligne est supprimée à la lecture. */21async function takeChallenge(id: string, kind: string) {22  const [row] = await sql`delete from challenges where id = ${id} and kind = ${kind} and expires_at > now() returning *`23  if (!row) throw bad("challenge_expired", 400)24  return row25}26async function checkToken(token: string) {27  const [t] = await sql`select purpose, user_id from enrollment_tokens where token_hash = ${sha256(token)} and used_at is null and expires_at > now()`28  if (!t) throw bad("invalid_token", 403)29  return t as { purpose: "bootstrap" | "recover" | "invite"; user_id: string | null }30}3132export function authRoutes(app: FastifyInstance) {33  app.get("/api/me", async (req) => {34    const a = await requireUser(req)35    const [u] = await sql`select id, handle, display_name, role, prefs from users where id = ${a.userId}`36    // Boîtes possédées, puis boîtes partagées avec cet utilisateur (mailbox_grants) : `access` distingue les deux.37    const mailboxes = await sql`select m.id, m.address, m.display_name, m.position,38        case when m.user_id = ${a.userId} then 'owner' else 'shared' end as access, (m.user_id = ${a.userId} or coalesce(g.can_send, false)) as can_send39      from mailboxes m left join mailbox_grants g on g.mailbox_id = m.id and g.user_id = ${a.userId}40      where m.user_id = ${a.userId} or g.can_read order by (m.user_id = ${a.userId}) desc, m.position, m.created_at`41    return { user: u, session: { id: a.sessionId, kind: a.kind }, mailboxes, version: config.version }42  })4344  app.put("/api/prefs", async (req) => {45    const a = await requireUser(req)46    const prefs = parse(z.record(z.string().max(40), z.unknown()), req.body)47    if (JSON.stringify(prefs).length > 20_000) throw bad("prefs_too_large", 413)48    await sql`update users set prefs = ${sql.json(prefs as never)} where id = ${a.userId}`49    return { ok: true }50  })5152  // Fusion superficielle : un client qui ignore une clé de préférences ne l'efface pas (null retire une clé).53  app.patch("/api/prefs", async (req) => {54    const a = await requireUser(req)55    const patch = parse(z.record(z.string().max(40), z.unknown()), req.body)56    const [u] = await sql`select prefs from users where id = ${a.userId}`57    const next: Record<string, unknown> = { ...(u.prefs as Record<string, unknown>) }58    for (const [k, v] of Object.entries(patch)) if (v === null) delete next[k]; else next[k] = v59    if (JSON.stringify(next).length > 20_000) throw bad("prefs_too_large", 413)60    await sql`update users set prefs = ${sql.json(next as never)} where id = ${a.userId}`61    return { ok: true, prefs: next }62  })6364  app.put("/api/profile", async (req) => {65    const a = await requireUser(req)66    const { display_name } = parse(z.object({ display_name: zName }), req.body)67    await sql`update users set display_name = ${display_name} where id = ${a.userId}`68    return { ok: true }69  })7071  // ---- enrôlement par lien à usage unique (premier administrateur, récupération, invitation)72  app.post("/api/enroll/check", async (req) => {73    limitReq(req, "enroll", 20)74    const { token } = parse(z.object({ token: zToken }), req.body)75    const t = await checkToken(token)76    const [u] = t.user_id ? await sql`select handle, display_name from users where id = ${t.user_id}` : [null]77    return { purpose: t.purpose, user: u ?? null }78  })7980  app.post("/api/enroll/options", async (req) => {81    limitReq(req, "enroll", 10)82    const body = parse(z.object({ token: zToken, handle: zHandle.optional(), display_name: zName.optional() }), req.body)83    const t = await checkToken(body.token)84    let userId = t.user_id85    let handle = body.handle86    let displayName = body.display_name87    if (userId) {88      const [u] = await sql`select handle, display_name from users where id = ${userId}`89      handle = u.handle90      displayName = u.display_name91    } else {92      if (!handle || !displayName) throw bad("invalid_request", 400, "handle and display_name are required")93      const [taken] = await sql`select 1 from users where handle = ${handle}`94      if (taken) throw bad("handle_taken", 409)95      userId = crypto.randomUUID()96    }97    const existing = await sql`select id, transports from passkeys where user_id = ${userId}`98    const options = await generateRegistrationOptions({99      rpName: config.rpName, rpID: config.rpId, userName: handle!, userDisplayName: displayName!,100      userID: new Uint8Array(uuidBytes(userId!)), attestationType: "none",101      excludeCredentials: existing.map((e) => ({ id: e.id, transports: e.transports })),102      authenticatorSelection: { residentKey: "required", userVerification: "required" },103    })104    const id = await newChallenge("enroll", options.challenge, null, { token: body.token, userId, handle, displayName, existing: !!t.user_id })105    return { challenge_id: id, options }106  })107108  app.post("/api/enroll/verify", async (req, reply) => {109    limitReq(req, "enroll", 10)110    const body = parse(z.object({ challenge_id: zUuid, response: z.any(), label: z.string().max(60).optional(), client: zClient }), req.body)111    const ch = await takeChallenge(body.challenge_id, "enroll")112    const d = ch.data as { token: string; userId: string; handle: string; displayName: string; existing: boolean }113    const v = await verifyRegistrationResponse({114      response: body.response, expectedChallenge: ch.challenge, expectedOrigin: config.origin, expectedRPID: config.rpId, requireUserVerification: true,115    }).catch(() => null)116    if (!v?.verified) throw bad("passkey_verification_failed", 400)117    const cred = v.registrationInfo.credential118    await sql.begin(async (tx) => {119      // Le lien est consommé dans la transaction qui crée le compte ou la clé.120      const [t] = await tx`update enrollment_tokens set used_at = now() where token_hash = ${sha256(d.token)} and used_at is null and expires_at > now() returning purpose`121      if (!t) throw bad("invalid_token", 403)122      if (!d.existing)123        await tx`insert into users (id, handle, display_name, role) values (${d.userId}, ${d.handle}, ${d.displayName}, ${t.purpose === "bootstrap" ? "admin" : "member"})`124      await tx`insert into passkeys (id, user_id, public_key, counter, transports, device_type, backed_up, label)125               values (${cred.id}, ${d.userId}, ${Buffer.from(cred.publicKey)}, ${cred.counter}, ${cred.transports ?? []},126                       ${v.registrationInfo.credentialDeviceType}, ${v.registrationInfo.credentialBackedUp}, ${body.label ?? "Passkey"})`127    })128    const s = await createSession(req, reply, d.userId, cred.id, clientOf(body.client))129    await audit(req, d.userId, "enroll", d.userId, { handle: d.handle })130    return { ok: true, token: s.token }131  })132133  // ---- connexion (identifiant découvrable : aucun nom d'utilisateur demandé)134  app.post("/api/login/options", async (req) => {135    limitReq(req, "login", 30)136    const options = await generateAuthenticationOptions({ rpID: config.rpId, userVerification: "required" })137    return { challenge_id: await newChallenge("login", options.challenge, null, {}), options }138  })139140  app.post("/api/login/verify", async (req, reply) => {141    limitReq(req, "login", 30)142    const body = parse(z.object({ challenge_id: zUuid, response: z.any(), client: zClient }), req.body)143    const ch = await takeChallenge(body.challenge_id, "login")144    const [pk] = await sql`select p.*, u.status from passkeys p join users u on u.id = p.user_id where p.id = ${String(body.response?.id ?? "")}`145    if (!pk) throw bad("unknown_passkey", 401)146    const v = await verifyAuthenticationResponse({147      response: body.response, expectedChallenge: ch.challenge, expectedOrigin: config.origin, expectedRPID: config.rpId, requireUserVerification: true,148      credential: { id: pk.id, publicKey: new Uint8Array(pk.public_key), counter: Number(pk.counter), transports: pk.transports },149    }).catch(() => null)150    if (!v?.verified) {151      await audit(req, pk.user_id, "login.failed", pk.user_id)152      throw bad("passkey_verification_failed", 401)153    }154    if (pk.status !== "active") throw bad("account_disabled", 403)155    await sql`update passkeys set counter = ${v.authenticationInfo.newCounter}, last_used_at = now(), backed_up = ${v.authenticationInfo.credentialBackedUp} where id = ${pk.id}`156    const s = await createSession(req, reply, pk.user_id, pk.id, clientOf(body.client))157    await audit(req, pk.user_id, "login", pk.user_id, { kind: body.client?.kind ?? "web" })158    return { ok: true, token: s.token }159  })160161  app.post("/api/logout", async (req, reply) => {162    const a = await requireUser(req)163    await sql`update sessions set revoked_at = now() where id = ${a.sessionId}`164    await sql`delete from push_devices where session_id = ${a.sessionId}` // un appareil déconnecté ne reçoit plus de notification165    clearSessionCookie(reply)166    return { ok: true }167  })168169  // ---- clés d'accès170  app.get("/api/passkeys", async (req) => {171    const a = await requireUser(req)172    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`173  })174  app.post("/api/passkeys/options", async (req) => {175    const a = await requireUser(req)176    const [u] = await sql`select handle, display_name from users where id = ${a.userId}`177    const existing = await sql`select id, transports from passkeys where user_id = ${a.userId}`178    const options = await generateRegistrationOptions({179      rpName: config.rpName, rpID: config.rpId, userName: u.handle, userDisplayName: u.display_name,180      userID: new Uint8Array(uuidBytes(a.userId)), attestationType: "none",181      excludeCredentials: existing.map((e) => ({ id: e.id, transports: e.transports })),182      authenticatorSelection: { residentKey: "required", userVerification: "required" },183    })184    return { challenge_id: await newChallenge("add-passkey", options.challenge, a.userId, {}), options }185  })186  app.post("/api/passkeys/verify", async (req) => {187    const a = await requireUser(req)188    const body = parse(z.object({ challenge_id: zUuid, response: z.any(), label: z.string().trim().min(1).max(60) }), req.body)189    const ch = await takeChallenge(body.challenge_id, "add-passkey")190    if (ch.user_id !== a.userId) throw bad("forbidden", 403)191    const v = await verifyRegistrationResponse({192      response: body.response, expectedChallenge: ch.challenge, expectedOrigin: config.origin, expectedRPID: config.rpId, requireUserVerification: true,193    }).catch(() => null)194    if (!v?.verified) throw bad("passkey_verification_failed", 400)195    const cred = v.registrationInfo.credential196    await sql`insert into passkeys (id, user_id, public_key, counter, transports, device_type, backed_up, label)197              values (${cred.id}, ${a.userId}, ${Buffer.from(cred.publicKey)}, ${cred.counter}, ${cred.transports ?? []},198                      ${v.registrationInfo.credentialDeviceType}, ${v.registrationInfo.credentialBackedUp}, ${body.label})`199    await audit(req, a.userId, "passkey.add", cred.id)200    return { ok: true }201  })202  app.delete("/api/passkeys/:id", async (req) => {203    const a = await requireUser(req)204    const { id } = req.params as { id: string }205    const [{ n }] = await sql`select count(*)::int as n from passkeys where user_id = ${a.userId}`206    if (n <= 1) throw bad("last_passkey", 409, "The last passkey cannot be removed")207    const r = await sql`delete from passkeys where id = ${id} and user_id = ${a.userId} returning 1`208    if (!r.length) throw bad("not_found", 404)209    const gone = await sql`update sessions set revoked_at = now() where passkey_id = ${id} and id <> ${a.sessionId} and revoked_at is null returning id`210    if (gone.length) await sql`delete from push_devices where session_id = any(${gone.map((g) => g.id)}::uuid[])`211    await audit(req, a.userId, "passkey.remove", id)212    return { ok: true }213  })214215  // ---- sessions (appareils)216  app.get("/api/sessions", async (req) => {217    const a = await requireUser(req)218    const rows = await sql`219      select id, kind, device_name, platform, ip, user_agent, created_at, last_seen_at from sessions220      where user_id = ${a.userId} and revoked_at is null and expires_at > now()221        and last_seen_at > now() - make_interval(days => ${config.sessionIdleDays})222      order by last_seen_at desc`223    return rows.map((r) => ({ ...r, current: r.id === a.sessionId }))224  })225  app.delete("/api/sessions/:id", async (req) => {226    const a = await requireUser(req)227    const { id } = parse(z.object({ id: zUuid }), req.params)228    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`229    if (!r.length) throw bad("not_found", 404)230    await sql`delete from push_devices where session_id = ${id}`231    await audit(req, a.userId, "session.revoke", id)232    return { ok: true }233  })234235  // ---- notifications push (apps natives) : seul le jeton APNs est conservé. Un nouvel enregistrement du même jeton met la236  // ligne à jour et la réactive ; s'il change d'utilisateur, ses réglages et ses notifications en attente ne suivent pas.237  app.post("/api/push/register", async (req) => {238    const a = await requireUser(req)239    if (a.kind !== "native") throw bad("native_only", 400)240    const b = parse(z.object({241      apns_token: z.string().regex(/^[0-9a-f]{64,200}$/), environment: z.enum(["production", "sandbox"]), bundle_id: z.string().max(120),242      device_name: z.string().trim().max(80).optional(), locale: z.string().trim().max(35).optional(), app_version: z.string().trim().max(40).optional(),243    }), req.body)244    const [d] = await sql`insert into push_devices as d (session_id, user_id, apns_token, environment, bundle_id, device_name, locale, app_version)245              values (${a.sessionId}, ${a.userId}, ${b.apns_token}, ${b.environment}, ${b.bundle_id}, ${b.device_name ?? null}, ${b.locale ?? null}, ${b.app_version ?? null})246              on conflict (apns_token, bundle_id) do update set session_id = excluded.session_id, user_id = excluded.user_id, environment = excluded.environment,247                device_name = coalesce(excluded.device_name, d.device_name), locale = coalesce(excluded.locale, d.locale), app_version = coalesce(excluded.app_version, d.app_version),248                prefs = case when d.user_id = excluded.user_id then d.prefs else '{}'::jsonb end, last_badge = case when d.user_id = excluded.user_id then d.last_badge else null end,249                enabled = true, last_registered_at = now(), last_error = null, failure_count = 0250              returning id`251    await sql`delete from push_outbox where device_id = ${d.id} and user_id <> ${a.userId}`252    return { ok: true, device_id: d.id as string }253  })254}255
Files main
Menu

Theme