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>
180 lines
5.6 KiB
JavaScript
180 lines
5.6 KiB
JavaScript
// 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();
|
|
// É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.
|
|
}
|
|
}
|
|
}
|
|
}
|