Lot 2 serveur : relais chiffré, OAuth sans état, MCP, synchro (sans l'interface) #10
+241
@@ -0,0 +1,241 @@
|
||||
// Routage du serveur d'IA-Fit : site statique, relais, OAuth et MCP sur la même
|
||||
// origine (ADR 0005). Aucun journal d'accès : ni adresse IP, ni identifiant de
|
||||
// journal, ni jeton ne sont écrits nulle part.
|
||||
|
||||
import { createStaticHandler } from "./static.js";
|
||||
import { createRelay } from "./relay.js";
|
||||
import { createOAuth, loadServerSecret, OAuthError } from "./oauth.js";
|
||||
import { createMcp } from "./mcp.js";
|
||||
import { clientIp, createRateLimiter } from "./rate-limit.js";
|
||||
import { HttpError, bearer, readBody, readJson, sendJson, sendText, BodyTooLarge, SECURITY_HEADERS } from "./http.js";
|
||||
import { deriveKeys, normalizeSyncKey } from "../app/domain/sync-crypto.js";
|
||||
|
||||
/** Corps maximal d'un dépôt sur le relais. */
|
||||
const RELAY_BODY_BYTES = 4 * 1024 * 1024;
|
||||
const SMALL_BODY_BYTES = 64 * 1024;
|
||||
const MCP_BODY_BYTES = 1024 * 1024;
|
||||
|
||||
const CORS = {
|
||||
"access-control-allow-origin": "*",
|
||||
"access-control-allow-methods": "GET, POST, OPTIONS",
|
||||
"access-control-allow-headers": "authorization, content-type, mcp-protocol-version, mcp-session-id",
|
||||
"access-control-expose-headers": "www-authenticate, mcp-protocol-version",
|
||||
"access-control-max-age": "86400",
|
||||
};
|
||||
|
||||
/**
|
||||
* @typedef {object} AppOptions
|
||||
* @property {string} dataDir
|
||||
* @property {string} siteDir
|
||||
* @property {string} publicUrl adresse publique, sans « / » final
|
||||
* @property {() => number} [now]
|
||||
* @property {Partial<import("./relay.js").LIMITS>} [limits]
|
||||
* @property {{max: number, windowMs: number}} [rate] toutes les routes dynamiques
|
||||
* @property {{max: number, windowMs: number}} [authorizeRate] POST /oauth/authorize
|
||||
*/
|
||||
|
||||
/** @param {AppOptions} options */
|
||||
export function createApp(options) {
|
||||
const now = options.now ?? Date.now;
|
||||
const publicUrl = options.publicUrl.replace(/\/+$/, "");
|
||||
const relay = createRelay(options.dataDir, { limits: options.limits, now });
|
||||
const oauth = createOAuth({ secret: loadServerSecret(options.dataDir), now });
|
||||
const mcp = createMcp({ relay, publicUrl, now: () => new Date(now()) });
|
||||
const serveStatic = createStaticHandler(options.siteDir);
|
||||
const limiter = createRateLimiter({ ...(options.rate ?? { max: 300, windowMs: 60e3 }), now });
|
||||
const authorizeLimiter = createRateLimiter({ ...(options.authorizeRate ?? { max: 20, windowMs: 60e3 }), now });
|
||||
const resourceMetadata = `${publicUrl}/.well-known/oauth-protected-resource/mcp`;
|
||||
|
||||
/**
|
||||
* @param {import("node:http").IncomingMessage} req
|
||||
* @param {import("node:http").ServerResponse} res
|
||||
*/
|
||||
async function route(req, res) {
|
||||
const url = new URL(req.url ?? "/", "http://localhost");
|
||||
const p = url.pathname;
|
||||
const dynamic = p.startsWith("/api/") || p.startsWith("/oauth/") || p === "/mcp" || p.startsWith("/.well-known/");
|
||||
if (!dynamic) return serveStatic(req, res, p);
|
||||
|
||||
const ip = clientIp(req);
|
||||
const wait = limiter.hit(ip);
|
||||
if (wait) throw new HttpError(429, "rate_limited", `Trop de requêtes : réessaie dans ${wait} s.`);
|
||||
if (req.method === "OPTIONS") return sendJson(res, 204, undefined, CORS);
|
||||
|
||||
if (p === "/.well-known/oauth-protected-resource" || p === "/.well-known/oauth-protected-resource/mcp")
|
||||
return sendJson(res, 200, {
|
||||
resource: `${publicUrl}/mcp`,
|
||||
authorization_servers: [publicUrl],
|
||||
bearer_methods_supported: ["header"],
|
||||
scopes_supported: ["ia-fit"],
|
||||
resource_name: "IA-Fit",
|
||||
resource_documentation: `${publicUrl}/ia.md`,
|
||||
}, CORS);
|
||||
if (p === "/.well-known/oauth-authorization-server" || p === "/.well-known/oauth-authorization-server/mcp")
|
||||
return sendJson(res, 200, {
|
||||
issuer: publicUrl,
|
||||
authorization_endpoint: `${publicUrl}/oauth/authorize`,
|
||||
token_endpoint: `${publicUrl}/oauth/token`,
|
||||
registration_endpoint: `${publicUrl}/oauth/register`,
|
||||
response_types_supported: ["code"],
|
||||
grant_types_supported: ["authorization_code", "refresh_token"],
|
||||
code_challenge_methods_supported: ["S256"],
|
||||
token_endpoint_auth_methods_supported: ["none"],
|
||||
scopes_supported: ["ia-fit"],
|
||||
}, CORS);
|
||||
|
||||
if (p === "/oauth/register") {
|
||||
if (req.method !== "POST") throw new HttpError(405, "method_not_allowed");
|
||||
return sendJson(res, 201, oauth.register(await readJson(req, SMALL_BODY_BYTES)), CORS);
|
||||
}
|
||||
|
||||
if (p === "/oauth/authorize") {
|
||||
if (req.method === "GET") return authorizeGet(url, res);
|
||||
if (req.method === "POST") {
|
||||
const wait2 = authorizeLimiter.hit(ip);
|
||||
if (wait2) throw new HttpError(429, "rate_limited", `Trop de tentatives : réessaie dans ${wait2} s.`);
|
||||
return authorizePost(await readJson(req, SMALL_BODY_BYTES), res);
|
||||
}
|
||||
throw new HttpError(405, "method_not_allowed");
|
||||
}
|
||||
|
||||
if (p === "/oauth/token") {
|
||||
if (req.method !== "POST") throw new HttpError(405, "method_not_allowed");
|
||||
return sendJson(res, 200, oauth.token(await readForm(req)), CORS);
|
||||
}
|
||||
|
||||
if (p === "/mcp") return handleMcp(req, res);
|
||||
|
||||
const m = /^\/api\/journals\/([^/]+)\/events$/.exec(p);
|
||||
if (m) {
|
||||
const id = m[1];
|
||||
const token = bearer(req);
|
||||
if (req.method === "GET") {
|
||||
const after = Number(url.searchParams.get("after") ?? 0);
|
||||
if (!Number.isInteger(after) || after < 0) throw new HttpError(400, "invalid_request", "'after' doit être un entier positif.");
|
||||
return sendJson(res, 200, await relay.read(id, token, after));
|
||||
}
|
||||
if (req.method === "POST") {
|
||||
// La clé d'accès est vérifiée avant de lire un gros corps.
|
||||
if (!token) throw new HttpError(401, "unauthorized", "Clé d'accès manquante.");
|
||||
const body = await readJson(req, RELAY_BODY_BYTES);
|
||||
return sendJson(res, 200, await relay.append(id, token, body));
|
||||
}
|
||||
throw new HttpError(405, "method_not_allowed");
|
||||
}
|
||||
throw new HttpError(404, "not_found", "Adresse inconnue.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Première étape de l'autorisation : on vérifie le client, puis on passe la
|
||||
* main à la page de l'app, qui retrouve la clé de synchro du navigateur.
|
||||
* @param {URL} url
|
||||
* @param {import("node:http").ServerResponse} res
|
||||
*/
|
||||
function authorizeGet(url, res) {
|
||||
const params = Object.fromEntries(url.searchParams);
|
||||
let request;
|
||||
try {
|
||||
request = oauth.checkAuthorization(params);
|
||||
} catch (e) {
|
||||
if (e instanceof OAuthError && e.redirect && typeof params.redirect_uri === "string") {
|
||||
res.writeHead(302, { ...SECURITY_HEADERS, "cache-control": "no-store",
|
||||
location: oauth.redirectTo(params.redirect_uri, { error: e.error, error_description: e.message, state: params.state ?? null }) });
|
||||
return res.end();
|
||||
}
|
||||
if (e instanceof OAuthError) return sendText(res, 400, `Autorisation impossible : ${e.message}`);
|
||||
throw e;
|
||||
}
|
||||
const forward = new URLSearchParams(url.searchParams);
|
||||
forward.set("client_name", request.client.name);
|
||||
res.writeHead(302, { ...SECURITY_HEADERS, "cache-control": "no-store", location: `/#/connecter-ia?${forward}` });
|
||||
res.end();
|
||||
}
|
||||
|
||||
/**
|
||||
* Seconde étape, appelée par la page de l'app avec la clé de synchro.
|
||||
* @param {any} body
|
||||
* @param {import("node:http").ServerResponse} res
|
||||
*/
|
||||
async function authorizePost(body, res) {
|
||||
if (typeof body !== "object" || body === null) throw new OAuthError("invalid_request", "Corps JSON attendu.");
|
||||
const request = oauth.checkAuthorization(body);
|
||||
const syncKey = normalizeSyncKey(body.sync_key);
|
||||
if (!syncKey) throw new OAuthError("invalid_sync_key", "Clé de synchro invalide.");
|
||||
const keys = await deriveKeys(syncKey);
|
||||
if (!(await relay.owns(keys.journalId, keys.authToken)))
|
||||
throw new OAuthError("unknown_journal", "Aucun journal synchronisé pour cette clé : active d'abord la synchro dans l'app.");
|
||||
return sendJson(res, 200, { redirect: oauth.authorize(request, body.client_id, syncKey) });
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("node:http").IncomingMessage} req
|
||||
* @param {import("node:http").ServerResponse} res
|
||||
*/
|
||||
async function handleMcp(req, res) {
|
||||
const token = bearer(req);
|
||||
const syncKey = token ? oauth.verifyAccess(token) : null;
|
||||
if (!syncKey) {
|
||||
const challenge = `Bearer resource_metadata="${resourceMetadata}"` + (token ? `, error="invalid_token"` : "");
|
||||
return sendJson(res, 401, { error: token ? "invalid_token" : "unauthorized" }, { ...CORS, "www-authenticate": challenge });
|
||||
}
|
||||
if (req.method !== "POST") return sendJson(res, 405, { error: "method_not_allowed" }, { ...CORS, allow: "POST" });
|
||||
let msg;
|
||||
try {
|
||||
msg = JSON.parse(await readBody(req, MCP_BODY_BYTES));
|
||||
} catch (e) {
|
||||
if (e instanceof BodyTooLarge) throw new HttpError(413, "payload_too_large");
|
||||
return sendJson(res, 400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "JSON invalide." } }, CORS);
|
||||
}
|
||||
if (Array.isArray(msg)) {
|
||||
const out = [];
|
||||
for (const m of msg) {
|
||||
const r = await mcp.handle(m, syncKey);
|
||||
if (r) out.push(r);
|
||||
}
|
||||
return out.length ? sendJson(res, 200, out, CORS) : sendJson(res, 202, undefined, CORS);
|
||||
}
|
||||
const r = await mcp.handle(msg, syncKey);
|
||||
return r ? sendJson(res, 200, r, CORS) : sendJson(res, 202, undefined, CORS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Corps d'une requête /oauth/token : formulaire (la norme) ou JSON.
|
||||
* @param {import("node:http").IncomingMessage} req
|
||||
* @returns {Promise<Record<string, string|undefined>>}
|
||||
*/
|
||||
async function readForm(req) {
|
||||
if ((req.headers["content-type"] ?? "").includes("application/json")) {
|
||||
const body = await readJson(req, SMALL_BODY_BYTES);
|
||||
return typeof body === "object" && body !== null ? body : {};
|
||||
}
|
||||
let text;
|
||||
try {
|
||||
text = await readBody(req, SMALL_BODY_BYTES);
|
||||
} catch (e) {
|
||||
if (e instanceof BodyTooLarge) throw new HttpError(413, "payload_too_large");
|
||||
throw e;
|
||||
}
|
||||
return Object.fromEntries(new URLSearchParams(text));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("node:http").IncomingMessage} req
|
||||
* @param {import("node:http").ServerResponse} res
|
||||
*/
|
||||
async function handler(req, res) {
|
||||
try {
|
||||
await route(req, res);
|
||||
} catch (e) {
|
||||
if (res.headersSent) return res.destroy();
|
||||
if (e instanceof HttpError) {
|
||||
const cors = req.url?.startsWith("/oauth/") || req.url?.startsWith("/mcp") ? CORS : {};
|
||||
return sendJson(res, e.status, { error: e.error, ...(e.description ? { error_description: e.description } : {}) }, cors);
|
||||
}
|
||||
// Message seul : ni adresse, ni requête, ni jeton.
|
||||
console.error("Erreur interne :", e instanceof Error ? e.message : e);
|
||||
sendJson(res, 500, { error: "server_error" });
|
||||
}
|
||||
}
|
||||
|
||||
return { handler, relay, oauth, mcp };
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
// Petits outils HTTP partagés par les routes du serveur.
|
||||
|
||||
/** En-têtes de sécurité de toutes les réponses, repris du Caddyfile du lot 1. */
|
||||
export const CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; worker-src 'self'; manifest-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
|
||||
|
||||
export const SECURITY_HEADERS = {
|
||||
"x-content-type-options": "nosniff",
|
||||
"referrer-policy": "no-referrer",
|
||||
"content-security-policy": CSP,
|
||||
};
|
||||
|
||||
/** Corps trop gros : le client reçoit 413. */
|
||||
export class BodyTooLarge extends Error {}
|
||||
|
||||
/** Erreur à renvoyer telle quelle au client (code HTTP, corps JSON). */
|
||||
export class HttpError extends Error {
|
||||
/** @param {number} status @param {string} error @param {string} [description] */
|
||||
constructor(status, error, description) {
|
||||
super(description ?? error);
|
||||
this.status = status;
|
||||
this.error = error;
|
||||
this.description = description;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lit le corps d'une requête, en refusant au-delà de `limit` octets.
|
||||
* @param {import("node:http").IncomingMessage} req
|
||||
* @param {number} limit
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
export function readBody(req, limit) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const declared = Number(req.headers["content-length"]);
|
||||
if (declared > limit) {
|
||||
req.resume();
|
||||
return reject(new BodyTooLarge());
|
||||
}
|
||||
/** @type {Buffer[]} */
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
let failed = false;
|
||||
req.on("data", (/** @type {Buffer} */ chunk) => {
|
||||
if (failed) return;
|
||||
size += chunk.length;
|
||||
if (size > limit) {
|
||||
failed = true;
|
||||
reject(new BodyTooLarge());
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
req.on("end", () => failed || resolve(Buffer.concat(chunks).toString("utf8")));
|
||||
req.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Lit un corps JSON ; lève une HttpError 400 s'il est illisible.
|
||||
* @param {import("node:http").IncomingMessage} req
|
||||
* @param {number} limit
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
export async function readJson(req, limit) {
|
||||
let text;
|
||||
try {
|
||||
text = await readBody(req, limit);
|
||||
} catch (e) {
|
||||
if (e instanceof BodyTooLarge) throw new HttpError(413, "payload_too_large", "Requête trop volumineuse.");
|
||||
throw e;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(text || "null");
|
||||
} catch {
|
||||
throw new HttpError(400, "invalid_request", "Corps JSON illisible.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Envoie une réponse JSON (ou vide pour 202 et 204), jamais mise en cache.
|
||||
* @param {import("node:http").ServerResponse} res
|
||||
* @param {number} status
|
||||
* @param {unknown} body
|
||||
* @param {Record<string, string>} [headers]
|
||||
*/
|
||||
export function sendJson(res, status, body, headers = {}) {
|
||||
const text = body === undefined ? "" : JSON.stringify(body);
|
||||
res.writeHead(status, {
|
||||
...SECURITY_HEADERS,
|
||||
"cache-control": "no-store",
|
||||
...(text ? { "content-type": "application/json; charset=utf-8", "content-length": Buffer.byteLength(text) } : {}),
|
||||
...headers,
|
||||
});
|
||||
res.end(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("node:http").ServerResponse} res
|
||||
* @param {number} status
|
||||
* @param {string} text
|
||||
* @param {Record<string, string>} [headers]
|
||||
*/
|
||||
export function sendText(res, status, text, headers = {}) {
|
||||
res.writeHead(status, {
|
||||
...SECURITY_HEADERS,
|
||||
"cache-control": "no-store",
|
||||
"content-type": "text/plain; charset=utf-8",
|
||||
"content-length": Buffer.byteLength(text),
|
||||
...headers,
|
||||
});
|
||||
res.end(text);
|
||||
}
|
||||
|
||||
/** Jeton porteur de l'en-tête Authorization, ou "" s'il n'y en a pas. @param {import("node:http").IncomingMessage} req */
|
||||
export function bearer(req) {
|
||||
const m = /^Bearer\s+(\S+)\s*$/i.exec(req.headers.authorization ?? "");
|
||||
return m ? m[1] : "";
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env node
|
||||
// Point d'entrée du serveur d'IA-Fit (lot 2, ADR 0005 et 0007) : Node seul,
|
||||
// sans dépendance.
|
||||
//
|
||||
// Variables :
|
||||
// PORT port d'écoute (3000)
|
||||
// DATA_DIR journaux chiffrés et secret du serveur (/data en production)
|
||||
// SITE_DIR site assemblé par make site (/srv/site en production)
|
||||
// PUBLIC_URL adresse publique (https://ia-fit.sans.pub), pour OAuth et MCP
|
||||
|
||||
import http from "node:http";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createApp } from "./app.js";
|
||||
|
||||
const PORT = Number(process.env.PORT ?? 3000);
|
||||
const DATA_DIR = path.resolve(process.env.DATA_DIR ?? "data");
|
||||
const SITE_DIR = path.resolve(process.env.SITE_DIR ?? "build/site");
|
||||
const PUBLIC_URL = (process.env.PUBLIC_URL ?? "https://ia-fit.sans.pub").replace(/\/+$/, "");
|
||||
|
||||
/** @param {string} message */
|
||||
function fail(message) {
|
||||
console.error("IA-Fit ne démarre pas : " + message);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Refus de démarrer sans dossier de données inscriptible : sinon le premier
|
||||
// dépôt échouerait, et le secret OAuth ne pourrait pas être gardé.
|
||||
try {
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
const probe = path.join(DATA_DIR, `.ecriture-${process.pid}`);
|
||||
fs.writeFileSync(probe, "");
|
||||
fs.unlinkSync(probe);
|
||||
} catch (e) {
|
||||
fail(`DATA_DIR (${DATA_DIR}) n'est pas inscriptible : ${e instanceof Error ? e.message : e}`);
|
||||
}
|
||||
if (!fs.existsSync(path.join(SITE_DIR, "index.html"))) fail(`SITE_DIR (${SITE_DIR}) ne contient pas index.html (make site).`);
|
||||
if (!/^https?:\/\/[^/]+$/.test(PUBLIC_URL)) fail(`PUBLIC_URL (${PUBLIC_URL}) doit être de la forme https://domaine, sans chemin.`);
|
||||
|
||||
const app = createApp({ dataDir: DATA_DIR, siteDir: SITE_DIR, publicUrl: PUBLIC_URL });
|
||||
const server = http.createServer(app.handler);
|
||||
server.headersTimeout = 20e3;
|
||||
server.requestTimeout = 60e3;
|
||||
|
||||
// Effacement des journaux inactifs : au démarrage, puis chaque jour.
|
||||
const purge = () => app.relay.purgeInactive()
|
||||
.then((n) => n && console.log(`Journaux inactifs effacés : ${n}`))
|
||||
.catch((e) => console.error("Effacement des journaux inactifs :", e instanceof Error ? e.message : e));
|
||||
purge();
|
||||
setInterval(purge, 864e5).unref();
|
||||
|
||||
server.listen(PORT, () => console.log(`IA-Fit : port ${PORT}, site ${SITE_DIR}, données ${DATA_DIR}, adresse ${PUBLIC_URL}`));
|
||||
|
||||
for (const signal of /** @type {const} */ (["SIGTERM", "SIGINT"]))
|
||||
process.on(signal, () => server.close(() => process.exit(0)));
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
// Serveur MCP (ADR 0005, points 5 et 6) : JSON-RPC 2.0 sur HTTP POST.
|
||||
//
|
||||
// À chaque appel d'outil : la clé de synchro (tirée du jeton) donne les clés du
|
||||
// journal ; on lit et déchiffre tous ses blocs en mémoire, on replie l'état avec
|
||||
// le même code que l'app (foldEvents), on répond, puis tout est oublié. Les
|
||||
// outils qui modifient n'écrivent qu'une proposition (ProgramProposed, source
|
||||
// « ai »), que l'utilisateur adopte ou refuse dans l'app.
|
||||
|
||||
import { createEvent, validateEvent } from "../app/domain/events.js";
|
||||
import { foldEvents } from "../app/domain/state.js";
|
||||
import { validateProgram } from "../app/domain/program.js";
|
||||
import { validateProfile } from "../app/domain/profile.js";
|
||||
import { exerciseHistory, attendance } from "../app/domain/analysis.js";
|
||||
import { weightTrend, weightMilestones } from "../app/domain/weight.js";
|
||||
import { addDays, localISO } from "../app/domain/dates.js";
|
||||
import { deriveKeys, decryptEvent, encryptEvent } from "../app/domain/sync-crypto.js";
|
||||
|
||||
/** Versions du protocole comprises ; la première est celle d'Atelier. */
|
||||
export const PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26"];
|
||||
|
||||
export const PROPOSAL_SAVED = "Proposition enregistrée : l'utilisateur la validera dans l'app.";
|
||||
|
||||
/** Erreur d'outil : renvoyée à l'IA comme résultat en erreur, pour qu'elle corrige. */
|
||||
class ToolError extends Error {
|
||||
/** @param {string} message @param {string[]} [problems] */
|
||||
constructor(message, problems = []) {
|
||||
super(problems.length ? message + "\n- " + problems.join("\n- ") : message);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {string} publicUrl */
|
||||
function instructions(publicUrl) {
|
||||
return `IA-Fit suit le programme de musculation de l'utilisateur. Commence toujours par get_overview : programme, profil (objectif, matériel, contraintes de sécurité à respecter absolument), mode, propositions en attente et assiduité. Tu ne modifies jamais rien directement : propose_program, propose_session_change et propose_profile enregistrent une proposition, avec ta raison, que l'utilisateur voit avec un aperçu des changements et valide (ou refuse) dans l'app. Explique-lui ce que tu proposes avant de l'enregistrer. Le format du programme et du profil, ses règles et la bibliothèque d'exercices (champ 'ref') sont décrits dans ${publicUrl}/ia.md : lis-le avant ta première proposition. Une proposition invalide est refusée avec la liste des problèmes : corrige-les et recommence.`;
|
||||
}
|
||||
|
||||
const DAYS = { type: "integer", minimum: 1, maximum: 3650 };
|
||||
|
||||
const TOOLS = [
|
||||
{
|
||||
name: "get_overview",
|
||||
description: "Vue d'ensemble, à lire en premier : programme courant (séances et exercices), profil (objectif, matériel, contraintes de sécurité), mode (progression, maintien, récupération), propositions en attente de validation, assiduité des 4 dernières semaines, dernière séance et dernière pesée.",
|
||||
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
},
|
||||
{
|
||||
name: "get_program",
|
||||
description: "Programme courant complet (JSON au format IA-Fit, celui à reprendre pour une proposition), avec les charges de travail actuelles par clé « séance-exercice » et l'historique des versions du programme.",
|
||||
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
},
|
||||
{
|
||||
name: "get_training_history",
|
||||
description: "Séances réellement faites sur les derniers jours (28 par défaut) : date, séance, exercices, charge, répétitions et ressenti de chaque série (easy, ok, hard, failure), ainsi que les jours prévus marqués non faits.",
|
||||
inputSchema: { type: "object", properties: { days: { ...DAYS, description: "Nombre de jours en arrière (28 par défaut)." } }, additionalProperties: false },
|
||||
},
|
||||
{
|
||||
name: "get_exercise_progress",
|
||||
description: "Évolution d'un exercice, séance après séance : charge, durée, séries, meilleure série, répétitions totales, volume et ressenti dominant. exercise_id est la 'ref' de l'exercice dans le programme (par exemple « squat »), ou son nom s'il n'a pas de ref.",
|
||||
inputSchema: { type: "object", properties: { exercise_id: { type: "string", description: "ref de l'exercice, sinon son nom." } }, required: ["exercise_id"], additionalProperties: false },
|
||||
},
|
||||
{
|
||||
name: "get_body_weight",
|
||||
description: "Pesées des derniers jours (90 par défaut), tendance en kg par semaine sur les 8 dernières semaines mesurées et repères (minimum, dernière fois sous le poids actuel).",
|
||||
inputSchema: { type: "object", properties: { days: { ...DAYS, description: "Nombre de jours en arrière (90 par défaut)." } }, additionalProperties: false },
|
||||
},
|
||||
{
|
||||
name: "propose_program",
|
||||
description: "Propose un nouveau programme complet (et, si besoin, un nouveau profil complet). Rien n'est appliqué : l'utilisateur voit l'aperçu des changements et valide dans l'app. Format : voir ia.md. Refusé avec la liste des problèmes si le programme ou le profil est invalide.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
program: { type: "object", description: "Programme complet au format IA-Fit : {name, sessions: [{key, name, exercises: [{ref|name, sets, reps, rest, …}]}], activities?, cardio?, rules?}." },
|
||||
profile: { type: "object", description: "Profil complet, facultatif : {goal, context, equipment[], constraints[], heightCm, sessionMinutes}." },
|
||||
reason: { type: "string", description: "Pourquoi ce changement, en une ou deux phrases adressées à l'utilisateur." },
|
||||
},
|
||||
required: ["program", "reason"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "propose_session_change",
|
||||
description: "Propose de remplacer une séance du programme courant (ou d'en ajouter une si la clé n'existe pas), le reste du programme étant gardé tel quel. Rien n'est appliqué sans la validation de l'utilisateur.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
key: { type: "string", description: "Clé de la séance (« A », « B »…)." },
|
||||
session: { type: "object", description: "Séance complète : {key?, name, subtitle?, exercises: [...]} ; sa clé, si elle est donnée, doit être 'key'." },
|
||||
reason: { type: "string", description: "Pourquoi ce changement." },
|
||||
},
|
||||
required: ["key", "session", "reason"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "propose_profile",
|
||||
description: "Propose un nouveau profil complet (objectif, contexte, matériel, contraintes, taille, durée de séance), le programme courant restant le même. Rien n'est appliqué sans la validation de l'utilisateur.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
profile: { type: "object", description: "Profil complet : {goal, context, equipment[], constraints[], heightCm, sessionMinutes}." },
|
||||
reason: { type: "string", description: "Pourquoi ce changement." },
|
||||
},
|
||||
required: ["profile", "reason"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* @param {{relay: import("./relay.js").Relay, publicUrl: string, now?: () => Date}} options
|
||||
*/
|
||||
export function createMcp({ relay, publicUrl, now = () => new Date() }) {
|
||||
/**
|
||||
* Ouvre le journal en mémoire, le temps d'une requête.
|
||||
* @param {string} syncKey
|
||||
*/
|
||||
async function openJournal(syncKey) {
|
||||
const keys = await deriveKeys(syncKey);
|
||||
/** @type {import("../app/domain/events.js").DomainEvent[]} */
|
||||
const events = [];
|
||||
let unreadable = 0;
|
||||
let after = 0;
|
||||
for (;;) {
|
||||
const page = await relay.read(keys.journalId, keys.authToken, after);
|
||||
for (const { blob } of page.events) {
|
||||
try {
|
||||
const e = await decryptEvent(keys.encKey, blob);
|
||||
if (validateEvent(e) === null) events.push(/** @type {any} */ (e));
|
||||
else unreadable++;
|
||||
} catch {
|
||||
unreadable++;
|
||||
}
|
||||
}
|
||||
after = page.events.length ? page.events[page.events.length - 1].seq : page.last;
|
||||
if (!page.more) break;
|
||||
}
|
||||
const byId = new Map(events.map((e) => [e.id, e]));
|
||||
const state = foldEvents([...byId.values()]);
|
||||
return {
|
||||
state,
|
||||
unreadable,
|
||||
/**
|
||||
* Enregistre une proposition de l'IA.
|
||||
* @param {{program: unknown, profile?: unknown, reason: string}} data
|
||||
*/
|
||||
async propose(data) {
|
||||
const event = createEvent("ProgramProposed", /** @type {any} */ ({ ...data, source: "ai" }), { device: "mcp", at: now().toISOString() });
|
||||
await relay.append(keys.journalId, keys.authToken, [await encryptEvent(keys.encKey, event)]);
|
||||
return event;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const today = () => localISO(now());
|
||||
|
||||
/** @param {unknown} reason */
|
||||
function checkReason(reason) {
|
||||
if (typeof reason !== "string" || !reason.trim()) throw new ToolError("'reason' manquant : explique en une phrase pourquoi tu proposes ce changement.");
|
||||
return reason.trim();
|
||||
}
|
||||
|
||||
/** @param {unknown} days @param {number} fallback */
|
||||
const daysArg = (days, fallback) => (Number.isInteger(days) && /** @type {number} */ (days) > 0 ? Math.min(/** @type {number} */ (days), 3650) : fallback);
|
||||
|
||||
/** @param {Awaited<ReturnType<typeof openJournal>>} j @param {{program: unknown, profile?: unknown, reason: string}} data */
|
||||
async function propose(j, data) {
|
||||
const problems = validateProgram(data.program).map((x) => "programme : " + x);
|
||||
if (data.profile !== undefined) problems.push(...validateProfile(data.profile).map((x) => "profil : " + x));
|
||||
if (problems.length) throw new ToolError("Proposition refusée, rien n'a été enregistré. Corrige :", problems);
|
||||
const event = await j.propose(data);
|
||||
return { message: PROPOSAL_SAVED, proposalId: event.id };
|
||||
}
|
||||
|
||||
/** @type {Record<string, (j: Awaited<ReturnType<typeof openJournal>>, args: Record<string, any>) => Promise<unknown>|unknown>} */
|
||||
const run = {
|
||||
get_overview(j) {
|
||||
const s = j.state;
|
||||
const day = today();
|
||||
const att = attendance(s, addDays(day, -27), day);
|
||||
const last = s.sessions.at(-1);
|
||||
return {
|
||||
today: day,
|
||||
program: s.program && {
|
||||
name: s.program.name,
|
||||
subtitle: s.program.subtitle ?? null,
|
||||
sessions: s.program.sessions.map((x) => ({
|
||||
key: x.key, name: x.name,
|
||||
exercises: x.exercises.map((e) => `${e.ref ?? e.name} ${e.sets} × ${e.reps}`),
|
||||
})),
|
||||
activities: (s.program.activities ?? []).map((a) => a.name),
|
||||
versions: s.programVersions.length,
|
||||
},
|
||||
profile: s.profile,
|
||||
mode: s.mode,
|
||||
pendingProposals: s.proposals.map((p) => ({ id: p.id, at: p.at, source: p.source, reason: p.reason, programName: p.program.name, withProfile: !!p.profile })),
|
||||
attendanceLast4Weeks: att,
|
||||
lastSession: last ? { date: last.date, kind: last.kind, ref: last.ref, name: last.name } : null,
|
||||
lastWeight: s.weights.at(-1) ?? null,
|
||||
planSettings: s.planSettings,
|
||||
notes: [
|
||||
...(s.program ? [] : ["Aucun programme adopté : construis-en un avec propose_program (format : ia.md)."]),
|
||||
...(s.proposals.length ? ["Des propositions attendent la décision de l'utilisateur : une nouvelle proposition s'ajoute à la liste."] : []),
|
||||
...(j.unreadable ? [`${j.unreadable} événement(s) illisibles ignorés.`] : []),
|
||||
],
|
||||
};
|
||||
},
|
||||
get_program(j) {
|
||||
const s = j.state;
|
||||
if (!s.program) return { program: null, note: "Aucun programme adopté : propose_program pour en construire un." };
|
||||
return { program: s.program, workingLoads: s.workingLoads, trackingOverrides: s.trackingOverrides, versions: s.programVersions };
|
||||
},
|
||||
get_training_history(j, args) {
|
||||
const day = today();
|
||||
const since = addDays(day, -daysArg(args.days, 28));
|
||||
return {
|
||||
from: since, to: day,
|
||||
sessions: j.state.sessions.filter((x) => x.date >= since && x.date <= day).map(({ loggedAt, ...rest }) => rest),
|
||||
skippedDays: j.state.skippedDays.filter((d) => d >= since && d <= day),
|
||||
};
|
||||
},
|
||||
get_exercise_progress(j, args) {
|
||||
if (typeof args.exercise_id !== "string" || !args.exercise_id.trim()) throw new ToolError("'exercise_id' manquant.");
|
||||
const points = exerciseHistory(j.state, args.exercise_id);
|
||||
if (points.length) return { exercise_id: args.exercise_id, points };
|
||||
const known = [...new Set(j.state.sessions.flatMap((x) => x.exercises.map((e) => e.id)))].sort();
|
||||
return { exercise_id: args.exercise_id, points: [], note: "Aucune séance avec cet exercice.", knownExerciseIds: known };
|
||||
},
|
||||
get_body_weight(j, args) {
|
||||
const day = today();
|
||||
const since = addDays(day, -daysArg(args.days, 90));
|
||||
const weights = j.state.weights;
|
||||
return {
|
||||
from: since, to: day,
|
||||
weights: weights.filter((w) => w.date >= since && w.date <= day),
|
||||
trend: weightTrend(weights, { today: day }),
|
||||
milestones: weightMilestones(weights),
|
||||
heightCm: j.state.profile.heightCm,
|
||||
};
|
||||
},
|
||||
propose_program(j, args) {
|
||||
const data = { program: args.program, reason: checkReason(args.reason) };
|
||||
if (args.profile !== undefined) Object.assign(data, { profile: args.profile });
|
||||
return propose(j, data);
|
||||
},
|
||||
propose_session_change(j, args) {
|
||||
const reason = checkReason(args.reason);
|
||||
const program = j.state.program;
|
||||
if (!program) throw new ToolError("Aucun programme courant à modifier : utilise propose_program avec un programme complet.");
|
||||
if (typeof args.key !== "string" || !args.key.trim()) throw new ToolError("'key' manquant : la clé de la séance (« A »).");
|
||||
const session = args.session;
|
||||
if (typeof session !== "object" || session === null || Array.isArray(session)) throw new ToolError("'session' doit être un objet séance.");
|
||||
if (session.key !== undefined && session.key !== args.key) throw new ToolError(`La séance porte la clé « ${session.key} », différente de 'key' (« ${args.key} »).`);
|
||||
const copy = structuredClone(program);
|
||||
const merged = { ...session, key: args.key };
|
||||
const i = copy.sessions.findIndex((x) => x.key === args.key);
|
||||
if (i >= 0) copy.sessions[i] = merged;
|
||||
else copy.sessions.push(merged);
|
||||
return propose(j, { program: copy, reason });
|
||||
},
|
||||
propose_profile(j, args) {
|
||||
const reason = checkReason(args.reason);
|
||||
if (!j.state.program) throw new ToolError("Aucun programme courant : une proposition porte toujours un programme. Utilise propose_program avec le programme et le profil.");
|
||||
return propose(j, { program: structuredClone(j.state.program), profile: args.profile, reason });
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Traite un message JSON-RPC. Renvoie null pour une notification.
|
||||
* @param {any} msg
|
||||
* @param {string} syncKey
|
||||
*/
|
||||
async function handle(msg, syncKey) {
|
||||
const id = msg && typeof msg === "object" && "id" in msg ? msg.id : null;
|
||||
const result = (/** @type {unknown} */ r) => ({ jsonrpc: "2.0", id, result: r });
|
||||
const error = (/** @type {number} */ code, /** @type {string} */ message) => ({ jsonrpc: "2.0", id, error: { code, message } });
|
||||
if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0" || typeof msg.method !== "string")
|
||||
return error(-32600, "Requête JSON-RPC invalide.");
|
||||
const isNotification = !("id" in msg);
|
||||
const params = msg.params ?? {};
|
||||
switch (msg.method) {
|
||||
case "initialize": {
|
||||
const asked = params.protocolVersion;
|
||||
return result({
|
||||
protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],
|
||||
capabilities: { tools: { listChanged: false } },
|
||||
serverInfo: { name: "ia-fit", title: "IA-Fit", version: "2.0.0" },
|
||||
instructions: instructions(publicUrl),
|
||||
});
|
||||
}
|
||||
case "ping":
|
||||
return isNotification ? null : result({});
|
||||
case "tools/list":
|
||||
return result({ tools: TOOLS });
|
||||
case "tools/call": {
|
||||
const tool = run[params.name];
|
||||
if (!tool) return error(-32602, `Outil inconnu : ${params.name}`);
|
||||
try {
|
||||
const j = await openJournal(syncKey);
|
||||
const out = await tool(j, params.arguments ?? {});
|
||||
return result({ content: [{ type: "text", text: JSON.stringify(out, null, 1) }] });
|
||||
} catch (e) {
|
||||
// Jamais la clé de synchro dans un message : les erreurs viennent des
|
||||
// outils (textes fixes) ou du relais (HttpError, textes fixes).
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
return result({ content: [{ type: "text", text: "Erreur : " + message }], isError: true });
|
||||
}
|
||||
}
|
||||
default:
|
||||
if (isNotification) return null;
|
||||
return error(-32601, `Méthode inconnue : ${msg.method}`);
|
||||
}
|
||||
}
|
||||
|
||||
return { handle, tools: TOOLS };
|
||||
}
|
||||
+305
@@ -0,0 +1,305 @@
|
||||
// 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<string, number>} */
|
||||
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<string, any>|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<string, unknown>} 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<string, string|null>} 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<typeof checkAuthorization>} 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<string, string|undefined>} 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<typeof createOAuth>} OAuth */
|
||||
@@ -0,0 +1,49 @@
|
||||
// Limite de requêtes par adresse IP, en mémoire seulement : rien n'est écrit,
|
||||
// et tout est oublié au redémarrage (ADR 0005 : aucune adresse conservée).
|
||||
|
||||
/**
|
||||
* Adresse du client telle que vue par le proxy de CapRover (nginx), qui écrit
|
||||
* `X-Real-IP` et AJOUTE l'adresse vue à la fin de `X-Forwarded-For`. Le début de
|
||||
* `X-Forwarded-For` vient du client et peut être inventé (défaut d'Atelier) :
|
||||
* on ne le lit jamais.
|
||||
* @param {import("node:http").IncomingMessage} req
|
||||
*/
|
||||
export function clientIp(req) {
|
||||
const real = req.headers["x-real-ip"];
|
||||
if (typeof real === "string" && real.trim()) return real.trim();
|
||||
const forwarded = req.headers["x-forwarded-for"];
|
||||
const list = (Array.isArray(forwarded) ? forwarded.join(",") : forwarded ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
||||
if (list.length) return list[list.length - 1];
|
||||
return req.socket.remoteAddress ?? "inconnue";
|
||||
}
|
||||
|
||||
/**
|
||||
* Fenêtre fixe : au plus `max` requêtes par `windowMs` et par clé.
|
||||
* @param {{max: number, windowMs: number, now?: () => number}} options
|
||||
*/
|
||||
export function createRateLimiter({ max, windowMs, now = Date.now }) {
|
||||
/** @type {Map<string, {start: number, count: number}>} */
|
||||
const windows = new Map();
|
||||
return {
|
||||
/**
|
||||
* Compte une requête ; renvoie le nombre de secondes à attendre si la limite
|
||||
* est dépassée, sinon 0.
|
||||
* @param {string} key
|
||||
*/
|
||||
hit(key) {
|
||||
const t = now();
|
||||
if (windows.size > 50_000) for (const [k, w] of windows) if (t - w.start >= windowMs) windows.delete(k);
|
||||
let w = windows.get(key);
|
||||
if (!w || t - w.start >= windowMs) {
|
||||
w = { start: t, count: 0 };
|
||||
windows.set(key, w);
|
||||
}
|
||||
w.count++;
|
||||
return w.count > max ? Math.ceil((w.start + windowMs - t) / 1000) : 0;
|
||||
},
|
||||
/** Nombre d'adresses suivies (tests). */
|
||||
get size() {
|
||||
return windows.size;
|
||||
},
|
||||
};
|
||||
}
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
// Le relais (ADR 0005, point 3) : il range des blocs chiffrés par journal, sans
|
||||
// pouvoir les lire. Glossaire : docs/glossaire/relais.md
|
||||
//
|
||||
// FORMAT DURABLE sur disque, un fichier JSON Lines par journal :
|
||||
// <DATA_DIR>/journals/<journalId>.jsonl
|
||||
// ligne 1 : {"v":1,"auth":"<SHA-256 hexadécimal de la clé d'accès>"}
|
||||
// puis : {"seq":1,"blob":"<bloc base64url>"}, {"seq":2,…}, …
|
||||
// Le fichier ne fait que grandir (ajout seulement). Aucune date, aucune adresse :
|
||||
// la date de modification du fichier sert seule à repérer l'inactivité.
|
||||
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import crypto from "node:crypto";
|
||||
import { HttpError } from "./http.js";
|
||||
|
||||
export const LIMITS = {
|
||||
/** Taille maximale d'un bloc chiffré (caractères base64url, donc octets). */
|
||||
blobBytes: 64 * 1024,
|
||||
/** Taille maximale d'un journal sur disque. */
|
||||
journalBytes: 20 * 1024 * 1024,
|
||||
/** Blocs par dépôt. */
|
||||
blobsPerRequest: 500,
|
||||
/** Blocs par réponse de lecture : au-delà, `more` vaut true. */
|
||||
blobsPerRead: 2000,
|
||||
/** Inactivité au bout de laquelle un journal est effacé. */
|
||||
inactiveDays: 400,
|
||||
};
|
||||
|
||||
/** Identifiant de journal : 16 octets en base64url (22 caractères) ; tolérance jusqu'à 64. */
|
||||
export const JOURNAL_ID = /^[A-Za-z0-9_-]{16,64}$/;
|
||||
const BLOB = /^[A-Za-z0-9_-]{38,}$/;
|
||||
|
||||
/** @param {string} token */
|
||||
const hashToken = (token) => crypto.createHash("sha256").update(token).digest();
|
||||
|
||||
/**
|
||||
* @typedef {object} JournalMeta
|
||||
* @property {Buffer} auth empreinte SHA-256 de la clé d'accès
|
||||
* @property {number} last dernier numéro d'ordre
|
||||
* @property {number} size taille du fichier
|
||||
* @property {number} touched dernière mise à jour de la date du fichier (lecture), en ms
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {string} dataDir
|
||||
* @param {{limits?: Partial<typeof LIMITS>, now?: () => number}} [options]
|
||||
*/
|
||||
export function createRelay(dataDir, options = {}) {
|
||||
const limits = { ...LIMITS, ...options.limits };
|
||||
const now = options.now ?? Date.now;
|
||||
const dir = path.join(dataDir, "journals");
|
||||
/** @type {Map<string, JournalMeta>} */
|
||||
const metas = new Map();
|
||||
/** File d'attente par journal : les écritures (et le chargement) sont sérialisées. */
|
||||
/** @type {Map<string, Promise<unknown>>} */
|
||||
const queues = new Map();
|
||||
|
||||
/** @param {string} id */
|
||||
const fileOf = (id) => path.join(dir, id + ".jsonl");
|
||||
|
||||
/**
|
||||
* @template T
|
||||
* @param {string} id
|
||||
* @param {() => Promise<T>} task
|
||||
* @returns {Promise<T>}
|
||||
*/
|
||||
function serialized(id, task) {
|
||||
const previous = queues.get(id) ?? Promise.resolve();
|
||||
const run = previous.then(task, task);
|
||||
const tail = run.catch(() => {});
|
||||
queues.set(id, tail);
|
||||
tail.then(() => { if (queues.get(id) === tail) queues.delete(id); });
|
||||
return run;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lit l'en-tête et compte les blocs. Une dernière ligne incomplète (arrêt
|
||||
* brutal pendant une écriture) est retirée.
|
||||
* @param {string} id
|
||||
* @returns {Promise<JournalMeta|null>}
|
||||
*/
|
||||
async function load(id) {
|
||||
const cached = metas.get(id);
|
||||
if (cached) return cached;
|
||||
let text;
|
||||
try {
|
||||
text = await fs.readFile(fileOf(id), "utf8");
|
||||
} catch (e) {
|
||||
if (/** @type {NodeJS.ErrnoException} */ (e).code === "ENOENT") return null;
|
||||
throw e;
|
||||
}
|
||||
if (!text.endsWith("\n")) {
|
||||
const cut = text.lastIndexOf("\n") + 1;
|
||||
await fs.truncate(fileOf(id), Buffer.byteLength(text.slice(0, cut)));
|
||||
text = text.slice(0, cut);
|
||||
if (!text) {
|
||||
await fs.unlink(fileOf(id));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const lines = text.split("\n");
|
||||
const header = JSON.parse(lines[0]);
|
||||
const meta = {
|
||||
auth: Buffer.from(header.auth, "hex"),
|
||||
last: lines.length - 2,
|
||||
size: Buffer.byteLength(text),
|
||||
touched: 0,
|
||||
};
|
||||
if (metas.size > 10_000) metas.clear();
|
||||
metas.set(id, meta);
|
||||
return meta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie la clé d'accès, à temps constant.
|
||||
* @param {JournalMeta} meta
|
||||
* @param {string} token
|
||||
*/
|
||||
function checkToken(meta, token) {
|
||||
if (!token || !crypto.timingSafeEqual(meta.auth, hashToken(token)))
|
||||
throw new HttpError(403, "forbidden", "Clé d'accès refusée pour ce journal.");
|
||||
}
|
||||
|
||||
/** @param {string} id */
|
||||
function checkId(id) {
|
||||
if (!JOURNAL_ID.test(id)) throw new HttpError(404, "unknown_journal", "Journal inconnu.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Garde le journal en vie : une lecture compte comme une activité (au plus
|
||||
* une mise à jour de la date du fichier par jour).
|
||||
* @param {string} id
|
||||
* @param {JournalMeta} meta
|
||||
*/
|
||||
async function touch(id, meta) {
|
||||
if (now() - meta.touched < 864e5) return;
|
||||
meta.touched = now();
|
||||
const t = new Date(now());
|
||||
await fs.utimes(fileOf(id), t, t).catch(() => {});
|
||||
}
|
||||
|
||||
return {
|
||||
limits,
|
||||
|
||||
/**
|
||||
* Dépose des blocs. Le premier dépôt crée le journal et retient l'empreinte
|
||||
* de la clé d'accès ; les suivants l'exigent.
|
||||
* @param {string} id
|
||||
* @param {string} token
|
||||
* @param {unknown} blobs
|
||||
* @returns {Promise<{last: number, accepted: number}>}
|
||||
*/
|
||||
append(id, token, blobs) {
|
||||
checkId(id);
|
||||
if (!token) throw new HttpError(401, "unauthorized", "Clé d'accès manquante.");
|
||||
if (!Array.isArray(blobs) || blobs.length === 0)
|
||||
throw new HttpError(400, "invalid_request", "Le corps doit être une liste non vide de blocs chiffrés.");
|
||||
if (blobs.length > limits.blobsPerRequest)
|
||||
throw new HttpError(413, "too_many_blobs", `Au plus ${limits.blobsPerRequest} blocs par dépôt.`);
|
||||
for (const b of blobs) {
|
||||
if (typeof b !== "string" || !BLOB.test(b)) throw new HttpError(400, "invalid_blob", "Bloc chiffré mal formé (base64url attendu).");
|
||||
if (b.length > limits.blobBytes) throw new HttpError(413, "blob_too_large", `Un bloc dépasse ${limits.blobBytes} octets.`);
|
||||
}
|
||||
return serialized(id, async () => {
|
||||
let meta = await load(id);
|
||||
let header = "";
|
||||
if (meta) checkToken(meta, token);
|
||||
else {
|
||||
await fs.mkdir(dir, { recursive: true });
|
||||
header = JSON.stringify({ v: 1, auth: hashToken(token).toString("hex") }) + "\n";
|
||||
}
|
||||
const start = meta?.last ?? 0;
|
||||
const lines = header + blobs.map((blob, i) => JSON.stringify({ seq: start + i + 1, blob })).join("\n") + "\n";
|
||||
const bytes = Buffer.byteLength(lines);
|
||||
if ((meta?.size ?? 0) + bytes > limits.journalBytes)
|
||||
throw new HttpError(413, "journal_full", `Le journal dépasserait ${Math.round(limits.journalBytes / 1048576)} Mo.`);
|
||||
const handle = await fs.open(fileOf(id), meta ? "a" : "wx");
|
||||
try {
|
||||
await handle.write(lines);
|
||||
await handle.datasync();
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
if (!meta) {
|
||||
meta = { auth: hashToken(token), last: 0, size: 0, touched: now() };
|
||||
metas.set(id, meta);
|
||||
}
|
||||
meta.last = start + blobs.length;
|
||||
meta.size += bytes;
|
||||
meta.touched = now();
|
||||
return { last: meta.last, accepted: blobs.length };
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Blocs dont le numéro d'ordre suit `after`.
|
||||
* @param {string} id
|
||||
* @param {string} token
|
||||
* @param {number} [after]
|
||||
* @returns {Promise<{events: {seq: number, blob: string}[], last: number, more: boolean}>}
|
||||
*/
|
||||
read(id, token, after = 0) {
|
||||
checkId(id);
|
||||
if (!token) throw new HttpError(401, "unauthorized", "Clé d'accès manquante.");
|
||||
return serialized(id, async () => {
|
||||
const meta = await load(id);
|
||||
if (!meta) throw new HttpError(404, "unknown_journal", "Journal inconnu : aucun dépôt n'a encore été fait avec cette clé.");
|
||||
checkToken(meta, token);
|
||||
await touch(id, meta);
|
||||
/** @type {{seq: number, blob: string}[]} */
|
||||
const events = [];
|
||||
if (after < meta.last) {
|
||||
const lines = (await fs.readFile(fileOf(id), "utf8")).split("\n");
|
||||
// Ligne n (à partir de 1) = bloc n.
|
||||
for (let seq = Math.max(1, after + 1); seq <= meta.last && events.length < limits.blobsPerRead; seq++)
|
||||
events.push({ seq, blob: JSON.parse(lines[seq]).blob });
|
||||
}
|
||||
const lastSent = events.length ? events[events.length - 1].seq : Math.max(after, 0);
|
||||
return { events, last: meta.last, more: lastSent < meta.last };
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Le journal existe-t-il, et cette clé d'accès est-elle la sienne ?
|
||||
* @param {string} id
|
||||
* @param {string} token
|
||||
*/
|
||||
async owns(id, token) {
|
||||
if (!JOURNAL_ID.test(id) || !token) return false;
|
||||
const meta = await serialized(id, () => load(id));
|
||||
return !!meta && crypto.timingSafeEqual(meta.auth, hashToken(token));
|
||||
},
|
||||
|
||||
/**
|
||||
* Efface les journaux inactifs depuis `inactiveDays` jours.
|
||||
* @returns {Promise<number>} nombre de journaux effacés
|
||||
*/
|
||||
async purgeInactive() {
|
||||
const limit = now() - limits.inactiveDays * 864e5;
|
||||
let removed = 0;
|
||||
const names = await fs.readdir(dir).catch(() => /** @type {string[]} */ ([]));
|
||||
for (const name of names) {
|
||||
if (!name.endsWith(".jsonl")) continue;
|
||||
const id = name.slice(0, -6);
|
||||
await serialized(id, async () => {
|
||||
const stat = await fs.stat(fileOf(id)).catch(() => null);
|
||||
if (stat && stat.mtimeMs < limit) {
|
||||
await fs.unlink(fileOf(id));
|
||||
metas.delete(id);
|
||||
removed++;
|
||||
}
|
||||
});
|
||||
}
|
||||
return removed;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** @typedef {ReturnType<typeof createRelay>} Relay */
|
||||
@@ -0,0 +1,140 @@
|
||||
// Site statique : les mêmes réponses que le Caddyfile du lot 1 (types MIME fixés,
|
||||
// en-têtes de sécurité, revalidation à chaque visite, compression des textes).
|
||||
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import zlib from "node:zlib";
|
||||
import { SECURITY_HEADERS, sendText } from "./http.js";
|
||||
|
||||
/**
|
||||
* Types MIME fixés ici plutôt que devinés : avec nosniff, un module ES servi
|
||||
* sous un autre type ne se charge pas.
|
||||
* @type {Record<string, string>}
|
||||
*/
|
||||
export const MIME_TYPES = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
".mjs": "text/javascript; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".json": "application/json",
|
||||
".webmanifest": "application/manifest+json",
|
||||
".md": "text/markdown; charset=utf-8",
|
||||
".txt": "text/plain; charset=utf-8",
|
||||
".svg": "image/svg+xml",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".webp": "image/webp",
|
||||
".ico": "image/x-icon",
|
||||
".woff2": "font/woff2",
|
||||
};
|
||||
|
||||
/** Types compressés : les textes. Les polices woff2 et les images le sont déjà. */
|
||||
const COMPRESSIBLE = /^(text\/|application\/json|application\/manifest\+json|image\/svg\+xml)/;
|
||||
/** Comme Caddy : en dessous, la compression ne fait rien gagner. */
|
||||
const MIN_COMPRESS = 512;
|
||||
|
||||
/**
|
||||
* Encodage choisi d'après Accept-Encoding : zstd, sinon gzip, sinon aucun.
|
||||
* @param {string|undefined} header
|
||||
* @returns {"zstd"|"gzip"|null}
|
||||
*/
|
||||
export function pickEncoding(header) {
|
||||
/** @type {Map<string, number>} */
|
||||
const accepted = new Map();
|
||||
for (const part of (header ?? "").split(",")) {
|
||||
const [name, ...params] = part.trim().toLowerCase().split(";");
|
||||
if (!name) continue;
|
||||
const q = params.map((p) => /^\s*q=([0-9.]+)\s*$/.exec(p)).find(Boolean);
|
||||
accepted.set(name, q ? Number(q[1]) : 1);
|
||||
}
|
||||
const ok = (/** @type {string} */ name) => (accepted.get(name) ?? accepted.get("*") ?? 0) > 0;
|
||||
if (ok("zstd")) return "zstd";
|
||||
if (ok("gzip")) return "gzip";
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} siteDir dossier du site assemblé (make site)
|
||||
*/
|
||||
export function createStaticHandler(siteDir) {
|
||||
const root = path.resolve(siteDir);
|
||||
/** Versions compressées, gardées en mémoire tant que le fichier ne change pas. */
|
||||
/** @type {Map<string, Buffer>} */
|
||||
const compressed = new Map();
|
||||
|
||||
/**
|
||||
* @param {import("node:http").IncomingMessage} req
|
||||
* @param {import("node:http").ServerResponse} res
|
||||
* @param {string} pathname chemin de l'URL, non décodé
|
||||
*/
|
||||
return async function serveStatic(req, res, pathname) {
|
||||
if (req.method !== "GET" && req.method !== "HEAD")
|
||||
return sendText(res, 405, "Méthode non permise.", { allow: "GET, HEAD" });
|
||||
let rel;
|
||||
try {
|
||||
rel = decodeURIComponent(pathname);
|
||||
} catch {
|
||||
return sendText(res, 400, "Adresse invalide.");
|
||||
}
|
||||
// Ni remontée, ni fichier caché, ni caractère nul.
|
||||
if (rel.includes("\0") || rel.split("/").some((seg) => seg === ".." || seg.startsWith(".")))
|
||||
return notFound(res);
|
||||
let file = path.join(root, rel);
|
||||
if (file !== root && !file.startsWith(root + path.sep)) return notFound(res);
|
||||
let stat = await fs.stat(file).catch(() => null);
|
||||
if (stat?.isDirectory()) {
|
||||
if (!rel.endsWith("/")) {
|
||||
const index = await fs.stat(path.join(file, "index.html")).catch(() => null);
|
||||
if (!index) return notFound(res);
|
||||
res.writeHead(308, { ...SECURITY_HEADERS, location: pathname + "/", "cache-control": "no-cache" });
|
||||
return res.end();
|
||||
}
|
||||
file = path.join(file, "index.html");
|
||||
stat = await fs.stat(file).catch(() => null);
|
||||
}
|
||||
if (!stat?.isFile()) return notFound(res);
|
||||
|
||||
const type = MIME_TYPES[path.extname(file).toLowerCase()] ?? "application/octet-stream";
|
||||
const encoding = COMPRESSIBLE.test(type) && stat.size >= MIN_COMPRESS ? pickEncoding(req.headers["accept-encoding"]) : null;
|
||||
const baseTag = `${Math.floor(stat.mtimeMs).toString(36)}${stat.size.toString(36)}`;
|
||||
const etag = `"${baseTag}${encoding ? "-" + encoding : ""}"`;
|
||||
/** @type {Record<string, string|number>} */
|
||||
const headers = {
|
||||
...SECURITY_HEADERS,
|
||||
// Les noms de fichiers ne changent pas d'une version à l'autre : le
|
||||
// navigateur revalide chaque fichier (ETag). sw.js porte la version.
|
||||
"cache-control": "no-cache",
|
||||
"content-type": type,
|
||||
etag,
|
||||
"last-modified": stat.mtime.toUTCString(),
|
||||
};
|
||||
if (COMPRESSIBLE.test(type)) headers.vary = "Accept-Encoding";
|
||||
const inm = req.headers["if-none-match"];
|
||||
if (inm && inm.split(",").some((t) => t.trim().replace(/^W\//, "") === etag)) {
|
||||
res.writeHead(304, headers);
|
||||
return res.end();
|
||||
}
|
||||
let body = await fs.readFile(file);
|
||||
if (encoding) {
|
||||
const key = `${file}|${baseTag}|${encoding}`;
|
||||
let packed = compressed.get(key);
|
||||
if (!packed) {
|
||||
packed = encoding === "zstd" ? zlib.zstdCompressSync(body) : zlib.gzipSync(body);
|
||||
if (compressed.size > 2000) compressed.clear();
|
||||
compressed.set(key, packed);
|
||||
}
|
||||
body = packed;
|
||||
headers["content-encoding"] = encoding;
|
||||
}
|
||||
headers["content-length"] = body.length;
|
||||
res.writeHead(200, headers);
|
||||
res.end(req.method === "HEAD" ? undefined : body);
|
||||
};
|
||||
}
|
||||
|
||||
/** @param {import("node:http").ServerResponse} res */
|
||||
function notFound(res) {
|
||||
res.writeHead(404, { ...SECURITY_HEADERS, "cache-control": "no-cache", "content-type": "text/plain; charset=utf-8" });
|
||||
res.end("Introuvable.");
|
||||
}
|
||||
Reference in New Issue
Block a user