Document how server.mjs keeps the site up when an API is misconfigured and reports it on /api/health, the cache and CSP policy, the share API's synchronous reservation, the trust placed in X-Forwarded-For, the hooks main.jsx wires once, and how to run each script. The deploy script header now recalls that CI runs the copy installed on the server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
193 lines
6.2 KiB
JavaScript
193 lines
6.2 KiB
JavaScript
/**
|
|
* @file Stockage sur disque des envois de toolbox chiffrés : contenu et métadonnées par envoi, lecture à usage
|
|
* unique, compteur de lectures, purge à l'échéance et nettoyage au démarrage.
|
|
*
|
|
* Utilisé par : services/shares/api.js.
|
|
* Attention :
|
|
* - Les écritures et suppressions d'un même envoi passent dans l'ordre d'arrivée : deux téléchargements ne se
|
|
* partagent pas un fichier temporaire, et une suppression ne peut pas être suivie d'une écriture qui le
|
|
* recréerait.
|
|
* - Au démarrage, tout ce qui est incomplet, illisible ou expiré est supprimé ; les envois ne sont pas
|
|
* sauvegardés.
|
|
* @see docs/STORAGE_SCHEMA.md
|
|
*/
|
|
|
|
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();
|
|
// Écritures et suppressions de chaque envoi, dans leur ordre d'arrivée : deux téléchargements simultanés ne se partagent
|
|
// pas le même fichier temporaire, et une suppression ne peut pas être suivie d'une écriture qui recréerait les métadonnées.
|
|
this.pending = new Map();
|
|
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;
|
|
}
|
|
|
|
queue(id, task) {
|
|
const next = (this.pending.get(id) || Promise.resolve()).catch(() => {}).then(task);
|
|
this.pending.set(id, next);
|
|
next.catch(() => {}).finally(() => {
|
|
if (this.pending.get(id) === next) this.pending.delete(id);
|
|
});
|
|
return next;
|
|
}
|
|
|
|
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;
|
|
// Le compteur en mémoire fait foi ; chaque écriture enregistre sa valeur du moment, tant que l'envoi existe.
|
|
await this.queue(id, () => (this.metas.get(id) === meta ? this.writeMeta(id, meta) : undefined));
|
|
}
|
|
|
|
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 this.queue(id, async () => {
|
|
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.
|
|
}
|
|
}
|
|
}
|
|
}
|