Send a toolbox through an encrypted link
All checks were successful
Validate and deploy Sokko G / validate (push) Successful in 20m39s
Validate and deploy Sokko G / deploy (push) Successful in 12s

Sharing a toolbox meant exporting a JSON file and passing it around by
hand. A toolbox can now be sent from the site while staying local first:
the browser compresses and encrypts the v2 export with AES-GCM, and the
key lives only in the link fragment, so the server keeps for at most
24 hours a copy it cannot read.

- Add the /api/shares service: upload, metadata, download and revoke,
  with files in SHARES_DIR, a purge every 10 minutes, and single-use
  links (the default) deleted only once fully downloaded.
- Cap the server load: 50 MiB per share, total storage, free disk
  space, daily volume, concurrent and stalled uploads, reads per link,
  plus a wide per-connection cap kept in memory without storing IPs.
- Limit each browser to 2 shares and 100 MiB per day and 2 active
  links, and show the existing link of a toolbox already shared.
- Add the send dialog (card and game drawer) and the /receive page,
  which previews or directly imports through the existing import path.
- Move shared HTTP helpers to services/http.js for both APIs.
- Document the format, delivery, server layout and privacy wording.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-11 16:26:05 +01:00
parent 957bfdc86f
commit bec9ea5b2f
43 changed files with 2349 additions and 59 deletions

View file

@ -4,28 +4,15 @@ import { join, resolve } from "node:path";
import { CardsDatabase } from "./database.js";
import { loadCardsCatalog, publicCatalog } from "./catalog.js";
import { CardsService, DEV_DISCORD_ID } from "./service.js";
import { bool, createRateLimiter, json } from "../http.js";
export { createRateLimiter };
const JSON_LIMIT = 64 * 1024;
const DISCORD_TIMEOUT_MS = 10_000;
const MAINTENANCE_INTERVAL_MS = 24 * 60 * 60 * 1000;
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
function bool(value, fallback = false) {
if (value == null || value === "") return fallback;
return /^(1|true|yes|on)$/i.test(String(value));
}
function json(res, status, body) {
const payload = JSON.stringify(body);
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": Buffer.byteLength(payload),
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff"
});
res.end(payload);
}
function redirect(res, location, cookies = []) {
const headers = { Location: location, "Cache-Control": "no-store" };
if (cookies.length) headers["Set-Cookie"] = cookies;
@ -106,25 +93,6 @@ function routeMatch(pathname, pattern) {
}
}
// Les compteurs ne valent que pour la minute en cours : ils sont tous oubliés à la suivante pour que la mémoire reste bornée.
export function createRateLimiter(now) {
const buckets = new Map();
let currentMinute = null;
const limiter = (req, scope, limit = 60) => {
const key = `${String(req.headers["x-forwarded-for"] || req.socket?.remoteAddress || "unknown").split(",")[0]}:${scope}`;
const minute = Math.floor(now() / 60_000);
if (minute !== currentMinute) {
buckets.clear();
currentMinute = minute;
}
const count = (buckets.get(key) || 0) + 1;
buckets.set(key, count);
if (count > limit) throw Object.assign(new Error("Trop de tentatives. Réessayez dans quelques instants."), { status: 429, code: "RATE_LIMITED" });
};
limiter.bucketCount = () => buckets.size;
return limiter;
}
export function createCardsApiHandler({
projectRoot = resolve("."),
env = process.env,

46
services/http.js Normal file
View file

@ -0,0 +1,46 @@
// Rôle : regroupe les petits outils HTTP partagés par les API du serveur Node.
export function bool(value, fallback = false) {
if (value == null || value === "") return fallback;
return /^(1|true|yes|on)$/i.test(String(value));
}
export function json(res, status, body, headers = {}) {
const payload = JSON.stringify(body);
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": Buffer.byteLength(payload),
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
...headers
});
res.end(payload);
}
export function httpError(status, code, message, extra = {}) {
return Object.assign(new Error(message), { status, code, ...extra });
}
// Caddy remplace X-Forwarded-For par l'adresse réelle du client (voir docs/SERVER.md).
export function clientAddress(req) {
return String(req.headers["x-forwarded-for"] || req.socket?.remoteAddress || "unknown").split(",")[0].trim();
}
// Les compteurs ne valent que pour la minute en cours : ils sont tous oubliés à la suivante pour que la mémoire reste bornée.
export function createRateLimiter(now) {
const buckets = new Map();
let currentMinute = null;
const limiter = (req, scope, limit = 60) => {
const key = `${clientAddress(req)}:${scope}`;
const minute = Math.floor(now() / 60_000);
if (minute !== currentMinute) {
buckets.clear();
currentMinute = minute;
}
const count = (buckets.get(key) || 0) + 1;
buckets.set(key, count);
if (count > limit) throw httpError(429, "RATE_LIMITED", "Trop de tentatives. Réessayez dans quelques instants.");
};
limiter.bucketCount = () => buckets.size;
return limiter;
}

