Tighten the remaining Cards and dev server security defaults
All checks were successful
Validate and deploy Sokko G / validate (push) Successful in 19m52s
Validate and deploy Sokko G / deploy (push) Successful in 10s

Session and OAuth cookies now carry the __Host- prefix over HTTPS, so another
application of the domain cannot set them. The public configuration route has
a request limit, the trader list reads every player in one query, and new
campaign codes need eight characters while existing ones keep working.

The Vite server now listens on 127.0.0.1 unless HOST says otherwise, because
it gives administrator rights to any visitor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-06 14:27:22 +01:00
parent 9b6da88ed3
commit 9ce0c3e33a
9 changed files with 137 additions and 43 deletions

View file

@ -1,6 +1,7 @@
# Port du serveur. Ne pas recopier dans /etc/sokko-g/cards.env : cette valeur prendrait le dessus sur le port de production.
PORT=5173
# Adresse d'écoute du serveur Node. En production, à définir dans le .env du site sur son adresse privée, pour que seul le proxy le joigne.
# Vite écoute sur 127.0.0.1 si elle est vide ; 0.0.0.0 ouvre le site de dev et son compte administrateur factice à tout le réseau.
HOST=
# Sokko TCG reste désactivé en production tant que ces valeurs ne sont pas configurées.

View file

@ -31,7 +31,7 @@ L'interface cible les fenêtres d'ordinateur en plein écran ou en demi-écran.
npm run dev
```
Par défaut, le site démarre sur `http://localhost:5173`.
Par défaut, le site démarre sur `http://localhost:5173` et n'est joignable que depuis cette machine. Pour l'ouvrir à d'autres appareils, définir `HOST=0.0.0.0` : le compte administrateur factice du mode développement devient alors accessible à tout le réseau.
Pour générer la version statique de production :

View file

