sokko-g/services/shares/api.js
Shinuwa 067a4a8fd6
Some checks failed
Validate and deploy Sokko G / validate (push) Failing after 19m40s
Validate and deploy Sokko G / deploy (push) Has been skipped
Fix the audit's concurrency, stale state and delivery findings
Share uploads now reserve their slot, bytes and per-IP count before the
disk check, so simultaneous uploads can no longer exceed the limits.
Writes to a share's metadata run one after another, and a revocation can
no longer be undone by a pending read count.

The TCG page ignores a state reload that started before or during a
mutation, the last mutation wins, and returning to the page triggers a
single reload. The card cache confirms writes only once the IndexedDB
transaction completes and shows only the current player's copy. The
administration panel loads on demand, which shrinks the TCG chunk from
311.6 to 191.8 kB.

A new /api/health route answers 503 when the cards or shares API failed
to start. The deploy script ships the commit's production dependencies
with the build, waits up to 30 s for a healthy server instead of trusting
systemctl is-active, and restores node_modules on rollback. Both Forgejo
workflows check the route on the public site. The updated script applies
once reinstalled on the server.

Unused helpers, the ignored join role and duplicate button selectors are
removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:38:20 +01:00

399 lines
16 KiB
JavaScript

// 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;
// Envois en cours par connexion : comptés dans son quota du jour avant même d'être terminés.
const ipInFlight = new Map();
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. Les compteurs sont vérifiés et réservés
// dans le même passage synchrone : des envois simultanés ne peuvent pas valider la même place avant qu'un seul ne la prenne.
async function admitUpload(req, size) {
const key = ipKey(req);
const ipEntries = recentIpUploads(key);
const ipPending = ipInFlight.get(key) || { uploads: 0, bytes: 0 };
const ipBytes = ipEntries.reduce((sum, entry) => sum + entry.bytes, 0) + ipPending.bytes;
if (ipEntries.length + ipPending.uploads >= limits.ipDailyUploads || ipBytes + 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.");
}
uploadsInFlight += 1;
reservedBytes += size;
ipInFlight.set(key, { uploads: ipPending.uploads + 1, bytes: ipPending.bytes + size });
let released = false;
const release = () => {
if (released) return;
released = true;
uploadsInFlight -= 1;
reservedBytes -= size;
const pending = ipInFlight.get(key);
if (pending.uploads <= 1) ipInFlight.delete(key);
else ipInFlight.set(key, { uploads: pending.uploads - 1, bytes: pending.bytes - size });
};
try {
// `reservedBytes` comprend déjà cet envoi.
if (await freeBytes() - reservedBytes < limits.minFreeBytes) {
throw refuse(507, "SHARE_STORAGE_FULL", "Le service d'envoi est plein. Réessayez plus tard.");
}
} catch (error) {
release();
throw error;
}
return { key, release };
}
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, release } = await admitUpload(req, size);
const id = randomBytes(16).toString("base64url");
const deleteToken = randomBytes(24).toString("base64url");
const part = store.partPath(id);
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 {
// L'envoi réussi est déjà compté dans le store et l'historique de sa connexion : sa réservation se libère.
release();
}
}
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;
}