Hide unrevealed Cards pulls and show the odds players really get

Keep a pending opening's cards out of the home highlight and collection until
they are revealed, and refuse transfers meanwhile. Odds now ignore rarities a
pack cannot give. Stable files gain an ETag so card images revalidate instead
of downloading again, and logging out clears the local collection copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-05 18:00:32 +01:00
parent b2e46b1d2a
commit 155187d01f
11 changed files with 167 additions and 26 deletions

View file

@ -66,6 +66,11 @@ function getCacheControl(root, file) {
return "no-cache";
}
function fileEtag(file) {
const { size, mtimeMs } = statSync(file);
return `W/"${size.toString(16)}-${Math.floor(mtimeMs).toString(16)}"`;
}
export function createStaticServer({ root = defaultRoot, publicRoot = defaultPublicRoot, cardsApi = null } = {}) {
async function handleRequest(req, res) {
if (cardsApi && await cardsApi(req, res)) return;
@ -79,9 +84,18 @@ export function createStaticServer({ root = defaultRoot, publicRoot = defaultPub
return;
}
const cacheControl = getCacheControl(root, file);
// `no-cache` impose de revalider : sans validateur, chaque visite retéléchargerait le fichier entier.
const etag = cacheControl === "no-cache" ? fileEtag(file) : null;
if (etag && String(req.headers["if-none-match"] || "").split(",").some((value) => value.trim() === etag)) {
res.writeHead(304, { ETag: etag, "Cache-Control": cacheControl });
res.end();
return;
}
res.writeHead(200, {
"Content-Type": types[extname(file)] || "application/octet-stream",
"Cache-Control": getCacheControl(root, file)
"Cache-Control": cacheControl,
...(etag ? { ETag: etag } : {})
});
// Un fichier remplacé pendant une livraison ne doit pas lever d'erreur non gérée.
createReadStream(file).on("error", () => res.destroy()).pipe(res);

View file

@ -238,6 +238,31 @@ export function isDrawableEdition(edition) {
return !edition.promotional && !edition.retired;
}
// Éditions tirables d'une collection.
export function collectionDrawableEditions(catalog, collectionId) {
const cardIds = new Set(catalog.cards.filter((card) => card.collectionId === collectionId).map((card) => card.id));
return catalog.editions.filter((edition) => cardIds.has(edition.cardId) && isDrawableEdition(edition));
}
// Paquet de la Boutique : les cartes de toutes les autres collections actives, plus les légendaires et mythiques de sa propre collection.
const SHOP_FEATURED_RARITIES = new Set(["legendary", "mythic"]);
export function shopPackPools(catalog, collectionId) {
const sourceOf = new Map(catalog.cards.map((card) => [card.id, card.collectionId]));
const activeIds = new Set(catalog.collections.filter((item) => item.active && item.packCategory !== "shop").map((item) => item.id));
const drawable = catalog.editions.filter(isDrawableEdition);
return {
others: drawable.filter((edition) => activeIds.has(sourceOf.get(edition.cardId))),
featured: drawable.filter((edition) => sourceOf.get(edition.cardId) === collectionId && SHOP_FEATURED_RARITIES.has(edition.rarity))
};
}
// Raretés qu'un paquet peut réellement donner, quels que soient ses taux.
export function drawableRarities(catalog, collection) {
const pools = collection.packCategory === "shop" ? shopPackPools(catalog, collection.id) : null;
const editions = pools ? [...pools.others, ...pools.featured] : collectionDrawableEditions(catalog, collection.id);
return catalog.rarities.map((rarity) => rarity.id).filter((rarity) => editions.some((edition) => edition.rarity === rarity));
}
export function holographicFinishIds(catalog) {
return new Set(catalog.finishes.filter((finish) => finish.effectPresetId != null).map((finish) => finish.id));
}
@ -297,5 +322,7 @@ export function buildPublishedCatalog(versionedCatalog, { variations = [], openi
}
export function publicCatalog(catalog) {
return JSON.parse(JSON.stringify(catalog));
const published = JSON.parse(JSON.stringify(catalog));
published.collections = published.collections.map((collection) => ({ ...collection, drawableRarities: drawableRarities(published, collection) }));
return published;
}

View file

@ -1,6 +1,6 @@
// Rôle : calcule la recharge des ouvertures et sélectionne les éditions d'un paquet.
import { randomInt } from "node:crypto";
import { isDrawableEdition } from "./catalog.js";
import { collectionDrawableEditions, shopPackPools } from "./catalog.js";
// Réglage de recharge unique (table recharge_settings) : un délai entre deux ouvertures et une réserve maximale.
// Un changement de délai s'applique aussi au temps déjà écoulé depuis la dernière recharge du joueur.
@ -53,18 +53,12 @@ function weightedChoice(entries, random = (max) => randomInt(max)) {
const pick = (random, max) => (random || ((limit) => randomInt(limit)))(max);
// Paquet de la Boutique : les cartes de toutes les autres collections actives, plus les légendaires et mythiques de sa propre collection.
// Quand une de ces deux raretés sort, `share` % des tirages reviennent aux cartes de sa collection, quel que soit leur nombre.
const FEATURED_RARITIES = new Set(["legendary", "mythic"]);
// Quand une légendaire ou une mythique sort du paquet de la Boutique, `share` % des tirages reviennent aux cartes de sa collection, quel que soit leur nombre.
export function drawShopPack(catalog, collectionId, random, share) {
const collection = catalog.collections.find((item) => item.id === collectionId && item.active);
if (!collection) throw Object.assign(new Error("Ce paquet n'est pas disponible."), { status: 404, code: "COLLECTION_UNAVAILABLE" });
if (!collection.dropWeights) throw new TypeError(`No drop rates for ${collectionId}.`);
const sourceOf = new Map(catalog.cards.map((card) => [card.id, card.collectionId]));
const activeIds = new Set(catalog.collections.filter((item) => item.active && item.packCategory !== "shop").map((item) => item.id));
const drawableEditions = catalog.editions.filter(isDrawableEdition);
const others = drawableEditions.filter((edition) => activeIds.has(sourceOf.get(edition.cardId)));
const featured = drawableEditions.filter((edition) => sourceOf.get(edition.cardId) === collectionId && FEATURED_RARITIES.has(edition.rarity));
const { others, featured } = shopPackPools(catalog, collectionId);
const ofRarity = (editions, rarity) => editions.filter((edition) => edition.rarity === rarity);
const rarityEntries = Object.entries(collection.dropWeights).filter(([rarity, weight]) => weight > 0 && (ofRarity(others, rarity).length || ofRarity(featured, rarity).length));
if (!rarityEntries.length) throw Object.assign(new Error("Aucune carte ne peut être tirée avec ces taux."), { status: 409, code: "NOTHING_DRAWABLE" });
@ -89,7 +83,7 @@ export function drawPack(catalog, collectionId, random, { weights = null, guaran
const rarityWeights = weights || collection.dropWeights;
if (!rarityWeights) throw new TypeError(`No drop rates for ${collectionId}.`);
const cardIds = new Set(catalog.cards.filter((card) => card.collectionId === collectionId).map((card) => card.id));
const editions = catalog.editions.filter((edition) => cardIds.has(edition.cardId) && isDrawableEdition(edition));
const editions = collectionDrawableEditions(catalog, collectionId);
const drawable = (rarity) => editions.some((edition) => edition.rarity === rarity);
const rarityEntries = Object.entries(rarityWeights).filter(([rarity, weight]) => weight > 0 && drawable(rarity));
if (!rarityEntries.length) throw Object.assign(new Error("Aucune carte ne peut être tirée avec ces taux."), { status: 409, code: "NOTHING_DRAWABLE" });

View file

@ -389,7 +389,7 @@ export class CardsService {
const pulls = this.db.prepare(`SELECT oc.edition_id, oc.position, o.id AS opening_id, o.created_at AS opened_at
FROM opening_cards oc
JOIN openings o ON o.id = oc.opening_id
WHERE o.player_id = ?
WHERE o.player_id = ? AND o.status = 'completed'
ORDER BY o.created_at DESC, oc.position DESC`).all(playerId);
let rarest = null;
for (const pull of pulls) {
@ -417,15 +417,27 @@ export class CardsService {
};
}
// Les cartes d'une ouverture en attente sont déjà attribuées, mais ne doivent pas se dévoiler avant la révélation.
visibleCollection(playerId, pendingOpeningId) {
const collection = this.collectionOf(playerId);
if (!pendingOpeningId) return collection;
const hidden = new Map();
for (const { edition_id: editionId } of this.db.prepare("SELECT edition_id FROM opening_cards WHERE opening_id = ?").all(pendingOpeningId)) hidden.set(editionId, (hidden.get(editionId) || 0) + 1);
return collection.map((entry) => {
const visible = { ...entry, quantity: entry.quantity - (hidden.get(entry.editionId) || 0) };
return { ...visible, spare: spareQuantity(visible) };
}).filter((entry) => entry.quantity > 0);
}
getState(playerId) {
const recharge = this.database.transaction(() => this.refreshRecharge(playerId));
this.expireTransfers();
const player = this.db.prepare("SELECT * FROM players WHERE id = ?").get(playerId);
if (!player) fail(404, "PLAYER_NOT_FOUND", "Profil introuvable.");
const owned = this.collectionOf(playerId);
const pending = this.db.prepare("SELECT id FROM openings WHERE player_id = ? AND status = 'pending' ORDER BY created_at DESC LIMIT 1").get(playerId);
const owned = this.visibleCollection(playerId, pending?.id);
const collection = owned.map((entry) => this.cardEntry(entry.editionId, entry));
const favorites = this.db.prepare("SELECT edition_id FROM favorites WHERE player_id = ?").all(playerId).map((row) => row.edition_id);
const pending = this.db.prepare("SELECT id FROM openings WHERE player_id = ? AND status = 'pending' ORDER BY created_at DESC LIMIT 1").get(playerId);
const history = this.db.prepare("SELECT event_type, entity_id, details_json, created_at FROM audit_log WHERE player_id = ? AND event_type IN (" + PLAYER_HISTORY_EVENTS.map(() => "?").join(", ") + ") ORDER BY created_at DESC LIMIT 100").all(playerId, ...PLAYER_HISTORY_EVENTS)
.map((row) => ({ type: row.event_type, entityId: row.entity_id, details: JSON.parse(row.details_json), createdAt: row.created_at }));
const transferRows = this.db.prepare("SELECT * FROM transfers WHERE initiator_id = ? OR recipient_id = ? ORDER BY created_at DESC LIMIT 50").all(playerId, playerId);
@ -679,6 +691,7 @@ export class CardsService {
const transferId = randomUUID();
this.database.transaction(() => {
this.expireTransfers();
if (this.db.prepare("SELECT 1 FROM openings WHERE player_id = ? AND status = 'pending'").get(playerId)) fail(409, "PENDING_OPENING", "Terminez d'abord l'ouverture en cours.");
this.requireRecipient(playerId, recipientId);
this.requireSpare(playerId, editionId);
const now = this.now();

View file

@ -140,6 +140,11 @@ test("cards API authenticates dev sessions and protects mutations", async (t) =>
const repeated = await call(handler, { method: "POST", path: "/api/cards/openings", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken, "idempotency-key": "one" }, body: { collectionId: "primordial-nebula" } });
assert.equal(repeated.json.opening.id, opened.json.opening.id);
const pendingState = await call(handler, { path: "/api/cards/state", headers: { cookie: sessionCookie } });
assert.equal(pendingState.status, 200);
assert.deepEqual(pendingState.json.collection, []);
const completed = await call(handler, { method: "POST", path: `/api/cards/openings/${opened.json.opening.id}/complete`, headers: { cookie: sessionCookie, "x-csrf-token": csrfToken } });
assert.equal(completed.status, 200);
const state = await call(handler, { path: "/api/cards/state", headers: { cookie: sessionCookie } });
assert.equal(state.status, 200);
assert.equal(state.json.collection.reduce((total, entry) => total + entry.quantity, 0), 3);

View file

@ -6,7 +6,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
import { spawnSync } from "node:child_process";
import { assertVersionedCatalogScope, buildPublishedCatalog, prepareVersionedCatalog, validateCardsCatalog, withGeneratedFinishes } from "../services/cards/catalog.js";
import { assertVersionedCatalogScope, buildPublishedCatalog, drawableRarities, publicCatalog, prepareVersionedCatalog, validateCardsCatalog, withGeneratedFinishes } from "../services/cards/catalog.js";
import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES, INITIAL_RECHARGE_SETTING, INITIAL_SHOP_SETTING } from "../services/cards/admin-seed.js";
import { planRecycling } from "../services/cards/stardust.js";
import { resolveMythicOpeningStyle, resolveOpeningEffect } from "../website/src/features/cards/openingEffects.js";
@ -14,6 +14,7 @@ import { summarizeReward } from "../website/src/features/cards/rewardText.js";
import { CardsDatabase } from "../services/cards/database.js";
import { calculateRecharge, drawPack, drawShopPack } from "../services/cards/game-rules.js";
import { CardsService, DEV_DISCORD_ID } from "../services/cards/service.js";
import { rarityPercentages } from "../website/src/features/cards/dropRates.js";
import { visibleCollections } from "../website/src/features/cards/collectionState.js";
import { backupCardsDatabase, restoreCardsDatabase, runScheduledBackup, verifyCardsDatabase } from "../services/cards/backup.js";
@ -409,12 +410,13 @@ test("opening is idempotent and server inventory owns the result", () => {
assert.equal(first.state.recharge.openingsBalance, 2);
const repeated = service.openPack(player.id, "primordial-nebula", "request-one");
assert.equal(repeated.opening.id, first.opening.id);
assert.deepEqual(repeated.state.collection.map((entry) => entry.quantity), [3]);
assert.equal(repeated.state.stats.openingsCount, 1);
assert.equal(repeated.state.rarestPull.id, first.opening.cards[2].id);
assert.equal(repeated.state.rarestPull.openedAt, now);
assert.equal(repeated.state.rarestPull.edition.rarity, "common");
service.completeOpening(player.id, first.opening.id);
assert.equal(database.db.prepare("SELECT quantity FROM collection_cards WHERE player_id = ?").get(player.id).quantity, 3);
const completed = service.completeOpening(player.id, first.opening.id);
assert.deepEqual(completed.collection.map((entry) => entry.quantity), [3]);
assert.equal(completed.rarestPull.id, first.opening.cards[2].id);
assert.equal(completed.rarestPull.openedAt, now);
assert.equal(completed.rarestPull.edition.rarity, "common");
now += INITIAL_RECHARGE_SETTING.intervalMs;
assert.equal(service.getState(player.id).recharge.openingsBalance, 3);
database.close();
@ -654,6 +656,51 @@ test("database backup passes integrity checks and restores ownership", async ()
}
});
test("a pending opening stays hidden from the player state until it is completed", () => {
const database = new CardsDatabase(":memory:");
const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000, random: () => 0 });
const player = service.upsertPlayer({ discordId: "spoiler", displayName: "Spoiler" });
const other = service.upsertPlayer({ discordId: "spoiler-other", displayName: "Autre" });
const { opening, state: pendingState } = service.openPack(player.id, "primordial-nebula", "spoiler-pack");
const [editionId] = opening.cards.map((card) => card.editionId);
assert.equal(pendingState.pendingOpening.id, opening.id);
assert.equal(pendingState.rarestPull, null);
assert.deepEqual(pendingState.collection, []);
assert.equal(pendingState.recycling.count, 0);
assert.throws(() => service.createTransfer(player.id, { type: "gift", recipientId: other.id, editionId }), /ouverture en cours/);
const completed = service.completeOpening(player.id, opening.id);
assert.equal(completed.pendingOpening, null);
assert.ok(completed.rarestPull);
assert.equal(completed.collection.reduce((total, entry) => total + entry.quantity, 0), 3);
database.close();
});
test("displayed odds only count the rarities a pack can really give", () => {
const collectionOf = (published, id) => published.collections.find((collection) => collection.id === id);
const states = [...INITIAL_COLLECTION_STATES, { collectionId: "stardust", active: true }];
const rates = [...INITIAL_DROP_RATES, { collectionId: "stardust", rarityWeights: INITIAL_DROP_RATES[0].rarityWeights }];
const empty = buildPublishedCatalog(baseCatalog, { collectionStates: states, dropRates: rates });
assert.deepEqual(drawableRarities(empty, collectionOf(empty, "primordial-nebula")), ["common", "rare", "epic", "legendary"]);
assert.deepEqual(drawableRarities(empty, collectionOf(empty, "stardust")), ["common", "rare", "epic", "legendary"]);
assert.deepEqual(publicCatalog(empty).collections.find((collection) => collection.id === "primordial-nebula").drawableRarities, ["common", "rare", "epic", "legendary"]);
const withMythic = buildPublishedCatalog(baseCatalog, { variations: TEST_MYTHIC_VARIATIONS, collectionStates: states, dropRates: rates });
assert.equal(drawableRarities(withMythic, collectionOf(withMythic, "astral-genesis")).includes("mythic"), true);
assert.equal(drawableRarities(withMythic, collectionOf(withMythic, "primordial-nebula")).includes("mythic"), false);
assert.equal(drawableRarities(withMythic, collectionOf(withMythic, "stardust")).includes("mythic"), true);
const retired = buildPublishedCatalog(baseCatalog, { variations: TEST_MYTHIC_VARIATIONS.map((variation) => ({ ...variation, status: "retired" })), collectionStates: states, dropRates: rates });
assert.equal(drawableRarities(retired, collectionOf(retired, "astral-genesis")).includes("mythic"), false);
const weights = { common: 64, rare: 24, epic: 8, legendary: 3, mythic: 1 };
const percent = (drawable) => Object.fromEntries(rarityPercentages(empty.rarities, weights, drawable).map(({ rarity, percent: value }) => [rarity.id, value]));
assert.equal(percent(undefined).mythic, 1);
const filtered = percent(["common", "rare", "epic", "legendary"]);
assert.equal(filtered.mythic, 0);
assert.ok(Math.abs(Object.values(filtered).reduce((total, value) => total + value, 0) - 100) < 1e-9);
assert.ok(Math.abs(filtered.common - 64 / 99 * 100) < 1e-9);
});
test("restoring replaces the database even when the stopped service left a write-ahead log", async () => {
const directory = await mkdtemp(join(tmpdir(), "sokko-cards-restore-wal-"));
const live = join(directory, "live.sqlite");

View file

@ -65,3 +65,35 @@ test("production server separates stable files from versioned assets", async (t)
assert.equal(missingBundle.status, 404);
assert.equal(missingBundle.headers.get("cache-control"), "no-store");
});
test("stable files can be revalidated with an ETag while no-store and immutable responses stay unconditional", async (t) => {
const root = await mkdtemp(join(tmpdir(), "sokko-server-etag-"));
await writeFixture(root, "index.html", "<main>Sokko G</main>");
await writeFixture(root, "assets/index-Ab12_cd34.js", "console.log('versioned');");
const imageFile = await writeFixture(root, "static/img/card.webp", "image-v1");
const server = createStaticServer({ root, publicRoot: root });
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
t.after(async () => {
await new Promise((resolve) => server.close(resolve));
await rm(root, { recursive: true, force: true });
});
const url = (path) => `http://127.0.0.1:${server.address().port}${path}`;
const first = await fetch(url("/static/img/card.webp"));
const etag = first.headers.get("etag");
assert.match(etag, /^W\/"/);
assert.equal(await first.text(), "image-v1");
const unchanged = await fetch(url("/static/img/card.webp"), { headers: { "If-None-Match": `"other", ${etag}` } });
assert.equal(unchanged.status, 304);
assert.equal(unchanged.headers.get("cache-control"), "no-cache");
assert.equal(await unchanged.text(), "");
await writeFile(imageFile, "image-version-2");
const replaced = await fetch(url("/static/img/card.webp"), { headers: { "If-None-Match": etag } });
assert.equal(replaced.status, 200);
assert.equal(await replaced.text(), "image-version-2");
assert.equal((await fetch(url("/"))).headers.get("etag"), null);
assert.equal((await fetch(url("/assets/index-Ab12_cd34.js"))).headers.get("etag"), null);
});

View file

@ -2,7 +2,7 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { navigate } from "../../router/hashRouter.js";
import { AdminPanel } from "./admin/AdminPanel.jsx";
import { readLatestCardsCache, writeCardsCache } from "./cardCache.js";
import { clearCardsCache, readLatestCardsCache, writeCardsCache } from "./cardCache.js";
import { devLogin, loadCardsSession, loadCardsState, logoutCards } from "./cardsApi.js";
import { CardsAccount, CardsDashboardLayout } from "./CardsDashboard.jsx";
import { CardsHomePanel } from "./CardsHomePanel.jsx";
@ -61,6 +61,7 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", adminM
const session = await loadCardsSession();
if (!active) return;
if (!session.authenticated) {
void clearCardsCache().catch(() => {});
setStatus("anonymous");
return;
}
@ -184,6 +185,7 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", adminM
async function logout() {
await logoutCards();
await clearCardsCache().catch(() => {});
setState(null);
setStatus("anonymous");
}

View file

@ -106,7 +106,7 @@ function OpeningOdds({ catalog, opening, collection, content, shopShare }) {
if (collection?.packCategory === "shop") details.push(`${shopShare} % ${content.shopShare} ${collection.name}`);
return <section className="nds-panel nebula-opening-odds" aria-labelledby="nebula-opening-odds-title">
<h3 id="nebula-opening-odds-title">{content.probabilities}</h3>
<ul className="nebula-shop-rates" aria-labelledby="nebula-opening-odds-title">{rarityPercentages(catalog.rarities, weights).map(({ rarity, percent }) => <li key={rarity.id} data-rarity={rarity.id}><span>{rarity.label}</span><strong>{formatPercent(percent)}</strong></li>)}</ul>
<ul className="nebula-shop-rates" aria-labelledby="nebula-opening-odds-title">{rarityPercentages(catalog.rarities, weights, collection?.drawableRarities).map(({ rarity, percent }) => <li key={rarity.id} data-rarity={rarity.id}><span>{rarity.label}</span><strong>{formatPercent(percent)}</strong></li>)}</ul>
{details.length > 0 && <p className="nebula-form-help">{details.join(" · ")}</p>}
</section>;
}

View file

@ -30,6 +30,11 @@ export function writeCardsCache(state, catalog) {
return transact("readwrite", (store) => store.put({ playerId: state.player.id, format: SNAPSHOT_FORMAT, savedAt: Date.now(), state, catalog }));
}
// La copie locale n'appartient qu'au joueur connecté : un autre utilisateur du navigateur ne doit pas la retrouver.
export function clearCardsCache() {
return transact("readwrite", (store) => store.clear());
}
export async function readLatestCardsCache() {
const entries = await transact("readonly", (store) => store.getAll());
return entries.filter((entry) => entry.format === SNAPSHOT_FORMAT).sort((left, right) => right.savedAt - left.savedAt)[0] || null;

View file

@ -6,9 +6,11 @@ export function recommendedWeights(rarities) {
}
// Pourcentage de chaque rareté pour une carte tirée, dans l'ordre des raretés du catalogue.
export function rarityPercentages(rarities, weights = {}) {
const total = rarities.reduce((sum, rarity) => sum + (Number(weights[rarity.id]) || 0), 0);
return rarities.map((rarity) => ({ rarity, weight: Number(weights[rarity.id]) || 0, percent: total ? (Number(weights[rarity.id]) || 0) / total * 100 : 0 }));
// `drawable` : raretés que le paquet peut réellement donner, les autres ne comptent pas dans le tirage. Sans cette liste, les poids sont pris tels quels.
export function rarityPercentages(rarities, weights = {}, drawable = null) {
const weightOf = (rarity) => (!drawable || drawable.includes(rarity.id) ? Number(weights[rarity.id]) || 0 : 0);
const total = rarities.reduce((sum, rarity) => sum + weightOf(rarity), 0);
return rarities.map((rarity) => ({ rarity, weight: weightOf(rarity), percent: total ? weightOf(rarity) / total * 100 : 0 }));
}
export function formatPercent(value, maximumFractionDigits = 2) {