SPB Git

Repository Public

crypto.ts 5.5 KB 158 lines typescript

1import crypto from "node:crypto";2import fs from "node:fs";3import path from "node:path";4import { dataDir } from "./db";56/** Hachage Argon2id (implémentation native de Node ≥ 24.7). Format : $argon2id$m,t,p$sel$hash (base64url). */7const ARGON = { memory: 65536, passes: 3, parallelism: 1, tagLength: 32 };89type Argon2Sync = (10  algo: "argon2id",11  params: {12    message: Buffer;13    nonce: Buffer;14    parallelism: number;15    tagLength: number;16    memory: number;17    passes: number;18  },19) => Buffer;20const argon2Sync = (crypto as unknown as { argon2Sync: Argon2Sync }).argon2Sync;2122export function hashPassword(password: string): string {23  const salt = crypto.randomBytes(16);24  const hash = argon2Sync("argon2id", { message: Buffer.from(password, "utf8"), nonce: salt, ...ARGON });25  return `$argon2id$${ARGON.memory},${ARGON.passes},${ARGON.parallelism}$${salt.toString("base64url")}$${hash.toString("base64url")}`;26}2728export function verifyPassword(password: string, stored: string): boolean {29  const m = /^\$argon2id\$(\d+),(\d+),(\d+)\$([\w-]+)\$([\w-]+)$/.exec(stored);30  if (!m) return false;31  const expected = Buffer.from(m[5], "base64url");32  const hash = argon2Sync("argon2id", {33    message: Buffer.from(password, "utf8"),34    nonce: Buffer.from(m[4], "base64url"),35    memory: Number(m[1]),36    passes: Number(m[2]),37    parallelism: Number(m[3]),38    tagLength: expected.length,39  });40  return hash.length === expected.length && crypto.timingSafeEqual(hash, expected);41}4243/** Hachage factice pour égaliser le temps de réponse quand le compte n'existe pas. */44let dummy: string | null = null;45export function dummyVerify(password: string) {46  dummy ??= hashPassword(crypto.randomBytes(12).toString("hex"));47  verifyPassword(password, dummy);48}4950export function randomToken(bytes = 32): string {51  return crypto.randomBytes(bytes).toString("base64url");52}5354export function sha256(value: string): string {55  return crypto.createHash("sha256").update(value).digest("hex");56}5758/**59 * Secret d'application (chiffrement des secrets TOTP / jetons OAuth, empreintes).60 * APP_SECRET (env) ou, à défaut, un secret aléatoire généré à l'installation dans DATA_DIR/app.secret (0600).61 * Jamais versionné.62 */63let secretCache: Buffer | null = null;64export function appSecret(): Buffer {65  if (secretCache) return secretCache;66  const env = process.env.APP_SECRET;67  if (env && env.length >= 32) {68    secretCache = crypto.createHash("sha256").update(env).digest();69    return secretCache;70  }71  const file = path.join(dataDir(), "app.secret");72  if (!fs.existsSync(file)) {73    fs.writeFileSync(file, crypto.randomBytes(48).toString("base64url"), { mode: 0o600 });74  }75  secretCache = crypto.createHash("sha256").update(fs.readFileSync(file, "utf8").trim()).digest();76  return secretCache;77}7879export function encrypt(plain: string): string {80  const iv = crypto.randomBytes(12);81  const c = crypto.createCipheriv("aes-256-gcm", appSecret(), iv);82  const enc = Buffer.concat([c.update(plain, "utf8"), c.final()]);83  return `v1.${iv.toString("base64url")}.${c.getAuthTag().toString("base64url")}.${enc.toString("base64url")}`;84}8586export function decrypt(payload: string): string {87  const [v, iv, tag, enc] = payload.split(".");88  if (v !== "v1") throw new Error("Format chiffré inconnu");89  const d = crypto.createDecipheriv("aes-256-gcm", appSecret(), Buffer.from(iv, "base64url"));90  d.setAuthTag(Buffer.from(tag, "base64url"));91  return Buffer.concat([d.update(Buffer.from(enc, "base64url")), d.final()]).toString("utf8");92}9394/** Empreinte non réversible (IP…) salée par le secret d'application. */95export function hmacFingerprint(value: string): string {96  return crypto.createHmac("sha256", appSecret()).update(value).digest("hex").slice(0, 16);97}9899/* ---------- TOTP (RFC 6238, SHA-1, 6 chiffres, pas de 30 s) ---------- */100const B32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";101102export function base32Encode(buf: Buffer): string {103  let bits = 0;104  let value = 0;105  let out = "";106  for (const byte of buf) {107    value = (value << 8) | byte;108    bits += 8;109    while (bits >= 5) {110      out += B32[(value >>> (bits - 5)) & 31];111      bits -= 5;112    }113  }114  if (bits > 0) out += B32[(value << (5 - bits)) & 31];115  return out;116}117118export function base32Decode(s: string): Buffer {119  let bits = 0;120  let value = 0;121  const out: number[] = [];122  for (const ch of s.replace(/=+$/, "").toUpperCase().replace(/\s/g, "")) {123    const idx = B32.indexOf(ch);124    if (idx < 0) throw new Error("Base32 invalide");125    value = (value << 5) | idx;126    bits += 5;127    if (bits >= 8) {128      out.push((value >>> (bits - 8)) & 255);129      bits -= 8;130    }131  }132  return Buffer.from(out);133}134135export function totpCode(secretB32: string, timeMs = Date.now(), step = 30): string {136  const counter = Math.floor(timeMs / 1000 / step);137  const buf = Buffer.alloc(8);138  buf.writeBigUInt64BE(BigInt(counter));139  const h = crypto.createHmac("sha1", base32Decode(secretB32)).update(buf).digest();140  const o = h[h.length - 1] & 15;141  const code = ((h[o] & 127) << 24) | (h[o + 1] << 16) | (h[o + 2] << 8) | h[o + 3];142  return String(code % 1_000_000).padStart(6, "0");143}144145export function totpVerify(secretB32: string, code: string, timeMs = Date.now()): boolean {146  const clean = code.replace(/\s/g, "");147  if (!/^\d{6}$/.test(clean)) return false;148  for (const drift of [-1, 0, 1]) {149    const expected = totpCode(secretB32, timeMs + drift * 30_000);150    if (crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(clean))) return true;151  }152  return false;153}154155export function newTotpSecret(): string {156  return base32Encode(crypto.randomBytes(20));157}158
Files main
Menu

Theme