Send a toolbox through an encrypted link
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:
parent
957bfdc86f
commit
bec9ea5b2f
43 changed files with 2349 additions and 59 deletions
377
services/shares/api.js
Normal file
377
services/shares/api.js
Normal 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;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue