Repository Public
1import type { FastifyReply, FastifyRequest } from "fastify"2import crypto from "node:crypto"3import { config, cookieName } from "./config.js"4import { sql } from "./db.js"5import { bad, sha256 } from "./util.js"67export type Auth = { sessionId: string; userId: string; role: "admin" | "member"; kind: "web" | "native" }89export type ClientInfo = { kind: "web" | "native"; deviceName?: string; platform?: string }1011/** Crée une session propre à l'appareil. Web : cookie HttpOnly. Natif : jeton rendu une seule fois, à ranger au trousseau. */12export async function createSession(req: FastifyRequest, reply: FastifyReply, userId: string, passkeyId: string | null, client: ClientInfo) {13 const token = crypto.randomBytes(32).toString("base64url")14 const expires = new Date(Date.now() + config.sessionMaxDays * 86400_000)15 const [row] = await sql`16 insert into sessions (token_hash, user_id, kind, device_name, platform, passkey_id, ip, user_agent, expires_at)17 values (${sha256(token)}, ${userId}, ${client.kind}, ${client.deviceName?.slice(0, 80) ?? null}, ${client.platform?.slice(0, 40) ?? null},18 ${passkeyId}, ${req.ip}, ${String(req.headers["user-agent"] ?? "").slice(0, 300)}, ${expires})19 returning id`20 if (client.kind === "web") {21 reply.setCookie(cookieName, token, { path: "/", httpOnly: true, secure: config.secureCookies, sameSite: "strict", expires })22 return { sessionId: row.id as string, token: undefined }23 }24 return { sessionId: row.id as string, token }25}2627export function clearSessionCookie(reply: FastifyReply) {28 reply.clearCookie(cookieName, { path: "/", httpOnly: true, secure: config.secureCookies, sameSite: "strict" })29}3031export function bearerOf(req: FastifyRequest): string | undefined {32 const h = req.headers.authorization33 return h?.startsWith("Bearer ") ? h.slice(7).trim() : undefined34}3536async function authFromToken(token: string | undefined, kind: "web" | "native"): Promise<Auth | null> {37 if (!token || token.length > 200) return null38 const [row] = await sql`39 select s.id, s.user_id, s.kind, s.last_seen_at, u.role, u.status40 from sessions s join users u on u.id = s.user_id41 where s.token_hash = ${sha256(token)} and s.kind = ${kind} and s.revoked_at is null and s.expires_at > now()42 and s.last_seen_at > now() - make_interval(days => ${config.sessionIdleDays})`43 if (!row || row.status !== "active") return null44 if (Date.now() - new Date(row.last_seen_at).getTime() > 60_000) await sql`update sessions set last_seen_at = now() where id = ${row.id}`45 return { sessionId: row.id, userId: row.user_id, role: row.role, kind: row.kind }46}4748declare module "fastify" {49 interface FastifyRequest {50 auth?: Auth51 }52}5354export async function requireUser(req: FastifyRequest): Promise<Auth> {55 if (req.auth) return req.auth56 const bearer = bearerOf(req)57 const a = bearer ? await authFromToken(bearer, "native") : await authFromToken(req.cookies[cookieName], "web")58 if (!a) throw bad("unauthenticated", 401)59 req.auth = a60 return a61}62export async function requireAdmin(req: FastifyRequest): Promise<Auth> {63 const a = await requireUser(req)64 if (a.role !== "admin") throw bad("forbidden", 403)65 return a66}67