SPB Git

Repository Public

auth.ts 27.5 KB 647 lines typescript

1import { getDb, tx } from "./db";2import {3  decrypt,4  dummyVerify,5  encrypt,6  hashPassword,7  newTotpSecret,8  randomToken,9  sha256,10  totpVerify,11  verifyPassword,12} from "./crypto";1314/**15 * Authentification maison (admin et clients) : Argon2id, sessions serveur opaques16 * (jeton aléatoire, seul le SHA-256 est stocké), limitation des tentatives,17 * verrouillage progressif, MFA TOTP, journal d'audit. Aucune dépendance à Next ici18 * (voir session.ts pour les témoins) afin de rester testable.19 */20export type Realm = "admin" | "client";2122export interface UserRow {23  id: number;24  role: Realm;25  username: string | null;26  email: string | null;27  name: string;28  organization: string;29  phone: string;30  password_hash: string;31  google_sub: string | null;32  must_change_password: number;33  email_verified_at: number | null;34  totp_secret_enc: string | null;35  totp_enabled: number;36  recovery_codes: string;37  failed_attempts: number;38  locked_until: number;39  disabled: number;40  marketing_consent: number;41  created_at: number;42  updated_at: number;43  last_login_at: number | null;44}4546export interface SessionRow {47  token_hash: string;48  user_id: number;49  realm: Realm;50  csrf: string;51  mfa_pending: number;52  created_at: number;53  last_seen_at: number;54  expires_at: number;55}5657const HOUR = 3600_000;58export const SESSION_TTL: Record<Realm, { absolute: number; idle: number }> = {59  admin: { absolute: 12 * HOUR, idle: 2 * HOUR },60  client: { absolute: 30 * 24 * HOUR, idle: 14 * 24 * HOUR },61};6263/* ---------------- Journal d'audit ---------------- */64export function audit(65  action: string,66  opts: { userId?: number | null; actor?: string; target?: string; detail?: string; ipHash?: string } = {},67) {68  getDb()69    .prepare(70      "INSERT INTO audit_log (at, user_id, actor, action, target, detail, ip_hash) VALUES (?,?,?,?,?,?,?)",71    )72    .run(73      Date.now(),74      opts.userId ?? null,75      opts.actor ?? "",76      action,77      opts.target ?? "",78      (opts.detail ?? "").slice(0, 500),79      opts.ipHash ?? "",80    );81}8283/* ---------------- Limitation de débit persistée ---------------- */84export function rateLimit(85  bucket: string,86  limit: number,87  windowMs: number,88  now = Date.now(),89): { allowed: boolean; retryAfterS: number } {90  const db = getDb();91  return tx(db, () => {92    db.prepare("DELETE FROM rate_events WHERE at < ?").run(now - 24 * HOUR);93    const rows = db94      .prepare("SELECT at FROM rate_events WHERE bucket = ? AND at > ? ORDER BY at ASC")95      .all(bucket, now - windowMs) as { at: number }[];96    if (rows.length >= limit) {97      return { allowed: false, retryAfterS: Math.max(1, Math.ceil((rows[0].at + windowMs - now) / 1000)) };98    }99    db.prepare("INSERT INTO rate_events (bucket, at) VALUES (?, ?)").run(bucket, now);100    return { allowed: true, retryAfterS: 0 };101  });102}103104/* ---------------- Politique de mot de passe ---------------- */105const COMMON = new Set([106  "admin123",107  "admin1234",108  "password",109  "password1",110  "motdepasse",111  "motdepasse1",112  "123456789",113  "1234567890",114  "12345678910",115  "qwertyuiop",116  "azertyuiop",117  "phiconseil",118  "phiconseil1",119  "changeme123",120  "bonjour123",121  "letmein123",122]);123124export function passwordIssues(password: string, ctx: { role: Realm; identifiers?: string[] }): string | null {125  const min = ctx.role === "admin" ? 12 : 10;126  if (password.length < min) return `Le mot de passe doit contenir au moins ${min} caractères.`;127  if (password.length > 200) return "Le mot de passe est trop long (200 caractères maximum).";128  const lower = password.toLowerCase();129  if (COMMON.has(lower)) return "Ce mot de passe est trop courant. Choisissez-en un autre.";130  if (/^(.)\1+$/.test(password)) return "Le mot de passe ne peut pas répéter un seul caractère.";131  for (const id of ctx.identifiers ?? []) {132    if (id && id.length >= 3 && lower.includes(id.toLowerCase()))133      return "Le mot de passe ne doit pas contenir votre identifiant ou votre courriel.";134  }135  const classes = [/[a-z]/, /[A-Z]/, /\d/, /[^A-Za-z0-9]/].filter((r) => r.test(password)).length;136  if (classes < 3 && password.length < 16)137    return "Utilisez au moins trois types de caractères (minuscules, majuscules, chiffres, symboles) ou une phrase de 16 caractères et plus.";138  return null;139}140141/* ---------------- Utilisateurs ---------------- */142export function userById(id: number): UserRow | undefined {143  return getDb().prepare("SELECT * FROM users WHERE id = ?").get(id) as UserRow | undefined;144}145146function findUser(realm: Realm, identifier: string): UserRow | undefined {147  const id = identifier.trim().toLowerCase();148  const db = getDb();149  if (realm === "admin") {150    return db151      .prepare("SELECT * FROM users WHERE role = 'admin' AND (lower(username) = ? OR lower(email) = ?)")152      .get(id, id) as UserRow | undefined;153  }154  return db.prepare("SELECT * FROM users WHERE role = 'client' AND lower(email) = ?").get(id) as155    | UserRow156    | undefined;157}158159/** Crée (ou réinitialise) le compte administrateur initial. Le mot de passe n'est jamais stocké en clair. */160export function upsertAdmin(username: string, password: string, mustChange = true): number {161  const db = getDb();162  const now = Date.now();163  const existing = db164    .prepare("SELECT id FROM users WHERE role = 'admin' AND lower(username) = ?")165    .get(username.toLowerCase()) as { id: number } | undefined;166  const hash = hashPassword(password);167  if (existing) {168    db.prepare(169      "UPDATE users SET password_hash = ?, must_change_password = ?, failed_attempts = 0, locked_until = 0, disabled = 0, updated_at = ? WHERE id = ?",170    ).run(hash, mustChange ? 1 : 0, now, existing.id);171    db.prepare("DELETE FROM sessions WHERE user_id = ?").run(existing.id);172    return existing.id;173  }174  const r = db175    .prepare(176      "INSERT INTO users (role, username, name, password_hash, must_change_password, email_verified_at, created_at, updated_at) VALUES ('admin', ?, 'Administrateur', ?, ?, ?, ?, ?)",177    )178    .run(username, hash, mustChange ? 1 : 0, now, now, now);179  return Number(r.lastInsertRowid);180}181182export function adminCount(): number {183  return (getDb().prepare("SELECT count(*) AS n FROM users WHERE role = 'admin'").get() as { n: number }).n;184}185186/* ---------------- Sessions ---------------- */187export function createSession(188  userId: number,189  realm: Realm,190  opts: { mfaPending?: boolean; ipHash?: string; userAgent?: string; now?: number } = {},191): string {192  const now = opts.now ?? Date.now();193  const token = randomToken(32);194  getDb()195    .prepare(196      "INSERT INTO sessions (token_hash, user_id, realm, csrf, mfa_pending, created_at, last_seen_at, expires_at, ip_hash, user_agent) VALUES (?,?,?,?,?,?,?,?,?,?)",197    )198    .run(199      sha256(token),200      userId,201      realm,202      randomToken(24),203      opts.mfaPending ? 1 : 0,204      now,205      now,206      now + SESSION_TTL[realm].absolute,207      opts.ipHash ?? "",208      (opts.userAgent ?? "").slice(0, 200),209    );210  return token;211}212213export function getSession(214  token: string | undefined,215  realm: Realm,216  now = Date.now(),217): { session: SessionRow; user: UserRow } | null {218  if (!token || token.length < 20) return null;219  const db = getDb();220  const hash = sha256(token);221  const session = db.prepare("SELECT * FROM sessions WHERE token_hash = ? AND realm = ?").get(hash, realm) as222    | SessionRow223    | undefined;224  if (!session) return null;225  if (session.expires_at <= now || now - session.last_seen_at > SESSION_TTL[realm].idle) {226    db.prepare("DELETE FROM sessions WHERE token_hash = ?").run(hash);227    return null;228  }229  const user = userById(session.user_id);230  if (!user || user.disabled || user.role !== realm) {231    db.prepare("DELETE FROM sessions WHERE token_hash = ?").run(hash);232    return null;233  }234  if (now - session.last_seen_at > 60_000) {235    db.prepare("UPDATE sessions SET last_seen_at = ? WHERE token_hash = ?").run(now, hash);236  }237  return { session, user };238}239240export function destroySession(token: string | undefined) {241  if (token) getDb().prepare("DELETE FROM sessions WHERE token_hash = ?").run(sha256(token));242}243244export function destroyUserSessions(userId: number) {245  getDb().prepare("DELETE FROM sessions WHERE user_id = ?").run(userId);246}247248export function listSessions(userId: number) {249  return getDb()250    .prepare(251      "SELECT token_hash, created_at, last_seen_at, expires_at, user_agent FROM sessions WHERE user_id = ? ORDER BY last_seen_at DESC",252    )253    .all(userId) as { token_hash: string; created_at: number; last_seen_at: number; expires_at: number; user_agent: string }[];254}255256/* ---------------- Connexion ---------------- */257export type LoginResult =258  | { ok: true; token: string; user: UserRow; mfaRequired: boolean }259  | { ok: false; reason: "invalid" | "locked" | "rate" | "unverified"; retryAfterS?: number };260261function lockDelayMs(failures: number): number {262  if (failures < 5) return 0;263  return Math.min(60_000 * 2 ** (failures - 5), HOUR);264}265266export function attemptLogin(input: {267  realm: Realm;268  identifier: string;269  password: string;270  ipHash: string;271  userAgent?: string;272  now?: number;273}): LoginResult {274  const now = input.now ?? Date.now();275  const db = getDb();276  const ipRl = rateLimit(`login:${input.realm}:ip:${input.ipHash}`, 20, 10 * 60_000, now);277  if (!ipRl.allowed) {278    audit("login.rate_limited", { actor: input.identifier.slice(0, 80), ipHash: input.ipHash });279    return { ok: false, reason: "rate", retryAfterS: ipRl.retryAfterS };280  }281  const user = findUser(input.realm, input.identifier);282  if (!user || user.disabled) {283    dummyVerify(input.password);284    audit("login.failed", { actor: input.identifier.slice(0, 80), detail: "compte inconnu", ipHash: input.ipHash });285    return { ok: false, reason: "invalid" };286  }287  if (user.locked_until > now) {288    dummyVerify(input.password);289    audit("login.locked", { userId: user.id, ipHash: input.ipHash });290    return { ok: false, reason: "locked", retryAfterS: Math.ceil((user.locked_until - now) / 1000) };291  }292  if (!verifyPassword(input.password, user.password_hash)) {293    const failures = user.failed_attempts + 1;294    const delay = lockDelayMs(failures);295    db.prepare("UPDATE users SET failed_attempts = ?, locked_until = ? WHERE id = ?").run(296      failures,297      delay ? now + delay : 0,298      user.id,299    );300    audit("login.failed", { userId: user.id, detail: `tentative ${failures}`, ipHash: input.ipHash });301    if (delay) return { ok: false, reason: "locked", retryAfterS: Math.ceil(delay / 1000) };302    return { ok: false, reason: "invalid" };303  }304  if (input.realm === "client" && !user.email_verified_at) {305    return { ok: false, reason: "unverified" };306  }307  db.prepare("UPDATE users SET failed_attempts = 0, locked_until = 0, last_login_at = ? WHERE id = ?").run(308    now,309    user.id,310  );311  const mfaRequired = user.totp_enabled === 1;312  const token = createSession(user.id, input.realm, {313    mfaPending: mfaRequired,314    ipHash: input.ipHash,315    userAgent: input.userAgent,316    now,317  });318  audit(mfaRequired ? "login.password_ok_mfa_pending" : "login.success", { userId: user.id, ipHash: input.ipHash });319  return { ok: true, token, user, mfaRequired };320}321322/* ---------------- Mot de passe ---------------- */323export type PasswordChangeResult = { ok: true; token: string } | { ok: false; error: string };324325/**326 * Change le mot de passe : vérifie l'actuel, applique la politique, invalide TOUTES les327 * sessions de l'utilisateur puis en ouvre une nouvelle (renvoyée) pour l'appareil courant.328 */329export function changePassword(input: {330  userId: number;331  current: string;332  next: string;333  ipHash?: string;334  userAgent?: string;335}): PasswordChangeResult {336  const user = userById(input.userId);337  if (!user) return { ok: false, error: "Compte introuvable." };338  const rl = rateLimit(`pwchange:${user.id}`, 8, 15 * 60_000);339  if (!rl.allowed) return { ok: false, error: "Trop de tentatives. Réessayez plus tard." };340  if (!verifyPassword(input.current, user.password_hash))341    return { ok: false, error: "Le mot de passe actuel est incorrect." };342  if (input.current === input.next)343    return { ok: false, error: "Le nouveau mot de passe doit être différent de l'ancien." };344  const issue = passwordIssues(input.next, {345    role: user.role,346    identifiers: [user.username ?? "", user.email ?? ""],347  });348  if (issue) return { ok: false, error: issue };349  const db = getDb();350  const token = tx(db, () => {351    db.prepare(352      "UPDATE users SET password_hash = ?, must_change_password = 0, failed_attempts = 0, locked_until = 0, updated_at = ? WHERE id = ?",353    ).run(hashPassword(input.next), Date.now(), user.id);354    db.prepare("DELETE FROM sessions WHERE user_id = ?").run(user.id);355    db.prepare("DELETE FROM user_tokens WHERE user_id = ? AND purpose = 'reset_password'").run(user.id);356    return null;357  });358  void token;359  const fresh = createSession(user.id, user.role, { ipHash: input.ipHash, userAgent: input.userAgent });360  audit("password.changed", { userId: user.id, ipHash: input.ipHash });361  return { ok: true, token: fresh };362}363364/* ---------------- MFA (TOTP) ---------------- */365export function beginTotpSetup(userId: number): string {366  const secret = newTotpSecret();367  getDb().prepare("UPDATE users SET totp_secret_enc = ?, totp_enabled = 0 WHERE id = ?").run(encrypt(secret), userId);368  return secret;369}370371export function pendingTotpSecret(userId: number): string | null {372  const u = userById(userId);373  if (!u?.totp_secret_enc) return null;374  return decrypt(u.totp_secret_enc);375}376377/** Active la MFA après vérification d'un premier code ; renvoie les codes de secours (affichés une seule fois). */378export function confirmTotp(userId: number, code: string): string[] | null {379  const u = userById(userId);380  if (!u?.totp_secret_enc) return null;381  if (!totpVerify(decrypt(u.totp_secret_enc), code)) return null;382  const codes = Array.from({ length: 10 }, () => randomToken(6).replace(/[-_]/g, "x").slice(0, 8).toLowerCase());383  getDb()384    .prepare("UPDATE users SET totp_enabled = 1, recovery_codes = ?, updated_at = ? WHERE id = ?")385    .run(JSON.stringify(codes.map(sha256)), Date.now(), userId);386  audit("mfa.enabled", { userId });387  return codes;388}389390export function disableTotp(userId: number, password: string): boolean {391  const u = userById(userId);392  if (!u || !verifyPassword(password, u.password_hash)) return false;393  getDb()394    .prepare("UPDATE users SET totp_enabled = 0, totp_secret_enc = NULL, recovery_codes = '[]', updated_at = ? WHERE id = ?")395    .run(Date.now(), userId);396  audit("mfa.disabled", { userId });397  return true;398}399400/** Deuxième facteur : code TOTP ou code de secours (à usage unique). */401export function verifyMfa(token: string, code: string): boolean {402  const db = getDb();403  const hash = sha256(token);404  const s = db.prepare("SELECT * FROM sessions WHERE token_hash = ?").get(hash) as SessionRow | undefined;405  if (!s || !s.mfa_pending) return false;406  const rl = rateLimit(`mfa:${s.user_id}`, 6, 10 * 60_000);407  if (!rl.allowed) return false;408  const u = userById(s.user_id);409  if (!u?.totp_secret_enc) return false;410  let ok = totpVerify(decrypt(u.totp_secret_enc), code);411  if (!ok) {412    const codes = JSON.parse(u.recovery_codes || "[]") as string[];413    const h = sha256(code.trim().toLowerCase());414    if (codes.includes(h)) {415      ok = true;416      db.prepare("UPDATE users SET recovery_codes = ? WHERE id = ?").run(417        JSON.stringify(codes.filter((c) => c !== h)),418        u.id,419      );420      audit("mfa.recovery_code_used", { userId: u.id });421    }422  }423  if (!ok) {424    audit("mfa.failed", { userId: u.id });425    return false;426  }427  db.prepare("UPDATE sessions SET mfa_pending = 0 WHERE token_hash = ?").run(hash);428  audit("login.success", { userId: u.id, detail: "mfa" });429  return true;430}431432/* ---------------- Jetons à usage unique (vérification de courriel, réinitialisation) ---------------- */433export function issueUserToken(userId: number, purpose: "verify_email" | "reset_password", ttlMs: number): string {434  const db = getDb();435  const token = randomToken(32);436  const now = Date.now();437  db.prepare("DELETE FROM user_tokens WHERE user_id = ? AND purpose = ?").run(userId, purpose);438  db.prepare(439    "INSERT INTO user_tokens (token_hash, user_id, purpose, created_at, expires_at) VALUES (?,?,?,?,?)",440  ).run(sha256(token), userId, purpose, now, now + ttlMs);441  return token;442}443444function consumeUserToken(token: string, purpose: "verify_email" | "reset_password", now = Date.now()): number | null {445  const db = getDb();446  const row = db447    .prepare("SELECT user_id, expires_at, used_at FROM user_tokens WHERE token_hash = ? AND purpose = ?")448    .get(sha256(token), purpose) as { user_id: number; expires_at: number; used_at: number | null } | undefined;449  if (!row || row.used_at || row.expires_at <= now) return null;450  db.prepare("UPDATE user_tokens SET used_at = ? WHERE token_hash = ?").run(now, sha256(token));451  return row.user_id;452}453454/* ---------------- Comptes clients ---------------- */455export type RegisterResult =456  | { ok: true; created: boolean; userId: number; verifyToken: string | null }457  | { ok: false; error: string };458459/**460 * Inscription d'un client. Réponse identique que le courriel existe ou non (pas d'énumération) :461 * `verifyToken` est fourni pour un nouveau compte ou un compte non encore vérifié, null sinon.462 */463export function registerClient(input: {464  email: string;465  name: string;466  password: string;467  organization?: string;468  phone?: string;469}): RegisterResult {470  const email = input.email.trim().toLowerCase();471  const issue = passwordIssues(input.password, { role: "client", identifiers: [email.split("@")[0], email] });472  if (issue) return { ok: false, error: issue };473  const db = getDb();474  const now = Date.now();475  const existing = db.prepare("SELECT * FROM users WHERE lower(email) = ?").get(email) as UserRow | undefined;476  if (existing) {477    if (existing.role === "client" && !existing.email_verified_at) {478      return { ok: true, created: false, userId: existing.id, verifyToken: issueUserToken(existing.id, "verify_email", 24 * HOUR) };479    }480    return { ok: true, created: false, userId: existing.id, verifyToken: null };481  }482  const r = db483    .prepare(484      "INSERT INTO users (role, email, name, organization, phone, password_hash, created_at, updated_at) VALUES ('client', ?, ?, ?, ?, ?, ?, ?)",485    )486    .run(email, input.name.trim(), (input.organization ?? "").trim(), (input.phone ?? "").trim(), hashPassword(input.password), now, now);487  const userId = Number(r.lastInsertRowid);488  audit("client.registered", { userId });489  return { ok: true, created: true, userId, verifyToken: issueUserToken(userId, "verify_email", 24 * HOUR) };490}491492export function verifyEmailToken(token: string): UserRow | null {493  const userId = consumeUserToken(token, "verify_email");494  if (!userId) return null;495  getDb().prepare("UPDATE users SET email_verified_at = ?, updated_at = ? WHERE id = ?").run(Date.now(), Date.now(), userId);496  audit("client.email_verified", { userId });497  return userById(userId) ?? null;498}499500/** Demande de réinitialisation : renvoie un jeton si le compte existe (sinon null, réponse publique identique). */501export function requestPasswordReset(email: string): { user: UserRow; token: string } | null {502  const user = getDb().prepare("SELECT * FROM users WHERE lower(email) = ? AND disabled = 0").get(email.trim().toLowerCase()) as503    | UserRow504    | undefined;505  if (!user) return null;506  return { user, token: issueUserToken(user.id, "reset_password", HOUR) };507}508509export function resetPasswordWithToken(token: string, next: string): { ok: true; user: UserRow } | { ok: false; error: string } {510  const db = getDb();511  const row = db512    .prepare("SELECT user_id, expires_at, used_at FROM user_tokens WHERE token_hash = ? AND purpose = 'reset_password'")513    .get(sha256(token)) as { user_id: number; expires_at: number; used_at: number | null } | undefined;514  if (!row || row.used_at || row.expires_at <= Date.now())515    return { ok: false, error: "Ce lien n'est plus valide. Demandez-en un nouveau." };516  const user = userById(row.user_id);517  if (!user) return { ok: false, error: "Compte introuvable." };518  const issue = passwordIssues(next, { role: user.role, identifiers: [user.username ?? "", user.email ?? ""] });519  if (issue) return { ok: false, error: issue };520  consumeUserToken(token, "reset_password");521  db.prepare(522    "UPDATE users SET password_hash = ?, must_change_password = 0, failed_attempts = 0, locked_until = 0, email_verified_at = coalesce(email_verified_at, ?), updated_at = ? WHERE id = ?",523  ).run(hashPassword(next), Date.now(), Date.now(), user.id);524  destroyUserSessions(user.id);525  audit("password.reset", { userId: user.id });526  return { ok: true, user };527}528529export function updateClientProfile(userId: number, p: { name: string; organization: string; phone: string; marketingConsent: boolean }) {530  getDb()531    .prepare("UPDATE users SET name = ?, organization = ?, phone = ?, marketing_consent = ?, updated_at = ? WHERE id = ? AND role = 'client'")532    .run(p.name.trim(), p.organization.trim(), p.phone.trim(), p.marketingConsent ? 1 : 0, Date.now(), userId);533}534535/** Suppression du compte client (Loi 25) : le compte et ses sessions sont effacés ; ses rendez-vous sont détachés. */536export function deleteClient(userId: number, password?: string): boolean {537  const u = userById(userId);538  if (!u || u.role !== "client") return false;539  if (password !== undefined && !verifyPassword(password, u.password_hash)) return false;540  getDb().prepare("DELETE FROM users WHERE id = ?").run(userId);541  audit("client.deleted", { target: `user:${userId}` });542  return true;543}544545/* ---------------- Connexion Google (clients) ---------------- */546/** Mot de passe inutilisable pour les comptes créés via Google (aucun hachage ne peut y correspondre). */547export const NO_PASSWORD = "!google";548549/**550 * Trouve ou crée le compte client associé à une identité Google vérifiée.551 * Un compte existant portant le même courriel (vérifié par Google) est relié à cette identité.552 */553export function upsertGoogleClient(p: { sub: string; email: string; name: string }): UserRow | null {554  const db = getDb();555  const now = Date.now();556  const email = p.email.trim().toLowerCase();557  let user = db.prepare("SELECT * FROM users WHERE google_sub = ?").get(p.sub) as UserRow | undefined;558  if (!user) {559    const byEmail = db.prepare("SELECT * FROM users WHERE lower(email) = ?").get(email) as UserRow | undefined;560    if (byEmail) {561      if (byEmail.role !== "client") return null; // jamais de connexion Google pour un compte administrateur562      db.prepare("UPDATE users SET google_sub = ?, email_verified_at = coalesce(email_verified_at, ?), updated_at = ? WHERE id = ?").run(p.sub, now, now, byEmail.id);563      user = userById(byEmail.id);564    } else {565      const r = db566        .prepare("INSERT INTO users (role, email, name, password_hash, google_sub, email_verified_at, created_at, updated_at) VALUES ('client', ?, ?, ?, ?, ?, ?, ?)")567        .run(email, p.name.trim().slice(0, 120), NO_PASSWORD, p.sub, now, now, now);568      user = userById(Number(r.lastInsertRowid));569      audit("client.registered", { userId: user?.id, detail: "google" });570    }571  }572  if (!user || user.disabled || user.role !== "client") return null;573  db.prepare("UPDATE users SET last_login_at = ? WHERE id = ?").run(now, user.id);574  return user;575}576577/** Définit un mot de passe pour un compte créé via Google (qui n'en a pas encore). */578export function setInitialPassword(userId: number, next: string): { ok: true } | { ok: false; error: string } {579  const u = userById(userId);580  if (!u || u.password_hash !== NO_PASSWORD) return { ok: false, error: "Un mot de passe existe déjà." };581  const issue = passwordIssues(next, { role: u.role, identifiers: [u.email ?? ""] });582  if (issue) return { ok: false, error: issue };583  getDb().prepare("UPDATE users SET password_hash = ?, updated_at = ? WHERE id = ?").run(hashPassword(next), Date.now(), userId);584  audit("password.set", { userId });585  return { ok: true };586}587588/* ---------------- Invitation d'administrateur (lien à usage unique) ---------------- */589const RESERVED_USERNAMES = new Set(["admin", "administrateur", "administrator", "root", "test", "user", "utilisateur"]);590591/** Crée une invitation ; renvoie le jeton en clair (à transmettre une seule fois, jamais stocké). */592export function createAdminInvite(ttlMs = 7 * 24 * HOUR, note = "", now = Date.now()): string {593  const token = randomToken(32);594  getDb().prepare("INSERT INTO admin_invites (token_hash, created_at, expires_at, note) VALUES (?,?,?,?)").run(sha256(token), now, now + ttlMs, note.slice(0, 200));595  audit("admin.invite_created", { actor: "cli", detail: note });596  return token;597}598599export function pendingAdminInvites(now = Date.now()): number {600  return (getDb().prepare("SELECT count(*) AS n FROM admin_invites WHERE used_at IS NULL AND expires_at > ?").get(now) as { n: number }).n;601}602603export function adminInviteValid(token: string, now = Date.now()): boolean {604  if (!token || token.length < 20) return false;605  const row = getDb().prepare("SELECT expires_at, used_at FROM admin_invites WHERE token_hash = ?").get(sha256(token)) as { expires_at: number; used_at: number | null } | undefined;606  return !!row && !row.used_at && row.expires_at > now;607}608609export type InviteResult = { ok: true; userId: number } | { ok: false; error: string };610611/**612 * Le propriétaire crée son accès administrateur personnel à partir du lien d'invitation.613 * L'invitation est consommée dans la même transaction ; le compte générique d'amorçage614 * (jamais utilisé) est supprimé : il ne reste aucun accès partagé.615 */616export function acceptAdminInvite(input: { token: string; username: string; email: string; name: string; password: string; now?: number }): InviteResult {617  const now = input.now ?? Date.now();618  const username = input.username.trim().toLowerCase();619  const email = input.email.trim().toLowerCase();620  const name = input.name.trim().slice(0, 120);621  if (!/^[a-z0-9][a-z0-9._-]{2,39}$/.test(username)) return { ok: false, error: "Identifiant : 3 à 40 caractères (lettres minuscules, chiffres, point, tiret)." };622  if (RESERVED_USERNAMES.has(username)) return { ok: false, error: "Choisissez un identifiant personnel (« admin » et les noms génériques ne sont pas permis)." };623  if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return { ok: false, error: "Adresse courriel invalide." };624  if (name.length < 2) return { ok: false, error: "Indiquez votre nom." };625  const issue = passwordIssues(input.password, { role: "admin", identifiers: [username, email.split("@")[0]] });626  if (issue) return { ok: false, error: issue };627  const db = getDb();628  const hash = hashPassword(input.password);629  try {630    return tx(db, () => {631      if (!adminInviteValid(input.token, now)) return { ok: false as const, error: "Ce lien d’activation n’est plus valide (déjà utilisé ou expiré)." };632      if (db.prepare("SELECT 1 FROM users WHERE lower(username) = ? OR lower(email) = ?").get(username, email)) return { ok: false as const, error: "Cet identifiant ou ce courriel est déjà utilisé." };633      const r = db634        .prepare("INSERT INTO users (role, username, email, name, password_hash, must_change_password, email_verified_at, created_at, updated_at) VALUES ('admin', ?, ?, ?, ?, 0, ?, ?, ?)")635        .run(username, email, name, hash, now, now, now);636      const userId = Number(r.lastInsertRowid);637      db.prepare("UPDATE admin_invites SET used_at = ?, used_by = ? WHERE token_hash = ?").run(now, userId, sha256(input.token));638      // Compte générique d'amorçage jamais utilisé → supprimé.639      db.prepare("DELETE FROM users WHERE role = 'admin' AND id != ? AND last_login_at IS NULL AND must_change_password = 1").run(userId);640      audit("admin.invite_accepted", { userId, target: username });641      return { ok: true as const, userId };642    });643  } catch {644    return { ok: false, error: "La création du compte a échoué. Réessayez." };645  }646}647
Files main
Menu

Theme