Fix the audit's concurrency, stale state and delivery findings
Some checks failed
Validate and deploy Sokko G / validate (push) Failing after 19m40s
Validate and deploy Sokko G / deploy (push) Has been skipped

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>
This commit is contained in:
Shinuwa 2026-11-20 21:38:12 +01:00
parent 0571a935d6
commit 067a4a8fd6
20 changed files with 391 additions and 73 deletions

View file

@ -42,11 +42,6 @@ export function buildCommons(catalog) {
}));
}
// Communes à stats du catalogue, prêtes à équiper : { cardId, stats, tags }.
export function statCommons(catalog) {
return catalog.cards.filter((card) => card.expedition?.equipment?.stats).map((card) => ({ cardId: card.id, stats: card.expedition.equipment.stats, synergyStat: card.expedition.equipment.synergyStat ?? null, tags: card.expedition.tags }));
}
// Situations d'une destination : chaque condition, avec chaque paire de dangers qui se suivent.
export function destinationSituations(destination) {
const situations = [];

View file

@ -118,6 +118,8 @@ export function createSharesApiHandler({
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");
@ -143,11 +145,14 @@ export function createSharesApiHandler({
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) {
// 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);
if (ipEntries.length >= limits.ipDailyUploads || ipEntries.reduce((sum, entry) => sum + entry.bytes, 0) + size > limits.ipDailyBytes) {
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) {
@ -159,10 +164,29 @@ export function createSharesApiHandler({
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.");
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;
return { key, release };
}
function receiveBody(req, file, size) {
@ -233,13 +257,11 @@ export function createSharesApiHandler({
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 { key, release } = await admitUpload(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();
@ -254,8 +276,8 @@ export function createSharesApiHandler({
await rm(part, { force: true });
throw error;
} finally {
uploadsInFlight -= 1;
reservedBytes -= size;
// L'envoi réussi est déjà compté dans le store et l'historique de sa connexion : sa réservation se libère.
release();
}
}

View file

@ -40,6 +40,9 @@ export class ShareStore {
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();
}
@ -101,6 +104,15 @@ export class ShareStore {
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 });
@ -124,7 +136,8 @@ export class ShareStore {
const meta = this.metas.get(id);
if (!meta) return;
meta.reads += 1;
await this.writeMeta(id, meta);
// 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) {
@ -142,8 +155,10 @@ export class ShareStore {
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 });
await this.queue(id, async () => {
await rm(this.metaPath(id), { force: true });
await rm(this.binPath(id), { force: true });
});
return true;
}