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

@ -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);
});