// OAuth 2.1 sans état (ADR 0005, point 5) : le serveur ne garde ni client, ni // code, ni jeton. Tout ce qu'il doit retrouver voyage dans ce qu'il a émis : // - l'identifiant d'un client porte ses adresses de retour, signées (HMAC) : les // connecteurs survivent à un redémarrage ; // - le code et les jetons sont chiffrés (AES-256-GCM) par une clé du serveur et // portent la clé de synchro et leur expiration. // Seule exception, en mémoire : la liste des codes déjà échangés, jusqu'à leur // expiration (usage unique). PKCE S256 est obligatoire. // // La clé de synchro n'apparaît jamais dans un message d'erreur ni dans un journal. import crypto from "node:crypto"; import fs from "node:fs"; import path from "node:path"; import { HttpError } from "./http.js"; export const TTL = { codeMs: 5 * 60e3, accessMs: 3600e3, refreshMs: 90 * 864e5, }; export const SCOPE = "ia-fit"; /** * Secret du serveur, créé au premier lancement dans DATA_DIR/.server-secret * (32 octets aléatoires, en hexadécimal, lisible par le seul propriétaire). Le * perdre ou le changer déconnecte toutes les IA (clients et jetons), sans * toucher aux journaux. * @param {string} dataDir * @returns {Buffer} */ export function loadServerSecret(dataDir) { const file = path.join(dataDir, ".server-secret"); try { fs.writeFileSync(file, crypto.randomBytes(32).toString("hex") + "\n", { flag: "wx", mode: 0o600 }); } catch (e) { if (/** @type {NodeJS.ErrnoException} */ (e).code !== "EEXIST") throw e; } const secret = Buffer.from(fs.readFileSync(file, "utf8").trim(), "hex"); if (secret.length !== 32) throw new Error(`${file} est illisible : 64 caractères hexadécimaux attendus.`); return secret; } /** Erreur OAuth : renvoyée au client (en JSON, ou vers son adresse de retour). */ export class OAuthError extends HttpError { /** * @param {string} error code OAuth (invalid_request, invalid_grant…) * @param {string} description * @param {{status?: number, redirect?: boolean}} [options] redirect : l'erreur peut être renvoyée à l'adresse de retour */ constructor(error, description, { status = 400, redirect = false } = {}) { super(status, error, description); this.redirect = redirect; } } /** @param {string} uri */ function isLoopback(uri) { try { const u = new URL(uri); return u.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname); } catch { return false; } } /** * Adresse de retour acceptable : https, http en boucle locale (outils en ligne * de commande), ou schéma privé d'application (« com.exemple.app: »). * @param {unknown} uri */ export function isAcceptableRedirect(uri) { if (typeof uri !== "string" || uri.length > 512) return false; let u; try { u = new URL(uri); } catch { return false; } if (u.hash) return false; if (u.protocol === "https:") return !!u.hostname; if (u.protocol === "http:") return isLoopback(uri); return /^[a-z][a-z0-9+-]*(\.[a-z0-9+-]+)+:$/.test(u.protocol); } /** * L'adresse demandée correspond-elle à une adresse enregistrée ? Égalité * exacte, sauf le port en boucle locale (RFC 8252, point 7.3). * @param {string[]} registered * @param {string} uri */ function redirectMatches(registered, uri) { if (registered.includes(uri)) return true; if (!isLoopback(uri)) return false; const strip = (/** @type {string} */ x) => { const u = new URL(x); u.port = ""; return u.toString(); }; return registered.some((r) => isLoopback(r) && strip(r) === strip(uri)); } /** * @param {{secret: Buffer, now?: () => number}} options */ export function createOAuth({ secret, now = Date.now }) { const sub = (/** @type {string} */ label) => crypto.createHmac("sha256", secret).update(label).digest(); const clientKey = sub("ia-fit/oauth-clients"); const tokenKey = sub("ia-fit/oauth-tokens"); /** Codes déjà échangés : identifiant → expiration. */ /** @type {Map} */ const usedCodes = new Map(); /** @param {string} payload */ const sign = (payload) => crypto.createHmac("sha256", clientKey).update(payload).digest("base64url"); /** Empreinte courte d'un client, portée par ses jetons. @param {string} clientId */ const clientTag = (clientId) => crypto.createHash("sha256").update(clientId).digest("base64url").slice(0, 16); /** @param {object} payload */ function seal(payload) { const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv("aes-256-gcm", tokenKey, iv); const body = Buffer.concat([cipher.update(JSON.stringify(payload), "utf8"), cipher.final()]); return Buffer.concat([iv, body, cipher.getAuthTag()]).toString("base64url"); } /** * @param {unknown} token * @param {string} type * @returns {Record|null} null si illisible, d'un autre type ou expiré */ function open(token, type) { if (typeof token !== "string" || token.length > 4096 || !/^[A-Za-z0-9_-]+$/.test(token)) return null; const raw = Buffer.from(token, "base64url"); if (raw.length < 12 + 16 + 2) return null; try { const decipher = crypto.createDecipheriv("aes-256-gcm", tokenKey, raw.subarray(0, 12)); decipher.setAuthTag(raw.subarray(raw.length - 16)); const p = JSON.parse(Buffer.concat([decipher.update(raw.subarray(12, raw.length - 16)), decipher.final()]).toString("utf8")); return p.t === type && typeof p.exp === "number" && p.exp > now() ? p : null; } catch { return null; } } /** * @param {unknown} clientId * @returns {{redirectUris: string[], name: string}|null} */ function readClient(clientId) { if (typeof clientId !== "string" || clientId.length > 8192) return null; const [payload, mac, extra] = clientId.split("."); if (!payload || !mac || extra !== undefined) return null; const expected = Buffer.from(sign(payload)); if (expected.length !== Buffer.byteLength(mac) || !crypto.timingSafeEqual(expected, Buffer.from(mac))) return null; try { const c = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")); return Array.isArray(c.r) ? { redirectUris: c.r, name: typeof c.n === "string" ? c.n : "" } : null; } catch { return null; } } /** * Vérifie une demande d'autorisation (GET ou POST /oauth/authorize). * Erreurs : sans `redirect` si le client ou l'adresse de retour sont en cause * (on ne renvoie rien vers une adresse inconnue), avec sinon. * @param {Record} p */ function checkAuthorization(p) { const client = readClient(p.client_id); if (!client) throw new OAuthError("invalid_client", "Client inconnu : l'enregistrement du connecteur n'est pas reconnu par ce serveur. Supprime puis rajoute le connecteur."); const redirectUri = p.redirect_uri; if (typeof redirectUri !== "string" || !redirectMatches(client.redirectUris, redirectUri)) throw new OAuthError("invalid_request", "Adresse de retour non enregistrée pour ce client."); if (p.response_type !== undefined && p.response_type !== "code") throw new OAuthError("unsupported_response_type", "Seul response_type=code est accepté.", { redirect: true }); if (typeof p.code_challenge !== "string" || !/^[A-Za-z0-9_-]{43,128}$/.test(p.code_challenge)) throw new OAuthError("invalid_request", "PKCE obligatoire : code_challenge manquant ou mal formé.", { redirect: true }); if (p.code_challenge_method !== "S256") throw new OAuthError("invalid_request", "PKCE : seule la méthode S256 est acceptée.", { redirect: true }); return { client, redirectUri, challenge: p.code_challenge, state: typeof p.state === "string" ? p.state : null }; } /** * @param {string} redirectUri * @param {Record} params */ function redirectTo(redirectUri, params) { const u = new URL(redirectUri); for (const [k, v] of Object.entries(params)) if (v !== null) u.searchParams.set(k, v); return u.toString(); } /** @param {string} syncKey @param {string} cid empreinte du client */ function issueTokens(syncKey, cid) { return { access_token: seal({ t: "access", k: syncKey, cid, exp: now() + TTL.accessMs }), token_type: "Bearer", expires_in: TTL.accessMs / 1000, refresh_token: seal({ t: "refresh", k: syncKey, cid, exp: now() + TTL.refreshMs }), scope: SCOPE, }; } return { readClient, checkAuthorization, /** * Enregistrement dynamique (RFC 7591), sans stockage. * @param {any} body */ register(body) { if (typeof body !== "object" || body === null) throw new OAuthError("invalid_client_metadata", "Corps JSON attendu."); const uris = body.redirect_uris; if (!Array.isArray(uris) || uris.length === 0 || uris.length > 10) throw new OAuthError("invalid_redirect_uri", "redirect_uris : une à dix adresses attendues."); for (const u of uris) if (!isAcceptableRedirect(u)) throw new OAuthError("invalid_redirect_uri", "Adresse de retour refusée : https, http://localhost ou schéma d'application attendu, sans fragment."); const name = typeof body.client_name === "string" ? body.client_name.slice(0, 80) : ""; const payload = Buffer.from(JSON.stringify({ r: uris, n: name })).toString("base64url"); const clientId = payload + "." + sign(payload); return { client_id: clientId, client_id_issued_at: Math.floor(now() / 1000), client_name: name, redirect_uris: uris, token_endpoint_auth_method: "none", grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], scope: SCOPE, }; }, /** * Émet un code pour une demande vérifiée, avec la clé de synchro (déjà * vérifiée contre le relais par l'appelant). * @param {ReturnType} request * @param {string} clientId * @param {string} syncKey au format normalisé * @returns {string} adresse de retour, avec le code et l'état */ authorize(request, clientId, syncKey) { const code = seal({ t: "code", k: syncKey, cid: clientTag(clientId), r: request.redirectUri, ch: request.challenge, j: crypto.randomBytes(12).toString("base64url"), exp: now() + TTL.codeMs, }); return redirectTo(request.redirectUri, { code, state: request.state }); }, redirectTo, /** * Point d'échange (/oauth/token). * @param {Record} p */ token(p) { if (p.grant_type === "authorization_code") { const c = open(p.code, "code"); if (!c) throw new OAuthError("invalid_grant", "Code inconnu ou expiré."); if (p.client_id !== undefined && clientTag(p.client_id) !== c.cid) throw new OAuthError("invalid_grant", "Ce code a été émis pour un autre client."); if (p.redirect_uri !== undefined && p.redirect_uri !== c.r) throw new OAuthError("invalid_grant", "redirect_uri différente de celle de la demande."); const verifier = p.code_verifier; if (typeof verifier !== "string" || !/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) throw new OAuthError("invalid_grant", "PKCE obligatoire : code_verifier manquant ou mal formé."); const computed = Buffer.from(crypto.createHash("sha256").update(verifier).digest("base64url")); const expected = Buffer.from(c.ch); if (computed.length !== expected.length || !crypto.timingSafeEqual(computed, expected)) throw new OAuthError("invalid_grant", "PKCE : code_verifier ne correspond pas."); const t = now(); for (const [j, exp] of usedCodes) if (exp <= t) usedCodes.delete(j); if (usedCodes.has(c.j)) throw new OAuthError("invalid_grant", "Code déjà utilisé."); usedCodes.set(c.j, c.exp); return issueTokens(c.k, c.cid); } if (p.grant_type === "refresh_token") { const r = open(p.refresh_token, "refresh"); if (!r) throw new OAuthError("invalid_grant", "Jeton de rafraîchissement inconnu ou expiré."); if (p.client_id !== undefined && clientTag(p.client_id) !== r.cid) throw new OAuthError("invalid_grant", "Ce jeton a été émis pour un autre client."); // Rotation sans révocation (sans état) : l'ancien jeton reste valable // jusqu'à son expiration. return issueTokens(r.k, r.cid); } throw new OAuthError("unsupported_grant_type", "grant_type : authorization_code ou refresh_token."); }, /** * Clé de synchro portée par un jeton d'accès valide, sinon null. * @param {string} token * @returns {string|null} */ verifyAccess(token) { const a = open(token, "access"); return a && typeof a.k === "string" ? a.k : null; }, /** Codes échangés gardés en mémoire (tests). */ get usedCodes() { return usedCodes.size; }, }; } /** @typedef {ReturnType} OAuth */