377
services/shares/api.js Normal file
View file

@ -0,0 +1,377 @@
// Rôle : expose l'API d'envoi de toolbox chiffrée et applique les plafonds qui protègent le serveur.
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { createReadStream, createWriteStream } from "node:fs";
import { rm, statfs as fsStatfs } from "node:fs/promises";
import { join, resolve } from "node:path";
import { bool, clientAddress, createRateLimiter, httpError, json } from "../http.js";
import { SHARE_ID_PATTERN, ShareStore } from "./store.js";
export const SHARE_TTL_MS = 24 * 60 * 60 * 1000;
export const SHARE_MAX_BYTES = 50 * 1024 * 1024;
// En-tête "SKS1", IV de 12 octets et étiquette AES-GCM de 16 octets : un envoi plus petit ne peut pas être valide.
export const SHARE_MIN_BYTES = 4 + 12 + 16;
const SHARE_MAGIC = "SKS1";
const DAY_MS = 24 * 60 * 60 * 1000;
const HOUR_MS = 60 * 60 * 1000;
const PURGE_INTERVAL_MS = 10 * 60 * 1000;
const GIB = 1024 * 1024 * 1024;
const MIB = 1024 * 1024;
export const DEFAULT_SHARE_LIMITS = Object.freeze({
maxTotalBytes: 2 * GIB,
maxActiveShares: 500,
minFreeBytes: 5 * GIB,
dailyBytes: 5 * GIB,
maxConcurrentUploads: 3,
uploadTimeoutMs: 2 * 60 * 1000,
// Sans donnée reçue pendant ce délai, l'envoi est coupé : un client volontairement lent ne garde pas une place.
uploadIdleTimeoutMs: 15 * 1000,
maxReads: 50,
ipDailyUploads: 10,
ipDailyBytes: 300 * MIB,
ipUploadsPerMinute: 5,
readsPerMinute: 60
});
const ENV_LIMITS = {
maxTotalBytes: "SHARES_MAX_TOTAL_BYTES",
maxActiveShares: "SHARES_MAX_ACTIVE",
minFreeBytes: "SHARES_MIN_FREE_BYTES",
dailyBytes: "SHARES_DAILY_BYTES",
maxConcurrentUploads: "SHARES_MAX_CONCURRENT_UPLOADS",
ipDailyUploads: "SHARES_IP_DAILY_UPLOADS",
ipDailyBytes: "SHARES_IP_DAILY_BYTES"
};
function limitsFromEnv(env) {
const limits = {};
for (const [key, name] of Object.entries(ENV_LIMITS)) {
const raw = String(env[name] ?? "").trim();
if (!raw) continue;
const value = Number(raw);
if (!Number.isSafeInteger(value) || value < 0) throw new TypeError(`${name} must be a non-negative integer.`);
limits[key] = value;
}
return limits;
}
function tokenHash(token) {
return createHash("sha256").update(String(token)).digest();
}
function sendEmpty(res, status, headers = {}) {
res.writeHead(status, { "Cache-Control": "no-store", ...headers });
res.end();
}
function shareNotFound() {
return httpError(404, "SHARE_NOT_FOUND", "Ce lien a expiré, a été révoqué ou a déjà été utilisé.");
}
// Volume reçu sur 24 h glissantes, compté par heure : la mémoire reste bornée quel que soit le nombre d'envois.
function createHourlyVolume() {
const buckets = new Map();
return {
total(now) {
const oldest = Math.floor((now - DAY_MS) / HOUR_MS);
let sum = 0;
for (const [hour, bytes] of buckets) {
if (hour <= oldest) buckets.delete(hour);
else sum += bytes;
}
return sum;
},
add(now, bytes) {
const hour = Math.floor(now / HOUR_MS);
buckets.set(hour, (buckets.get(hour) || 0) + bytes);
}
};
}
export function createSharesApiHandler({
projectRoot = resolve("."),
env = process.env,
enabled = bool(env.SHARES_ENABLED),
dir = env.SHARES_DIR || join(projectRoot, ".local", "shares"),
now = Date.now,
statfs = fsStatfs,
limits: overrides = {}
} = {}) {
const limits = { ...DEFAULT_SHARE_LIMITS, ...limitsFromEnv(env), ...overrides };
let store = null;
let purgeTimer = null;
if (enabled) {
// Sans dossier explicite, les envois iraient dans la copie du site, remplacée à chaque livraison.
if (env.NODE_ENV === "production" && !env.SHARES_DIR) throw new TypeError("SHARES_DIR is required when toolbox sharing is enabled in production.");
store = new ShareStore({ dir, now });
purgeTimer = setInterval(() => {
store.purge().catch((error) => console.error(error));
pruneIpUsage();
}, PURGE_INTERVAL_MS);
purgeTimer.unref();
}
const rateLimit = createRateLimiter(now);
// L'adresse IP n'est conservée qu'en mémoire, sous une empreinte dont la clé change à chaque démarrage.
const ipSecret = randomBytes(32);
const ipUsage = new Map();
const globalVolume = createHourlyVolume();
let uploadsInFlight = 0;
let reservedBytes = 0;
const ipKey = (req) => createHmac("sha256", ipSecret).update(clientAddress(req)).digest("base64url");
function recentIpUploads(key) {
const since = now() - DAY_MS;
const entries = (ipUsage.get(key) || []).filter((entry) => entry.at > since);
if (entries.length) ipUsage.set(key, entries);
else ipUsage.delete(key);
return entries;
}
function pruneIpUsage() {
for (const key of [...ipUsage.keys()]) recentIpUploads(key);
}
function refuse(status, code, message, extra = {}) {
console.warn(`Toolbox share refused: ${code}`);
return httpError(status, code, message, extra);
}
async function freeBytes() {
const stats = await statfs(store.dir);
return Number(stats.bavail) * Number(stats.bsize);
}
// Tous les refus possibles sont décidés avant de lire le corps de la requête.
async function checkCapacity(req, size) {
const key = ipKey(req);
const ipEntries = recentIpUploads(key);
if (ipEntries.length >= limits.ipDailyUploads || ipEntries.reduce((sum, entry) => sum + entry.bytes, 0) + size > limits.ipDailyBytes) {
throw refuse(429, "SHARE_IP_QUOTA", "Trop d'envois depuis cette connexion aujourd'hui. Réessayez demain.");
}
if (globalVolume.total(now()) + reservedBytes + size > limits.dailyBytes) {
throw refuse(429, "SHARE_DAILY_QUOTA", "Le service d'envoi a atteint sa limite du jour. Réessayez plus tard.");
}
if (uploadsInFlight >= limits.maxConcurrentUploads) {
throw refuse(503, "SHARE_BUSY", "Le service d'envoi est occupé. Réessayez dans quelques instants.", { headers: { "Retry-After": "30" } });
}
if (store.count + uploadsInFlight >= limits.maxActiveShares || store.totalBytes + reservedBytes + size > limits.maxTotalBytes) {
throw refuse(507, "SHARE_STORAGE_FULL", "Le service d'envoi est plein. Réessayez plus tard.");
}
if (await freeBytes() - reservedBytes - size < limits.minFreeBytes) {
throw refuse(507, "SHARE_STORAGE_FULL", "Le service d'envoi est plein. Réessayez plus tard.");
}
return key;
}
function receiveBody(req, file, size) {
return new Promise((resolvePromise, reject) => {
const out = createWriteStream(file, { flags: "wx", mode: 0o600 });
let received = 0;
let header = Buffer.alloc(0);
let ended = false;
let settled = false;
let idleTimer = null;
const finish = (error) => {
if (settled) return;
settled = true;
clearTimeout(totalTimer);
clearTimeout(idleTimer);
if (error) {
out.destroy();
reject(error);
} else {
resolvePromise();
}
};
const totalTimer = setTimeout(() => finish(httpError(408, "SHARE_TIMEOUT", "L'envoi a pris trop de temps.")), limits.uploadTimeoutMs);
const armIdle = () => {
clearTimeout(idleTimer);
idleTimer = setTimeout(() => finish(httpError(408, "SHARE_TIMEOUT", "L'envoi a pris trop de temps.")), limits.uploadIdleTimeoutMs);
};
armIdle();
req.on("data", (chunk) => {
if (settled) return;
received += chunk.length;
if (received > size) return finish(httpError(413, "SHARE_TOO_LARGE", "Cette toolbox dépasse la taille maximale d'envoi."));
if (header.length < SHARE_MAGIC.length) {
header = Buffer.concat([header, chunk.subarray(0, SHARE_MAGIC.length - header.length)]);
if (header.length === SHARE_MAGIC.length && header.toString("latin1") !== SHARE_MAGIC) {
return finish(httpError(400, "SHARE_FORMAT", "Le contenu envoyé n'est pas une toolbox chiffrée."));
}
}
armIdle();
if (!out.write(chunk)) {
req.pause();
out.once("drain", () => req.resume());
}
});
req.on("end", () => {
ended = true;
if (settled) return;
if (received !== size) return finish(httpError(400, "SHARE_INCOMPLETE", "L'envoi est incomplet."));
out.end();
});
req.on("close", () => {
if (!ended) finish(httpError(400, "SHARE_ABORTED", "L'envoi a été interrompu."));
});
// Un client qui coupe la connexion n'est pas une erreur du serveur.
req.on("error", () => finish(httpError(400, "SHARE_ABORTED", "L'envoi a été interrompu.")));
out.on("error", finish);
out.on("finish", () => finish());
});
}
async function handleUpload(req, res) {
if (req.headers["x-sokkog-share"] !== "1") throw httpError(400, "SHARE_HEADER_REQUIRED", "Requête d'envoi invalide.");
const type = String(req.headers["content-type"] || "").split(";")[0].trim().toLowerCase();
if (type !== "application/octet-stream") throw httpError(415, "SHARE_CONTENT_TYPE", "Requête d'envoi invalide.");
rateLimit(req, "shares-upload", limits.ipUploadsPerMinute);
const declared = req.headers["content-length"];
if (declared == null || !/^\d+$/.test(String(declared))) throw httpError(411, "SHARE_LENGTH_REQUIRED", "Requête d'envoi invalide.");
const size = Number(declared);
if (size > SHARE_MAX_BYTES) throw httpError(413, "SHARE_TOO_LARGE", "Cette toolbox dépasse la taille maximale d'envoi.");
if (size < SHARE_MIN_BYTES) throw httpError(400, "SHARE_FORMAT", "Le contenu envoyé n'est pas une toolbox chiffrée.");
const key = await checkCapacity(req, size);
const id = randomBytes(16).toString("base64url");
const deleteToken = randomBytes(24).toString("base64url");
const part = store.partPath(id);
uploadsInFlight += 1;
reservedBytes += size;
try {
await receiveBody(req, part, size);
const createdAt = now();
const meta = { createdAt, expiresAt: createdAt + SHARE_TTL_MS, size, singleUse: req.headers["x-share-single-use"] === "1", reads: 0, deleteTokenHash: tokenHash(deleteToken).toString("hex") };
await store.commit(id, meta);
const entries = recentIpUploads(key);
entries.push({ at: createdAt, bytes: size });
ipUsage.set(key, entries);
globalVolume.add(createdAt, size);
json(res, 201, { id, deleteToken, expiresAt: meta.expiresAt, singleUse: meta.singleUse });
} catch (error) {
await rm(part, { force: true });
throw error;
} finally {
uploadsInFlight -= 1;
reservedBytes -= size;
}
}
function readableShare(id) {
if (!SHARE_ID_PATTERN.test(id)) throw httpError(400, "INVALID_SHARE_ID", "Lien d'envoi invalide.");
const meta = store.get(id);
if (!meta || (!meta.singleUse && meta.reads >= limits.maxReads)) throw shareNotFound();
return meta;
}
function handleDownload(id, res) {
const meta = readableShare(id);
if (meta.singleUse) store.claim(id);
else void store.recordRead(id).catch((error) => console.error(error));
const stream = createReadStream(store.binPath(id));
let finished = false;
res.on("finish", () => {
finished = true;
if (meta.singleUse) void store.remove(id).catch((error) => console.error(error));
});
// Une lecture interrompue laisse le lien utilisable : le destinataire peut réessayer.
res.on("close", () => {
if (!finished && meta.singleUse) store.release(id);
stream.destroy();
});
stream.once("open", () => {
res.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Length": meta.size,
"Cache-Control": "no-store",
"X-Share-Expires-At": String(meta.expiresAt),
"X-Share-Single-Use": meta.singleUse ? "1" : "0"
});
stream.pipe(res);
});
stream.once("error", () => {
if (meta.singleUse) store.release(id);
if (res.headersSent) res.destroy();
else json(res, 404, { error: { code: "SHARE_NOT_FOUND", message: shareNotFound().message } });
});
}
async function handleDelete(id, req, res) {
if (!SHARE_ID_PATTERN.test(id)) throw httpError(400, "INVALID_SHARE_ID", "Lien d'envoi invalide.");
const meta = store.metas.get(id);
if (!meta || meta.expiresAt <= now()) throw shareNotFound();
const expected = Buffer.from(meta.deleteTokenHash, "hex");
if (!timingSafeEqual(tokenHash(req.headers["x-share-delete-token"] || ""), expected)) {
throw httpError(403, "SHARE_FORBIDDEN", "Ce lien ne peut pas être révoqué depuis ce navigateur.");
}
await store.remove(id);
sendEmpty(res, 204);
}
async function handler(req, res) {
let url;
try {
url = new URL(req.url || "/", "http://localhost");
} catch {
return false;
}
if (url.pathname !== "/api/shares" && !url.pathname.startsWith("/api/shares/")) return false;
try {
if (req.method === "GET" && url.pathname === "/api/shares/config") {
rateLimit(req, "shares-config", limits.readsPerMinute * 2);
json(res, 200, { enabled, maxBytes: SHARE_MAX_BYTES, ttlMs: SHARE_TTL_MS });
return true;
}
if (!enabled) throw httpError(503, "SHARES_DISABLED", "L'envoi de toolbox est désactivé sur ce serveur.");
if (url.pathname === "/api/shares") {
if (req.method !== "POST") throw httpError(405, "METHOD_NOT_ALLOWED", "Méthode non prise en charge.");
await handleUpload(req, res);
return true;
}
const match = url.pathname.match(/^\/api\/shares\/([^/]+)(\/meta)?$/);
if (!match) throw httpError(404, "NOT_FOUND", "Route d'envoi introuvable.");
const [, id, metaRoute] = match;
if (req.method === "GET" && metaRoute) {
rateLimit(req, "shares-read", limits.readsPerMinute);
const meta = readableShare(id);
json(res, 200, { size: meta.size, expiresAt: meta.expiresAt, singleUse: meta.singleUse });
return true;
}
if (req.method === "GET") {
rateLimit(req, "shares-read", limits.readsPerMinute);
handleDownload(id, res);
return true;
}
if (req.method === "DELETE" && !metaRoute) {
rateLimit(req, "shares-read", limits.readsPerMinute);
await handleDelete(id, req, res);
return true;
}
throw httpError(405, "METHOD_NOT_ALLOWED", "Méthode non prise en charge.");
} catch (error) {
if (res.headersSent) {
res.destroy();
return true;
}
const status = error.status || 500;
// Le corps d'un envoi refusé n'est pas lu : la connexion est fermée pour ne pas le recevoir pour rien.
const closing = req.method === "POST" && !req.readableEnded;
json(res, status, { error: { code: error.code || "INTERNAL_ERROR", message: error.status ? error.message : "Une erreur serveur est survenue." } }, {
...(error.headers || {}),
...(closing ? { Connection: "close" } : {})
});
if (closing) res.once("finish", () => req.destroy());
if (!error.status) console.error(error);
return true;
}
}
handler.close = () => {
clearInterval(purgeTimer);
};
handler.store = store;
handler.limits = limits;
return handler;
}

