Serveur Node : site statique, relais chiffré, OAuth sans état, MCP
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
5188c022d5
commit
508bab9a8e
+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 */
|
||||
Reference in New Issue
Block a user