Repository Public
1// Réauthentification par clé d'accès : les opérations sensibles d'une session exigent une assertion WebAuthn de moins de 5 minutes.2import type { FastifyInstance, FastifyRequest } from "fastify"3import { generateAuthenticationOptions, verifyAuthenticationResponse } from "@simplewebauthn/server"4import { z } from "zod"5import { config } from "./config.js"6import { sql } from "./db.js"7import { requireUser, type Auth } from "./session.js"8import { audit, bad, limitReq, parse, zUuid } from "./util.js"910export const REAUTH_WINDOW_MS = 5 * 60_0001112/** 403 `reauth_required` si la session n'a pas été réauthentifiée dans les 5 dernières minutes. */13export async function requireReauth(a: Auth): Promise<void> {14 const [s] = await sql`select reauth_at from sessions where id = ${a.sessionId}`15 if (!s?.reauth_at || Date.now() - new Date(s.reauth_at).getTime() > REAUTH_WINDOW_MS)16 throw bad("reauth_required", 403, "This operation requires a passkey re-authentication within the last 5 minutes (POST /api/reauth/options, then /api/reauth/verify)")17}18export async function requireAdminReauth(req: FastifyRequest): Promise<Auth> {19 const a = await requireUser(req)20 if (a.role !== "admin") throw bad("forbidden", 403)21 await requireReauth(a)22 return a23}2425export function reauthRoutes(app: FastifyInstance) {26 app.post("/api/reauth/options", async (req) => {27 const a = await requireUser(req)28 limitReq(req, "reauth", 30)29 const keys = await sql`select id, transports from passkeys where user_id = ${a.userId}`30 const options = await generateAuthenticationOptions({ rpID: config.rpId, userVerification: "required", allowCredentials: keys.map((k) => ({ id: k.id, transports: k.transports })) })31 const [row] = await sql`insert into challenges (kind, challenge, user_id, data, expires_at)32 values ('reauth', ${options.challenge}, ${a.userId}, ${sql.json({ session: a.sessionId })}, now() + interval '5 minutes') returning id`33 return { challenge_id: row.id, options }34 })3536 app.post("/api/reauth/verify", async (req) => {37 const a = await requireUser(req)38 limitReq(req, "reauth", 30)39 const body = parse(z.object({ challenge_id: zUuid, response: z.any() }), req.body)40 const [ch] = await sql`delete from challenges where id = ${body.challenge_id} and kind = 'reauth' and expires_at > now() returning *`41 if (!ch) throw bad("challenge_expired", 400)42 // Le défi est lié à la session ET à l'utilisateur courants ; la clé doit appartenir à cet utilisateur.43 if (ch.user_id !== a.userId || (ch.data as { session?: string }).session !== a.sessionId) throw bad("forbidden", 403)44 const [pk] = await sql`select * from passkeys where id = ${String(body.response?.id ?? "")} and user_id = ${a.userId}`45 if (!pk) throw bad("unknown_passkey", 401)46 const v = await verifyAuthenticationResponse({47 response: body.response, expectedChallenge: ch.challenge, expectedOrigin: config.origin, expectedRPID: config.rpId, requireUserVerification: true,48 credential: { id: pk.id, publicKey: new Uint8Array(pk.public_key), counter: Number(pk.counter), transports: pk.transports },49 }).catch(() => null)50 if (!v?.verified) {51 await audit(req, a.userId, "reauth.failed", a.sessionId)52 throw bad("passkey_verification_failed", 401)53 }54 await sql`update passkeys set counter = ${v.authenticationInfo.newCounter}, last_used_at = now() where id = ${pk.id}`55 const [s] = await sql`update sessions set reauth_at = now() where id = ${a.sessionId} returning reauth_at`56 await audit(req, a.userId, "reauth", a.sessionId)57 return { ok: true, reauth_at: s.reauth_at, valid_until: new Date(new Date(s.reauth_at).getTime() + REAUTH_WINDOW_MS).toISOString() }58 })59}60