165
services/shares/store.js Normal file
View file

@ -0,0 +1,165 @@
// Rôle : conserve sur disque les envois de toolbox chiffrés, le temps de leur validité, et les purge à l'échéance.
import { mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
import { rename, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
export const SHARE_ID_PATTERN = /^[A-Za-z0-9_-]{22}$/;
// Un fichier .part plus ancien n'appartient plus à aucun envoi en cours : ils sont tous coupés bien avant.
const ABANDONED_PART_MS = 60 * 60 * 1000;
function isMeta(value) {
return value && typeof value === "object"
&& Number.isSafeInteger(value.createdAt)
&& Number.isSafeInteger(value.expiresAt)
&& Number.isSafeInteger(value.size) && value.size > 0
&& typeof value.singleUse === "boolean"
&& Number.isSafeInteger(value.reads) && value.reads >= 0
&& typeof value.deleteTokenHash === "string";
}
function readJson(file) {
try {
return JSON.parse(readFileSync(file, "utf8"));
} catch {
return null;
}
}
function fileSize(file) {
try {
return statSync(file).size;
} catch {
return -1;
}
}
export class ShareStore {
constructor({ dir, now = Date.now }) {
this.dir = dir;
this.now = now;
this.metas = new Map();
// Envois à usage unique en cours de lecture : une seconde lecture simultanée ne doit pas les obtenir.
this.claimed = new Set();
this.totalBytes = 0;
this.load();
}
binPath(id) {
return join(this.dir, `${id}.bin`);
}
partPath(id) {
return join(this.dir, `${id}.part`);
}
metaPath(id) {
return join(this.dir, `${id}.json`);
}
// Lecture synchrone au démarrage : tout ce qui est incomplet, illisible ou expiré est supprimé.
load() {
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
const names = readdirSync(this.dir);
const now = this.now();
for (const name of names) {
const file = join(this.dir, name);
if (name.endsWith(".part") || name.endsWith(".tmp")) {
rmSync(file, { force: true });
continue;
}
if (!name.endsWith(".json")) continue;
const id = name.slice(0, -5);
const meta = readJson(file);
const binSize = fileSize(this.binPath(id));
if (!SHARE_ID_PATTERN.test(id) || !isMeta(meta) || meta.expiresAt <= now || binSize !== meta.size) {
rmSync(file, { force: true });
rmSync(this.binPath(id), { force: true });
continue;
}
this.metas.set(id, meta);
this.totalBytes += meta.size;
}
// Un contenu sans métadonnées vient d'une écriture interrompue.
for (const name of names) {
if (name.endsWith(".bin") && !this.metas.has(name.slice(0, -4))) rmSync(join(this.dir, name), { force: true });
}
}
get count() {
return this.metas.size;
}
// Renvoie un envoi encore lisible, ou null s'il est absent, expiré ou déjà pris par une lecture à usage unique.
get(id) {
const meta = this.metas.get(id);
if (!meta) return null;
if (meta.expiresAt <= this.now()) {
void this.remove(id).catch((error) => console.error(error));
return null;
}
if (this.claimed.has(id)) return null;
return meta;
}
async writeMeta(id, meta) {
const tmp = join(this.dir, `${id}.json.tmp`);
await writeFile(tmp, JSON.stringify(meta), { mode: 0o600 });
await rename(tmp, this.metaPath(id));
}
// Le contenu complet est déjà dans le fichier .part : il devient lisible une fois ses métadonnées écrites.
async commit(id, meta) {
await rename(this.partPath(id), this.binPath(id));
try {
await this.writeMeta(id, meta);
} catch (error) {
await rm(this.binPath(id), { force: true });
throw error;
}
this.metas.set(id, meta);
this.totalBytes += meta.size;
}
async recordRead(id) {
const meta = this.metas.get(id);
if (!meta) return;
meta.reads += 1;
await this.writeMeta(id, meta);
}
claim(id) {
this.claimed.add(id);
}
release(id) {
this.claimed.delete(id);
}
async remove(id) {
const meta = this.metas.get(id);
if (!meta) return false;
this.metas.delete(id);
this.claimed.delete(id);
this.totalBytes -= meta.size;
// Les métadonnées partent d'abord : un redémarrage entre les deux supprime le contenu orphelin.
await rm(this.metaPath(id), { force: true });
await rm(this.binPath(id), { force: true });
return true;
}
async purge() {
const now = this.now();
for (const [id, meta] of [...this.metas]) {
if (meta.expiresAt <= now) await this.remove(id);
}
for (const name of readdirSync(this.dir)) {
if (!name.endsWith(".part") && !name.endsWith(".tmp")) continue;
const file = join(this.dir, name);
try {
if (now - statSync(file).mtimeMs > ABANDONED_PART_MS) await rm(file, { force: true });
} catch {
// Le fichier a été renommé ou supprimé entre-temps.
}
}
}
}