Repository Public
1import crypto from "node:crypto";2import { all, get, getNum, getSetting, log, now, run, setSetting } from "./db";3import { env } from "./env";45// Single-owner authentication: one password (scrypt) and any number of passkeys. Sessions are random 256-bit tokens;6// only their SHA-256 is stored. Failed sign-ins are throttled per address and globally.78export const COOKIE = env.prod ? "__Host-sptv" : "sptv";910export function hashPassword(pw: string): string {11 const salt = crypto.randomBytes(16);12 const N = 1 << 15;13 const key = crypto.scryptSync(pw.normalize("NFKC"), salt, 32, { N, r: 8, p: 1, maxmem: 64 * 1024 * 1024 });14 return `scrypt$${N}$${salt.toString("base64")}$${key.toString("base64")}`;15}16export function verifyPassword(pw: string, stored: string | undefined): boolean {17 // Always derive a key, even without a stored hash, so timing does not reveal whether a password is set.18 const [, n, salt, hash] = (stored ?? `scrypt$32768$${Buffer.alloc(16).toString("base64")}$${Buffer.alloc(32).toString("base64")}`).split("$");19 const key = crypto.scryptSync(pw.normalize("NFKC"), Buffer.from(salt, "base64"), 32, { N: Number(n), r: 8, p: 1, maxmem: 64 * 1024 * 1024 });20 const ref = Buffer.from(hash, "base64");21 return !!stored && key.length === ref.length && crypto.timingSafeEqual(key, ref);22}23export function setPassword(pw: string) {24 if (pw.length < 12) throw new Error("Le mot de passe doit contenir au moins 12 caractères");25 setSetting("password_hash", hashPassword(pw));26}27export const hasPassword = () => !!getSetting("password_hash");2829const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");3031export function createSession(meta: { ip: string; userAgent: string | null; method: "password" | "passkey" }): { token: string; maxAge: number } {32 const token = crypto.randomBytes(32).toString("base64url");33 const maxAge = getNum("session_days") * 86400;34 run("INSERT INTO sessions(token_hash, created_at, expires_at, last_seen_at, user_agent, ip, method) VALUES(?,?,?,?,?,?,?)",35 sha(token), now(), now() + maxAge * 1000, now(), meta.userAgent?.slice(0, 300) ?? null, meta.ip, meta.method);36 run("DELETE FROM sessions WHERE expires_at < ?", now());37 return { token, maxAge };38}39export function checkSession(token: string | undefined): { id: string } | null {40 if (!token || token.length > 100) return null;41 const h = sha(token);42 const s = get<{ expires_at: number; last_seen_at: number }>("SELECT expires_at, last_seen_at FROM sessions WHERE token_hash = ?", h);43 if (!s || s.expires_at < now()) return null;44 if (now() - s.last_seen_at > 5 * 60_000) run("UPDATE sessions SET last_seen_at = ? WHERE token_hash = ?", now(), h);45 return { id: h };46}47export function destroySession(token: string | undefined) { if (token) run("DELETE FROM sessions WHERE token_hash = ?", sha(token)); }48export function listSessions(currentId: string) {49 return all<{ token_hash: string; created_at: number; last_seen_at: number; user_agent: string | null; ip: string | null; method: string }>(50 "SELECT token_hash, created_at, last_seen_at, user_agent, ip, method FROM sessions WHERE expires_at > ? ORDER BY last_seen_at DESC", now())51 .map((s) => ({ id: s.token_hash.slice(0, 16), current: s.token_hash === currentId, createdAt: s.created_at, lastSeenAt: s.last_seen_at, userAgent: s.user_agent, ip: s.ip, method: s.method }));52}53export function revokeSession(idPrefix: string) { if (/^[0-9a-f]{16}$/.test(idPrefix)) run("DELETE FROM sessions WHERE token_hash LIKE ?", idPrefix + "%"); }54export function revokeOtherSessions(currentId: string) { run("DELETE FROM sessions WHERE token_hash != ?", currentId); }5556// --- throttling -----------------------------------------------------------------------------------------------------57const WINDOW = 15 * 60_000, PER_IP = 5, GLOBAL = 30;58/** Seconds to wait before another attempt is accepted, 0 when allowed. */59export function loginLocked(ip: string): number {60 const since = now() - WINDOW;61 const mine = all<{ at: number }>("SELECT at FROM login_attempts WHERE ip = ? AND ok = 0 AND at > ? ORDER BY at DESC", ip, since);62 if (mine.length >= PER_IP) return Math.ceil((mine[PER_IP - 1].at + WINDOW - now()) / 1000);63 const allFails = get<{ n: number; first: number }>("SELECT COUNT(*) n, MIN(at) first FROM login_attempts WHERE ok = 0 AND at > ?", since)!;64 if (allFails.n >= GLOBAL) return Math.ceil((allFails.first + WINDOW - now()) / 1000);65 return 0;66}67export function recordAttempt(ip: string, ok: boolean, method: string) {68 run("INSERT INTO login_attempts(ip, at, ok, method) VALUES(?,?,?,?)", ip, now(), Number(ok), method);69 if (ok) run("DELETE FROM login_attempts WHERE ip = ? AND ok = 0", ip);70 else log("warn", "auth", `Échec de connexion (${method})`, { ip });71 run("DELETE FROM login_attempts WHERE at < ?", now() - 30 * 86400_000);72}7374// --- signed short-lived values (WebAuthn challenges) -----------------------------------------------------------------75export function sign(value: string, ttlSec: number): string {76 const body = Buffer.from(JSON.stringify({ v: value, e: now() + ttlSec * 1000 })).toString("base64url");77 return `${body}.${crypto.createHmac("sha256", env.appSecret).update(body).digest("base64url")}`;78}79export function unsign(signed: string | undefined): string | null {80 if (!signed) return null;81 const [body, mac] = signed.split(".");82 if (!body || !mac) return null;83 const want = crypto.createHmac("sha256", env.appSecret).update(body).digest();84 const got = Buffer.from(mac, "base64url");85 if (got.length !== want.length || !crypto.timingSafeEqual(got, want)) return null;86 try { const p = JSON.parse(Buffer.from(body, "base64url").toString()) as { v: string; e: number }; return p.e > now() ? p.v : null; } catch { return null; }87}88