Repository Public
1import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse } from "@simplewebauthn/server";2import { z } from "zod";3import { all, get, log, now, run } from "../db";4import { env } from "../env";5import { COOKIE, createSession, destroySession, listSessions, loginLocked, recordAttempt, revokeOtherSessions, revokeSession, setPassword, sign, unsign, verifyPassword } from "../auth";6import { getSetting } from "../db";7import { cookie, HttpError, route, type Ctx } from "./core";89const rpID = () => new URL(env.appUrl).hostname;10const CHAL = "sptv_chal";1112function startSession(c: Ctx, method: "password" | "passkey") {13 const s = createSession({ ip: c.ip, userAgent: c.req.headers.get("user-agent"), method });14 c.setCookies.push(cookie(COOKIE, s.token, s.maxAge));15 log("info", "auth", `Connexion réussie (${method})`, { ip: c.ip });16}17function throttle(c: Ctx) {18 const wait = loginLocked(c.ip);19 if (wait > 0) throw new HttpError(429, `Trop de tentatives. Réessayez dans ${Math.ceil(wait / 60)} min.`, { retryAfter: wait });20}2122route("POST", "/auth/login", async (c) => {23 throttle(c);24 const b = await c.body(z.object({ username: z.string().max(100), password: z.string().min(1).max(500) }));25 const ok = verifyPassword(b.password, getSetting("password_hash")) && b.username.trim().toLowerCase() === env.ownerUsername.toLowerCase();26 recordAttempt(c.ip, ok, "password");27 if (!ok) throw new HttpError(401, "Identifiant ou mot de passe incorrect");28 startSession(c, "password");29}, { public: true });3031route("POST", "/auth/logout", (c) => { destroySession(c.cookies.get(COOKIE)); c.setCookies.push(cookie(COOKIE, "", 0)); }, { public: true });3233route("POST", "/auth/passkey/options", async (c) => {34 throttle(c);35 const options = await generateAuthenticationOptions({ rpID: rpID(), userVerification: "preferred" });36 c.setCookies.push(cookie(CHAL, sign(options.challenge, 300), 300, { path: "/api/auth" }));37 return { options, available: !!get("SELECT 1 FROM passkeys LIMIT 1") };38}, { public: true });3940route("POST", "/auth/passkey/verify", async (c) => {41 throttle(c);42 const b = await c.body(z.object({ response: z.any() }));43 const challenge = unsign(c.cookies.get(CHAL));44 const cred = get<{ id: string; public_key: Uint8Array; counter: number; transports: string | null }>("SELECT * FROM passkeys WHERE id = ?", String(b.response?.id ?? ""));45 let ok = false;46 if (challenge && cred) {47 try {48 const v = await verifyAuthenticationResponse({49 response: b.response, expectedChallenge: challenge, expectedOrigin: env.appUrl, expectedRPID: rpID(), requireUserVerification: false,50 credential: { id: cred.id, publicKey: new Uint8Array(cred.public_key), counter: cred.counter, transports: cred.transports ? JSON.parse(cred.transports) : undefined },51 });52 ok = v.verified;53 if (ok) run("UPDATE passkeys SET counter = ?, last_used_at = ? WHERE id = ?", v.authenticationInfo.newCounter, now(), cred.id);54 } catch { ok = false; }55 }56 recordAttempt(c.ip, ok, "passkey");57 c.setCookies.push(cookie(CHAL, "", 0, { path: "/api/auth" }));58 if (!ok) throw new HttpError(401, "Clé d'accès refusée");59 startSession(c, "passkey");60}, { public: true });6162// --- authenticated security settings --------------------------------------------------------------------------------63route("POST", "/auth/passkey/register-options", async (c) => {64 const existing = all<{ id: string; transports: string | null }>("SELECT id, transports FROM passkeys");65 const options = await generateRegistrationOptions({66 rpName: "SP TV", rpID: rpID(), userName: env.ownerUsername, userDisplayName: "SP TV", userID: new TextEncoder().encode("sptv-owner"), attestationType: "none",67 excludeCredentials: existing.map((e) => ({ id: e.id, transports: e.transports ? JSON.parse(e.transports) : undefined })),68 authenticatorSelection: { residentKey: "required", userVerification: "preferred" },69 });70 c.setCookies.push(cookie(CHAL, sign(options.challenge, 300), 300, { path: "/api/auth" }));71 return { options };72});73route("POST", "/auth/passkey/register", async (c) => {74 const b = await c.body(z.object({ response: z.any(), name: z.string().trim().min(1).max(60) }));75 const challenge = unsign(c.cookies.get(CHAL));76 if (!challenge) throw new HttpError(400, "Défi expiré, recommencez");77 const v = await verifyRegistrationResponse({ response: b.response, expectedChallenge: challenge, expectedOrigin: env.appUrl, expectedRPID: rpID(), requireUserVerification: false }).catch((e) => { throw new HttpError(400, `Enregistrement refusé : ${(e as Error).message}`); });78 if (!v.verified || !v.registrationInfo) throw new HttpError(400, "Enregistrement refusé");79 const cr = v.registrationInfo.credential;80 run("INSERT INTO passkeys(id, public_key, counter, transports, name, created_at) VALUES(?,?,?,?,?,?)", cr.id, Buffer.from(cr.publicKey), cr.counter, JSON.stringify(cr.transports ?? []), b.name, now());81 c.setCookies.push(cookie(CHAL, "", 0, { path: "/api/auth" }));82 log("info", "auth", `Clé d'accès ajoutée : ${b.name}`);83});84route("DELETE", "/auth/passkey/:id", (c) => { run("DELETE FROM passkeys WHERE id = ?", c.params[0]); log("info", "auth", "Clé d'accès supprimée"); });8586route("GET", "/auth/security", (c) => ({87 username: env.ownerUsername,88 passkeys: all<{ id: string; name: string; created_at: number; last_used_at: number | null }>("SELECT id, name, created_at, last_used_at FROM passkeys ORDER BY created_at"),89 sessions: listSessions(c.session!.id),90 attempts: all("SELECT ip, at, ok, method FROM login_attempts ORDER BY at DESC LIMIT 30"),91 sessionDays: Number(getSetting("session_days")),92}));93route("POST", "/auth/password", async (c) => {94 const b = await c.body(z.object({ current: z.string().max(500), next: z.string().min(12, "12 caractères minimum").max(500) }));95 if (!verifyPassword(b.current, getSetting("password_hash"))) { recordAttempt(c.ip, false, "password-change"); throw new HttpError(403, "Mot de passe actuel incorrect"); }96 setPassword(b.next);97 revokeOtherSessions(c.session!.id);98 log("info", "auth", "Mot de passe modifié ; autres sessions fermées");99});100route("DELETE", "/auth/sessions/:id", (c) => { if (c.params[0] === "others") revokeOtherSessions(c.session!.id); else revokeSession(c.params[0]); });101