SPB Git

Repository Public

admin.ts 11.5 KB 192 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr SMS Gateway8 * File             : backend/src/auth/admin.ts9 * Module           : auth10 * Repository       : https://git.spboucher.ai/maclustr-sms11 * Project Website  : https://sms.spboucher.ai12 * Created          : 2026-11-3013 * Last Modified    : 2026-11-3014 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"43import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse } from "@simplewebauthn/server"44import { z } from "zod"45import { config } from "../config.ts"46import { audit, sql } from "../db.ts"47import { enforce } from "../security/ratelimit.ts"48import { ApiError, bad, iso, newId, randomToken, sha256hex } from "../util.ts"4950export const COOKIE = "mlsms_session"51const SESSION_DAYS = 14, IDLE_HOURS = 7252export interface Admin { userId: string; sessionId: string; handle: string }53declare module "fastify" { interface FastifyRequest { admin?: Admin } }5455async function createSession(req: FastifyRequest, reply: FastifyReply, userId: string) {56  const token = randomToken(32), expires = new Date(Date.now() + SESSION_DAYS * 86400_000)57  await sql`insert into admin_sessions(id, user_id, expires_at, ip, user_agent) values (${sha256hex(token)}, ${userId}, ${expires}, ${req.ip}, ${String(req.headers["user-agent"] ?? "").slice(0, 300)})`58  reply.setCookie(COOKIE, token, { path: "/", httpOnly: true, secure: config.secure, sameSite: "strict", expires })59}6061export async function adminFromRequest(req: FastifyRequest): Promise<Admin | null> {62  const token = req.cookies[COOKIE]63  if (!token || token.length > 200) return null64  const [r] = await sql`65    select s.id, s.user_id, s.last_seen_at, u.handle from admin_sessions s join users u on u.id = s.user_id66    where s.id = ${sha256hex(token)} and s.expires_at > now() and s.last_seen_at > now() - make_interval(hours => ${IDLE_HOURS}) and u.disabled_at is null`67  if (!r) return null68  if (Date.now() - new Date(r.last_seen_at).getTime() > 60_000) await sql`update admin_sessions set last_seen_at = now() where id = ${r.id}`69  return { userId: r.user_id, sessionId: r.id, handle: r.handle }70}7172/** Garde des routes d'administration : session valide + protections CSRF (cookie SameSite=Strict, origine vérifiée, en-tête dédié pour les écritures). */73export async function requireAdmin(req: FastifyRequest): Promise<Admin> {74  if (req.method !== "GET" && req.method !== "HEAD") {75    const origin = req.headers.origin76    if (origin && origin !== config.origin) throw new ApiError(403, "bad_origin", "origine refusée")77    if (req.headers["x-requested-with"] !== "maclustr-sms") throw new ApiError(403, "csrf", "en-tête X-Requested-With manquant")78  }79  const a = await adminFromRequest(req)80  if (!a) throw new ApiError(401, "unauthenticated", "session d'administration requise")81  req.admin = a82  return a83}8485async function newChallenge(kind: "register" | "login", challenge: string, userId: string | null) {86  const id = newId("chal")87  await sql`insert into auth_challenges(id, kind, challenge, user_id, expires_at) values (${id}, ${kind}, ${challenge}, ${userId}, now() + interval '5 minutes')`88  return id89}90async function takeChallenge(id: string, kind: string) {91  const [r] = await sql`delete from auth_challenges where id = ${id} and kind = ${kind} and expires_at > now() returning *`92  if (!r) throw bad("challenge_expired", "défi expiré, recommencez")93  return r94}95const parse = <T>(s: z.ZodType<T>, v: unknown): T => { const r = s.safeParse(v); if (!r.success) throw bad("invalid_request", "requête invalide", r.error.issues.map(i => ({ path: i.path.join("."), message: i.message }))); return r.data }9697async function registrationOptions(userId: string) {98  const [u] = await sql`select * from users where id = ${userId}`99  const existing = await sql`select id, transports from passkeys where user_id = ${userId}`100  const options = await generateRegistrationOptions({101    rpName: "MacLustr SMS", rpID: config.rpId, userName: u.handle, userDisplayName: u.display_name, userID: new TextEncoder().encode(u.id),102    attestationType: "none", authenticatorSelection: { residentKey: "required", userVerification: "required" },103    excludeCredentials: existing.map(p => ({ id: p.id, transports: p.transports })),104  })105  return { challenge_id: await newChallenge("register", options.challenge, userId), options }106}107async function verifyRegistration(challengeId: string, response: any, label: string) {108  const ch = await takeChallenge(challengeId, "register")109  const v = await verifyRegistrationResponse({ response, expectedChallenge: ch.challenge, expectedOrigin: config.origin, expectedRPID: config.rpId, requireUserVerification: true }).catch(() => null)110  if (!v?.verified || !v.registrationInfo) throw bad("passkey_verification_failed", "la clé d'accès n'a pas pu être vérifiée")111  const c = v.registrationInfo.credential112  return { userId: ch.user_id as string, insert: (tx: any) => tx`insert into passkeys(id, user_id, public_key, counter, transports, label) values (${c.id}, ${ch.user_id}, ${Buffer.from(c.publicKey)}, ${c.counter}, ${c.transports ?? []}, ${label})` }113}114115export function authRoutes(app: FastifyInstance) {116  app.get("/api/auth/me", async req => {117    const a = await adminFromRequest(req)118    if (!a) throw new ApiError(401, "unauthenticated", "non connecté")119    const [u] = await sql`select id, handle, display_name from users where id = ${a.userId}`120    const keys = await sql`select id, label, created_at, last_used_at from passkeys where user_id = ${a.userId} order by created_at`121    return { user: u, passkeys: keys.map(k => ({ id: k.id, label: k.label, created_at: iso(k.created_at), last_used_at: iso(k.last_used_at) })) }122  })123124  // Enrôlement par lien à usage unique émis par la CLI opérateur (le jeton voyage dans le corps, jamais dans l'URL côté serveur).125  app.post("/api/auth/enroll/options", async req => {126    enforce("enroll:" + req.ip, 10)127    const { token } = parse(z.object({ token: z.string().min(20).max(120) }), req.body)128    const [t] = await sql`select user_id from enrollment_tokens where token_hash = ${sha256hex(token)} and used_at is null and expires_at > now()`129    if (!t) throw new ApiError(403, "invalid_enrollment_token", "lien d'enrôlement invalide, expiré ou déjà utilisé")130    return registrationOptions(t.user_id)131  })132  app.post("/api/auth/enroll/verify", async (req, reply) => {133    enforce("enroll:" + req.ip, 10)134    const b = parse(z.object({ token: z.string().min(20).max(120), challenge_id: z.string().max(64), response: z.any(), label: z.string().max(60).optional() }), req.body)135    const reg = await verifyRegistration(b.challenge_id, b.response, b.label || "Clé d'accès")136    await sql.begin(async tx => {137      const used = await tx`update enrollment_tokens set used_at = now() where token_hash = ${sha256hex(b.token)} and user_id = ${reg.userId} and used_at is null and expires_at > now() returning 1`138      if (!used.length) throw new ApiError(403, "invalid_enrollment_token", "lien d'enrôlement invalide, expiré ou déjà utilisé")139      await reg.insert(tx)140      await audit({ actorType: "admin", actorId: reg.userId, action: "passkey.enrolled", ip: req.ip }, tx)141    })142    await createSession(req, reply, reg.userId)143    return { ok: true }144  })145146  app.post("/api/auth/passkeys/options", async req => registrationOptions((await requireAdmin(req)).userId))147  app.post("/api/auth/passkeys/verify", async req => {148    const a = await requireAdmin(req)149    const b = parse(z.object({ challenge_id: z.string().max(64), response: z.any(), label: z.string().max(60).optional() }), req.body)150    const reg = await verifyRegistration(b.challenge_id, b.response, b.label || "Clé d'accès")151    if (reg.userId !== a.userId) throw new ApiError(403, "forbidden", "défi d'un autre compte")152    await sql.begin(async tx => { await reg.insert(tx); await audit({ actorType: "admin", actorId: a.userId, action: "passkey.added", ip: req.ip }, tx) })153    return { ok: true }154  })155  app.delete("/api/auth/passkeys/:id", async req => {156    const a = await requireAdmin(req)157    const [n] = await sql`select count(*)::int as n from passkeys where user_id = ${a.userId}`158    if (n.n <= 1) throw new ApiError(409, "last_passkey", "impossible de supprimer la dernière clé d'accès")159    await sql`delete from passkeys where id = ${(req.params as any).id} and user_id = ${a.userId}`160    await audit({ actorType: "admin", actorId: a.userId, action: "passkey.removed", ip: req.ip })161    return { ok: true }162  })163164  app.post("/api/auth/login/options", async req => {165    enforce("login:" + req.ip, 20)166    const options = await generateAuthenticationOptions({ rpID: config.rpId, userVerification: "required" })167    return { challenge_id: await newChallenge("login", options.challenge, null), options }168  })169  app.post("/api/auth/login/verify", async (req, reply) => {170    enforce("login:" + req.ip, 20)171    const b = parse(z.object({ challenge_id: z.string().max(64), response: z.any() }), req.body)172    const ch = await takeChallenge(b.challenge_id, "login")173    const [pk] = await sql`select p.*, u.disabled_at from passkeys p join users u on u.id = p.user_id where p.id = ${String(b.response?.id ?? "")}`174    if (!pk || pk.disabled_at) throw new ApiError(401, "login_failed", "connexion refusée")175    const v = await verifyAuthenticationResponse({176      response: b.response, expectedChallenge: ch.challenge, expectedOrigin: config.origin, expectedRPID: config.rpId, requireUserVerification: true,177      credential: { id: pk.id, publicKey: new Uint8Array(pk.public_key), counter: Number(pk.counter), transports: pk.transports },178    }).catch(() => null)179    if (!v?.verified) throw new ApiError(401, "login_failed", "connexion refusée")180    await sql`update passkeys set counter = ${v.authenticationInfo.newCounter}, last_used_at = now() where id = ${pk.id}`181    await createSession(req, reply, pk.user_id)182    await audit({ actorType: "admin", actorId: pk.user_id, action: "admin.login", ip: req.ip })183    return { ok: true }184  })185  app.post("/api/auth/logout", async (req, reply) => {186    const a = await adminFromRequest(req)187    if (a) await sql`delete from admin_sessions where id = ${a.sessionId}`188    reply.clearCookie(COOKIE, { path: "/", httpOnly: true, secure: config.secure, sameSite: "strict" })189    return { ok: true }190  })191}192
Files main
Menu

Theme