@ -1299,14 +1299,14 @@ test("administrator navigates sections, manages mythic content and previews visu
await expect(campaignForm.getByLabel("Sans date d’expiration")).toBeChecked();
await expect(campaignForm.getByLabel("Valable jusqu’au")).toHaveCount(0);
await campaignForm.getByRole("button", { name: "Générer" }).click();
await expect(campaignForm.getByLabel("Code à annoncer (4 à 24 caractères)")).toHaveValue(/^[2-9A-HJKMNP-Z]{4}-[2-9A-HJKMNP-Z]{4}$/);
await campaignForm.getByLabel("Code à annoncer (4 à 24 caractères)").fill("dragon");
await expect(campaignForm.getByLabel("Code à annoncer (8 à 24 caractères)")).toHaveValue(/^[2-9A-HJKMNP-Z]{4}-[2-9A-HJKMNP-Z]{4}$/);
await campaignForm.getByLabel("Code à annoncer (8 à 24 caractères)").fill("dragon-01");
await campaignForm.getByLabel("Sans limite d’utilisations").uncheck();
await campaignForm.getByLabel("Utilisations maximum").fill("1");
await campaignForm.getByLabel("Sans date d’expiration").uncheck();
await expect(campaignForm.getByLabel("Valable jusqu’au")).toBeVisible();
await expect(campaignForm.locator(".nebula-admin-campaign-summary")).toContainText("Carte Dragon du Néant Étoilé (Mythique · Prisme spectral — Aurore)");
await expect(campaignForm.locator(".nebula-admin-campaign-summary")).toContainText("Le code DRAGON, utilisable 1 fois, jusqu’au");
await expect(campaignForm.locator(".nebula-admin-campaign-summary")).toContainText("Le code DRAGON-01, utilisable 1 fois, jusqu’au");
await createButton.click();
const generated = page.locator(".nebula-admin-generated");
await expect(generated.getByRole("heading", { name: "Campagne « Cadeau dragon » créée" })).toBeVisible();
@ -1328,8 +1328,8 @@ test("administrator navigates sections, manages mythic content and previews visu
await packItem.getByLabel("Quantité").fill("2");
await packItem.getByRole("radio", { name: "Une rareté minimum" }).click();
await chooseOption(packItem, "Rareté garantie", "Légendaire");
await campaignForm.getByLabel("Code à annoncer (4 à 24 caractères)").fill("e2e live");
await expect(campaignForm.getByLabel("Code à annoncer (4 à 24 caractères)")).toHaveValue("E2E-LIVE");
await campaignForm.getByLabel("Code à annoncer (8 à 24 caractères)").fill("e2e live");
await expect(campaignForm.getByLabel("Code à annoncer (8 à 24 caractères)")).toHaveValue("E2E-LIVE");
await expect(campaignForm.locator(".nebula-admin-campaign-missing")).toHaveCount(0);
await expect(campaignForm.locator(".nebula-admin-campaign-summary")).toContainText("+ 2 × Paquet Genèse Astrale · au moins 1 carte légendaire ou mieux garantie");
await expect(campaignForm.locator(".nebula-admin-campaign-summary")).toContainText("Le code E2E-LIVE, utilisable sans limite, sans date d’expiration.");
@ -1384,7 +1384,7 @@ test("players give cards and answer trade proposals from two accounts", async ({
const { token } = JSON.parse(await readFile(join(tmpdir(), "sokkog-cards-e2e-partner.json"), "utf8"));
const partnerContext = await browser.newContext({ baseURL: "http://127.0.0.1:4180" });
await partnerContext.addCookies([{ name: "sokkog_cards_session", value: token, url: "http://127.0.0.1:4180" }]);
await partnerContext.addCookies([{ name: "__Host-sokkog_cards_session", value: token, domain: "127.0.0.1", path: "/", secure: true, httpOnly: true, sameSite: "Lax" }]);
const partner = await partnerContext.newPage();
await partner.goto("/#/cards/transfers");
@ -1553,8 +1553,10 @@ test("a player reads the privacy notice and deletes the account for good", async
const { token } = JSON.parse(await readFile(join(tmpdir(), "sokkog-cards-e2e-partner.json"), "utf8"));
const partnerContext = await browser.newContext({ baseURL: "http://127.0.0.1:4180" });
await partnerContext.addCookies([{ name: "sokkog_cards_session", value: token, url: "http://127.0.0.1:4180" }]);
const { traders } = await (await partnerContext.request.get("/api/cards/traders")).json();
await partnerContext.addCookies([{ name: "__Host-sokkog_cards_session", value: token, domain: "127.0.0.1", path: "/", secure: true, httpOnly: true, sameSite: "Lax" }]);
const partnerPage = await partnerContext.newPage();
await partnerPage.goto("http://127.0.0.1:4180/");
const { traders } = await partnerPage.evaluate(() => globalThis.fetch("/api/cards/traders").then((response) => response.json()));
expect(traders.map((trader) => trader.displayName)).not.toContain("Version développement");
await partnerContext.close();

View file

@ -49,16 +49,26 @@ function parseCookies(req) {
}));
}
// Avec __Host-, le navigateur refuse qu'une autre application du domaine pose ces cookies. Ce préfixe exige Secure et Path=/ :
// sans HTTPS, en développement, le nom reste donc nu.
function cookieName(name, secure) {
return secure ? `__Host-${name}` : name;
}
function cookie(name, value, secure, maxAge) {
return `${cookieName(name, secure)}=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? "; Secure" : ""}`;
}
function sessionCookie(value, secure, maxAge = 30 * 24 * 60 * 60) {
return `sokkog_cards_session=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? "; Secure" : ""}`;
return cookie("sokkog_cards_session", value, secure, maxAge);
}
function stateCookie(value, secure, maxAge = 600) {
return `sokkog_cards_oauth_state=${encodeURIComponent(value)}; Path=/api/cards/auth; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? "; Secure" : ""}`;
return cookie("sokkog_cards_oauth_state", value, secure, maxAge);
}
function oauthReturnCookie(value, secure, maxAge = 600) {
return `sokkog_cards_oauth_return=${encodeURIComponent(value)}; Path=/api/cards/auth; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? "; Secure" : ""}`;
return cookie("sokkog_cards_oauth_return", value, secure, maxAge);
}
function cardsReturnPath(value) {
@ -193,6 +203,8 @@ export function createCardsApiHandler({
if (!url.pathname.startsWith("/api/cards")) return false;
try {
if (req.method === "GET" && url.pathname === "/api/cards/config") {
// Compteur séparé : chaque visite du site lit cette route, mais elle renvoie tout le catalogue.
rateLimit(req, "config", apiRateLimit * 2);
json(res, 200, {
enabled,
devAuth: enabled && devAuth,
@ -210,7 +222,7 @@ export function createCardsApiHandler({
}
const cookies = parseCookies(req);
const session = service.getSession(cookies.sokkog_cards_session);
const session = service.getSession(cookies[cookieName("sokkog_cards_session", secureCookies)]);
if (req.method === "GET" && url.pathname === "/api/cards/auth/discord") {
if (!env.DISCORD_CLIENT_ID || !env.DISCORD_CLIENT_SECRET) throw Object.assign(new Error("Connexion Discord non configurée."), { status: 503, code: "DISCORD_NOT_CONFIGURED" });
@ -225,11 +237,11 @@ export function createCardsApiHandler({
if (req.method === "GET" && url.pathname === "/api/cards/auth/callback") {
const state = url.searchParams.get("state");
const code = url.searchParams.get("code");
const returnTo = cardsReturnPath(cookies.sokkog_cards_oauth_return);
const returnTo = cardsReturnPath(cookies[cookieName("sokkog_cards_oauth_return", secureCookies)]);
const clearedCookies = [stateCookie("", secureCookies, 0), oauthReturnCookie("", secureCookies, 0)];
// Cette route est une navigation : le joueur revient toujours sur le site, jamais sur une réponse JSON.
const fail = (reason) => redirect(res, `${publicOrigin(req)}/?cardsAuth=${reason}#${returnTo}`, clearedCookies);
if (!state || state !== cookies.sokkog_cards_oauth_state) {
if (!state || state !== cookies[cookieName("sokkog_cards_oauth_state", secureCookies)]) {
fail("expired");
return true;
}
@ -274,7 +286,7 @@ export function createCardsApiHandler({
}
if (req.method === "POST" && url.pathname === "/api/cards/auth/logout") {
service.deleteSession(cookies.sokkog_cards_session);
service.deleteSession(cookies[cookieName("sokkog_cards_session", secureCookies)]);
res.setHeader("Set-Cookie", sessionCookie("", secureCookies, 0));
json(res, 200, { ok: true });
return true;

View file

@ -669,12 +669,25 @@ export class CardsService {
listTraders(playerId) {
this.expireTransfers();
const rows = this.db.prepare("SELECT id, display_name, avatar_url FROM players WHERE id != ? AND deleted_at IS NULL ORDER BY display_name COLLATE NOCASE").all(playerId);
// Une seule requête pour tous les joueurs : cette route est ouverte à tout joueur connecté et le serveur est bloqué pendant la lecture.
const duplicates = new Map();
for (const row of this.db.prepare(`SELECT c.player_id, c.edition_id, c.quantity, COUNT(t.id) AS reserved
FROM collection_cards c
LEFT JOIN transfers t ON t.initiator_id = c.player_id AND t.offered_edition_id = c.edition_id AND t.status = 'open'
WHERE c.quantity > 1
GROUP BY c.player_id, c.edition_id
ORDER BY c.acquired_at DESC, c.edition_id`).all()) {
const spare = spareQuantity(row);
if (!spare) continue;
if (!duplicates.has(row.player_id)) duplicates.set(row.player_id, []);
duplicates.get(row.player_id).push({ editionId: row.edition_id, spare });
}
return {
traders: rows.map((row) => ({
id: row.id,
displayName: row.display_name,
avatarUrl: row.avatar_url,
duplicates: this.collectionOf(row.id).filter((entry) => entry.spare > 0).map(({ editionId, spare }) => ({ editionId, spare }))
duplicates: duplicates.get(row.id) || []
}))
};
}
@ -822,7 +835,8 @@ export class CardsService {
const normalized = normalizeReward(reward, this.catalog);
if (!name?.trim() || name.trim().length > 80) fail(400, "CAMPAIGN_INVALID", "Donnez un nom de 1 à 80 caractères à la campagne.");
const code = String(rawCode || "").trim().toUpperCase();
if (!/^[A-Z0-9][A-Z0-9-]{3,23}$/.test(code)) fail(400, "CAMPAIGN_INVALID", "Code : 4 à 24 caractères, lettres, chiffres et tirets.");
// Un code court se devine : les anciens restent utilisables, seuls les nouveaux sont concernés.
if (!/^[A-Z0-9][A-Z0-9-]{7,23}$/.test(code)) fail(400, "CAMPAIGN_INVALID", "Code : 8 à 24 caractères, lettres, chiffres et tirets.");
const limit = maxClaims == null ? null : Number(maxClaims);
if (limit !== null && (!Number.isInteger(limit) || limit < 1 || limit > 100_000)) fail(400, "CAMPAIGN_INVALID", "Entre 1 et 100 000 utilisations, ou illimité.");
const expiry = this.campaignExpiry(expiresAt);

View file

@ -332,3 +332,30 @@ test("without explicit settings the game and the fake admin login stay off, what
assert.equal(json.devAuth, false);
assert.equal((await call(enabledOnly, { method: "POST", path: "/api/cards/auth/dev" })).status, 404);
});
test("the public configuration route has its own request limit", async (t) => {
const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: false, devAuth: false, databasePath: ":memory:", env: { NODE_ENV: "test" }, apiRateLimit: 2 });
t.after(() => handler.close());
const statuses = [];
for (let index = 0; index < 5; index += 1) statuses.push((await call(handler, { path: "/api/cards/config" })).status);
assert.deepEqual(statuses, [200, 200, 200, 200, 429]);
});
test("cookies carry the __Host- prefix over HTTPS and only the prefixed session is read", async (t) => {
const env = { NODE_ENV: "production", CARDS_ENABLED: "true", CARDS_DB_PATH: ":memory:", CARDS_PUBLIC_ORIGIN: "https://cards.invalid", CARDS_PRIVACY_CONTACT: "a@cards.invalid", CARDS_PRIVACY_CONTROLLER: "Test", DISCORD_CLIENT_ID: "id", DISCORD_CLIENT_SECRET: "secret" };
const handler = createCardsApiHandler({ projectRoot: resolve("."), env });
t.after(() => handler.close());
const authorization = await call(handler, { path: "/api/cards/auth/discord" });
const cookies = authorization.headers["set-cookie"];
assert.equal(cookies.length, 2);
for (const value of cookies) {
assert.match(value, /^__Host-sokkog_cards_oauth_(?:state|return)=/);
assert.match(value, /; Path=\/;/);
assert.match(value, /; Secure$/);
assert.doesNotMatch(value, /Domain=/i);
}
const player = handler.service.upsertPlayer({ discordId: "player", displayName: "Joueur" });
const { token } = handler.service.createSession(player.id);
assert.equal((await call(handler, { path: "/api/cards/session", headers: { cookie: `sokkog_cards_session=${token}` } })).json.authenticated, false);
assert.equal((await call(handler, { path: "/api/cards/session", headers: { cookie: `__Host-sokkog_cards_session=${token}` } })).json.authenticated, true);
});

View file

@ -543,16 +543,16 @@ test("trades and gifts move duplicates only and campaign claims add cards", () =
const campaign = service.createCampaign(admin.id, {
name: "Premiers explorateurs",
reward: { items: [{ type: "card", editionId: "aurora-wolf-standard" }] },
code: "explo",
code: "explo-01",
maxClaims: 1,
expiresAt: now + 60_000
});
assert.equal(campaign.campaign.code, "EXPLO");
const claimed = service.claimCampaign(player.id, "explo");
assert.equal(campaign.campaign.code, "EXPLO-01");
const claimed = service.claimCampaign(player.id, "explo-01");
assert.deepEqual(claimed.reward, { items: [{ type: "card", editionId: "aurora-wolf-standard", quantity: 1 }] });
assert.equal(quantity(player.id, "aurora-wolf-standard"), 1);
assert.throws(() => service.claimCampaign(player.id, "EXPLO"), /déjà reçu/);
assert.throws(() => service.claimCampaign(admin.id, "EXPLO"), /nombre maximal/);
assert.throws(() => service.claimCampaign(player.id, "EXPLO-01"), /déjà reçu/);
assert.throws(() => service.claimCampaign(admin.id, "EXPLO-01"), /nombre maximal/);
// Un exemplaire unique ne part jamais, ni en don ni dans un échange.
assert.throws(() => service.createTransfer(player.id, { type: "gift", recipientId: admin.id, editionId: "aurora-wolf-standard" }), /doublons/);
@ -947,12 +947,12 @@ test("admin catalog mutations persist mythic variations and keep owned ones out
// Une variation que personne ne possède mais qu'une campagne cite est retirée, pas supprimée : le code reste utilisable.
service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: ["spectral-prism-cosmic"], opening: {} });
const cosmic = "mythic-card-pull-spectral-prism-cosmic";
service.createCampaign(admin.id, { name: "Cosmique", reward: { items: [{ type: "card", editionId: cosmic }, { type: "pack", collectionId: "astral-genesis", guarantee: { type: "edition", editionId: cosmic } }] }, code: "COSMIC", maxClaims: null, expiresAt: null });
service.createCampaign(admin.id, { name: "Cosmique", reward: { items: [{ type: "card", editionId: cosmic }, { type: "pack", collectionId: "astral-genesis", guarantee: { type: "edition", editionId: cosmic } }] }, code: "COSMIC-01", maxClaims: null, expiresAt: null });
assert.equal(service.getAdminDashboard(admin.id).editionCampaigns[cosmic], 1);
service.setCardMythicConfig(admin.id, "mythic-card-pull", { finishIds: [], opening: {} });
assert.equal(service.catalog.editions.find((edition) => edition.id === cosmic)?.retired, true);
service.completeOpening(player.id, opened.opening.id);
const claimed = service.claimCampaign(player.id, "COSMIC");
const claimed = service.claimCampaign(player.id, "COSMIC-01");
assert.ok(claimed.state.collection.some((item) => item.editionId === cosmic));
const gift = service.openGiftPack(player.id, claimed.state.giftPacks[0].id, "cosmic-gift");
assert.ok(gift.opening.cards.some((card) => card.editionId === cosmic));
@ -1072,7 +1072,7 @@ test("gift packs apply custom rates and guarantees without spending recharge", (
assert.throws(() => service.createCampaign(player.id, { name: "X", reward, code: "LIVE-2026", maxClaims: 2, expiresAt: now + 60_000 }), /administrateur/);
assert.throws(() => service.createCampaign(admin.id, { name: "X", reward: { items: [{ ...pack, guarantee: { type: "rarity", rarity: "legendary", count: 4 } }] }, code: "LIVE-2026", maxClaims: 2, expiresAt: now + 60_000 }), /Garantie invalide/);
assert.throws(() => service.createCampaign(admin.id, { name: "X", reward: { items: [{ ...pack, guarantee: { type: "edition", editionId: "starvoid-dragon-standard" } }] }, code: "LIVE-2026", maxClaims: 2, expiresAt: now + 60_000 }), /appartenir/);
assert.throws(() => service.createCampaign(admin.id, { name: "X", reward, code: "x", maxClaims: 2, expiresAt: now + 60_000 }), /4 à 24/);
assert.throws(() => service.createCampaign(admin.id, { name: "X", reward, code: "x", maxClaims: 2, expiresAt: now + 60_000 }), /8 à 24/);
const shared = service.createCampaign(admin.id, { name: "Live", reward, code: "live-2026", maxClaims: 2, expiresAt: now + 60_000 });
assert.equal(shared.campaign.code, "LIVE-2026");
assert.throws(() => service.createCampaign(admin.id, { name: "Copie", reward, code: "LIVE-2026", maxClaims: 2, expiresAt: now + 60_000 }), /déjà utilisé/);
@ -1101,42 +1101,42 @@ test("gift packs apply custom rates and guarantees without spending recharge", (
assert.deepEqual(detail.claims.map((item) => item.playerName), ["Player", "Other"]);
// Révocation et expiration.
const revoked = service.createCampaign(admin.id, { name: "Révoquée", reward: { items: [{ type: "card", editionId: "astral-booster-standard" }] }, code: "REVOKED", maxClaims: null, expiresAt: null });
const revoked = service.createCampaign(admin.id, { name: "Révoquée", reward: { items: [{ type: "card", editionId: "astral-booster-standard" }] }, code: "REVOKED-1", maxClaims: null, expiresAt: null });
service.revokeCampaign(admin.id, revoked.campaign.id);
assert.throws(() => service.claimCampaign(other.id, "REVOKED"), /révoqué/);
const short = service.createCampaign(admin.id, { name: "Courte", reward: { items: [{ type: "card", editionId: "astral-booster-standard" }] }, code: "SHORT", maxClaims: null, expiresAt: now + 60_000 }).campaign;
service.claimCampaign(other.id, "SHORT");
assert.throws(() => service.claimCampaign(other.id, "REVOKED-1"), /révoqué/);
const short = service.createCampaign(admin.id, { name: "Courte", reward: { items: [{ type: "card", editionId: "astral-booster-standard" }] }, code: "SHORT-01", maxClaims: null, expiresAt: now + 60_000 }).campaign;
service.claimCampaign(other.id, "SHORT-01");
now += 120_000;
assert.throws(() => service.claimCampaign(admin.id, "SHORT"), /expiré/);
assert.throws(() => service.claimCampaign(admin.id, "SHORT-01"), /expiré/);
assert.throws(() => service.extendCampaign(admin.id, short.id, now - 1), /futur/);
service.extendCampaign(admin.id, short.id, now + 60_000);
assert.equal(service.campaignDetail(admin.id, short.id).campaign.expiresAt, now + 60_000);
// Sans date d'expiration : le code reste valable indéfiniment, et une campagne peut perdre son échéance.
service.extendCampaign(admin.id, short.id, null);
assert.equal(service.campaignDetail(admin.id, short.id).campaign.expiresAt, null);
const forever = service.createCampaign(admin.id, { name: "Permanent", reward: { items: [{ type: "card", editionId: "astral-booster-standard" }] }, code: "FOREVER", maxClaims: null, expiresAt: null });
const forever = service.createCampaign(admin.id, { name: "Permanent", reward: { items: [{ type: "card", editionId: "astral-booster-standard" }] }, code: "FOREVER-1", maxClaims: null, expiresAt: null });
now += 10 * 365 * 24 * 3_600_000;
service.claimCampaign(other.id, "FOREVER");
service.claimCampaign(other.id, "FOREVER-1");
assert.equal(service.campaignDetail(admin.id, forever.campaign.id).campaign.claimedCount, 1);
// Plusieurs éléments et quantités dans une même récompense, code partagé sans limite (une utilisation par joueur).
assert.throws(() => service.createCampaign(admin.id, { name: "Vide", reward: { items: [] }, code: "EMPTY", maxClaims: null, expiresAt: now + 60_000 }), /au moins une/);
assert.throws(() => service.createCampaign(admin.id, { name: "Vide", reward: { items: [] }, code: "EMPTY-01", maxClaims: null, expiresAt: now + 60_000 }), /au moins une/);
assert.throws(() => service.createCampaign(admin.id, { name: "Trop", reward: { items: [{ type: "pack", collectionId: "primordial-nebula", quantity: 11 }] }, code: "TOO-MANY", maxClaims: null, expiresAt: now + 60_000 }), /Quantité invalide/);
assert.throws(() => service.createCampaign(admin.id, { name: "Double", reward: { items: [{ type: "card", editionId: "astral-booster-standard", quantity: 2 }] }, code: "DOUBLE", maxClaims: null, expiresAt: now + 60_000 }), /un seul exemplaire/);
assert.throws(() => service.createCampaign(admin.id, { name: "Doublon", reward: { items: [{ type: "card", editionId: "astral-booster-standard" }, { type: "card", editionId: "astral-booster-standard" }] }, code: "DOUBLON", maxClaims: null, expiresAt: now + 60_000 }), /qu’une fois/);
assert.throws(() => service.createCampaign(admin.id, { name: "Double", reward: { items: [{ type: "card", editionId: "astral-booster-standard", quantity: 2 }] }, code: "DOUBLE-01", maxClaims: null, expiresAt: now + 60_000 }), /un seul exemplaire/);
assert.throws(() => service.createCampaign(admin.id, { name: "Doublon", reward: { items: [{ type: "card", editionId: "astral-booster-standard" }, { type: "card", editionId: "astral-booster-standard" }] }, code: "DOUBLON-1", maxClaims: null, expiresAt: now + 60_000 }), /qu’une fois/);
const bundle = service.createCampaign(admin.id, {
name: "Pack de bienvenue",
reward: { items: [{ type: "card", editionId: "astral-booster-standard" }, { type: "card", editionId: "aurora-wolf-standard" }, { type: "pack", collectionId: "primordial-nebula", quantity: 3 }] },
code: "WELCOME", maxClaims: null, expiresAt: now + 60_000
code: "WELCOME-1", maxClaims: null, expiresAt: now + 60_000
});
assert.equal(service.campaignDetail(admin.id, bundle.campaign.id).campaign.maxClaims, null);
const players = Array.from({ length: 3 }, (_, index) => service.upsertPlayer({ discordId: `bundle-${index}`, displayName: `Bundle ${index}` }));
for (const member of players) {
const received = service.claimCampaign(member.id, "WELCOME");
const received = service.claimCampaign(member.id, "WELCOME-1");
assert.equal(received.state.collection.filter((item) => ["astral-booster-standard", "aurora-wolf-standard"].includes(item.editionId)).length, 2);
assert.equal(received.state.giftPacks.length, 3);
}
assert.throws(() => service.claimCampaign(players[0].id, "WELCOME"), /déjà reçu/);
assert.throws(() => service.claimCampaign(players[0].id, "WELCOME-1"), /déjà reçu/);
assert.equal(service.campaignDetail(admin.id, bundle.campaign.id).campaign.claimedCount, 3);
assert.equal(service.getAdminDashboard(admin.id).campaigns.length, 5);
assert.equal("campaigns" in service.getState(admin.id), false);
@ -1146,3 +1146,38 @@ test("gift packs apply custom rates and guarantees without spending recharge", (
assert.equal(summarizeReward(many, published), "3 cartes + 2 paquets");
database.close();
});
test("traders list the same available duplicates as each collection, without reserved ones", () => {
const database = new CardsDatabase(":memory:");
const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000, random: () => 0 });
const owner = service.upsertPlayer({ discordId: "owner", displayName: "Owner" });
const partner = service.upsertPlayer({ discordId: "partner", displayName: "Partner" });
const viewer = service.upsertPlayer({ discordId: "viewer", displayName: "Viewer" });
service.addCard(owner.id, "aurora-wolf-standard");
service.addCard(owner.id, "aurora-wolf-standard");
service.addCard(owner.id, "aurora-wolf-standard");
service.addCard(partner.id, "astral-booster-standard");
service.addCard(partner.id, "astral-booster-standard");
service.addCard(partner.id, "aurora-wolf-standard");
service.createTransfer(owner.id, { type: "trade", recipientId: partner.id, editionId: "aurora-wolf-standard", requestedEditionId: "astral-booster-standard" });
const { traders } = service.listTraders(viewer.id);
for (const trader of traders) {
const expected = service.collectionOf(trader.id).filter((entry) => entry.spare > 0).map(({ editionId, spare }) => ({ editionId, spare }));
assert.deepEqual(trader.duplicates, expected, trader.displayName);
}
assert.deepEqual(traders.find((trader) => trader.id === owner.id).duplicates, [{ editionId: "aurora-wolf-standard", spare: 1 }]);
assert.deepEqual(traders.find((trader) => trader.id === partner.id).duplicates, [{ editionId: "astral-booster-standard", spare: 1 }]);
});
test("new campaign codes need eight characters while existing short ones keep working", () => {
const database = new CardsDatabase(":memory:");
const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000, random: () => 0 });
const admin = service.upsertPlayer({ discordId: "admin", displayName: "Admin", isAdmin: true });
const player = service.upsertPlayer({ discordId: "player", displayName: "Player" });
const reward = { items: [{ type: "card", editionId: "aurora-wolf-standard" }] };
assert.throws(() => service.createCampaign(admin.id, { name: "Courte", reward, code: "SEVEN77" }), /8 à 24/);
const { campaign } = service.createCampaign(admin.id, { name: "Ancienne", reward, code: "EIGHT888" });
database.db.prepare("UPDATE campaigns SET code = 'OLD1' WHERE id = ?").run(campaign.id);
assert.equal(service.claimCampaign(player.id, "old1").reward.items[0].editionId, "aurora-wolf-standard");
});

View file

@ -7,6 +7,9 @@ import { resolve } from "node:path";
loadProjectEnv();
// Le serveur de développement donne les droits administrateur à tout visiteur : il reste local sauf demande explicite.
const devHost = process.env.HOST || "127.0.0.1";
function nebulaCardsApi() {
return {
name: "nebula-cards-api",
@ -26,11 +29,11 @@ export default defineConfig({
publicDir: "public",
plugins: [react(), nebulaCardsApi()],
server: {
host: "0.0.0.0",
host: devHost,
port: Number(process.env.PORT || 5173)
},
preview: {
host: "0.0.0.0",
host: devHost,
port: Number(process.env.PORT || 4173)
},
build: {

View file

@ -225,7 +225,7 @@ function CampaignForm({ catalog, lookup, campaigns, mutateCampaigns, busy, now,
const expiry = draft.noExpiry ? null : new Date(draft.expiresAt).getTime();
const code = draft.code.trim().toUpperCase();
const limitReady = unlimited || (Number.isInteger(limit) && limit >= 1 && limit <= 100_000);
const codeReady = /^[A-Z0-9][A-Z0-9-]{3,23}$/.test(code);
const codeReady = /^[A-Z0-9][A-Z0-9-]{7,23}$/.test(code);
const expiryReady = expiry === null || expiry > now;
// Tout ce qui empêche la création, affiché sous le bouton pour ne jamais laisser un bouton désactivé sans explication.
const missing = [
@ -256,7 +256,7 @@ function CampaignForm({ catalog, lookup, campaigns, mutateCampaigns, busy, now,
<div className="nebula-admin-campaign-identity">
<label><span>Nom de la campagne, visible par les joueurs</span><input className="nds-input" value={draft.name} maxLength="80" placeholder="Ex. Live de lancement" onChange={(event) => update({ name: event.target.value })} required /></label>
<div className="nebula-admin-code-field">
<label><span>Code à annoncer (4 à 24 caractères)</span><input className="nds-input nebula-admin-code-input" value={draft.code} maxLength="24" placeholder="Ex. NEBULA-2026" onChange={(event) => update({ code: event.target.value.toUpperCase().replace(/\s+/g, "-").replace(/[^A-Z0-9-]/g, "") })} required /></label>
<label><span>Code à annoncer (8 à 24 caractères)</span><input className="nds-input nebula-admin-code-input" value={draft.code} maxLength="24" placeholder="Ex. NEBULA-2026" onChange={(event) => update({ code: event.target.value.toUpperCase().replace(/\s+/g, "-").replace(/[^A-Z0-9-]/g, "") })} required /></label>
<Tooltip as="button" className="nds-button" content="Générer un code aléatoire" data-variant="secondary" type="button" onClick={() => update({ code: randomCode(new Set(campaigns.map((campaign) => campaign.code))) })}>Générer</Tooltip>
</div>
</div>