// Rôle : vérifie le service et l'API des Expéditions Sokko TCG (destinations du jour, départ solo, retour, réglages, suppression de compte). import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { resolve } from "node:path"; import { Readable } from "node:stream"; import { test } from "node:test"; import { createCardsApiHandler } from "../services/cards/api.js"; import { buildPublishedCatalog, prepareVersionedCatalog } from "../services/cards/catalog.js"; import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES } from "../services/cards/admin-seed.js"; import { CardsDatabase } from "../services/cards/database.js"; import { CardsService } from "../services/cards/service.js"; const baseCatalog = prepareVersionedCatalog(JSON.parse(await readFile("website/public/data/cards/catalog.json", "utf8"))); const published = buildPublishedCatalog(baseCatalog, { collectionStates: INITIAL_COLLECTION_STATES, dropRates: INITIAL_DROP_RATES }); const HOUR = 3_600_000; const rarityOf = (cardId) => published.editions.find((edition) => edition.cardId === cardId && !edition.promotional).rarity; const editionsOf = (rarity, collectionId = "primordial-nebula") => published.editions .filter((edition) => edition.rarity === rarity && published.cards.find((card) => card.id === edition.cardId).collectionId === collectionId) .map((edition) => edition.id); function expeditionService({ start = Date.parse("2026-11-15T09:00:00Z"), random = () => 0 } = {}) { const clock = { now: start }; const database = new CardsDatabase(":memory:"); const service = new CardsService({ database, catalog: baseCatalog, now: () => clock.now, random }); const admin = service.upsertPlayer({ discordId: "expedition-admin", displayName: "Admin", isAdmin: true }); const player = service.upsertPlayer({ discordId: "expedition-player", displayName: "Player" }); const open = (changes = {}) => service.expeditions.updateSettings(admin.id, { ...service.expeditions.settings, enabled: true, ...changes }); const rares = editionsOf("rare"); database.transaction(() => rares.slice(0, 4).forEach((editionId) => service.addCard(player.id, editionId))); return { clock, database, service, admin, player, open, rares }; } const soloBody = (view, slots, changes = {}) => ({ day: view.day, destinationId: view.destinations[0].id, difficulty: 1, durationHours: 2, slots, ...changes }); test("expeditions stay closed until an administrator opens them", () => { const { service, player, open, rares } = expeditionService(); const closed = service.expeditions.getExpeditions(player.id); assert.equal(closed.enabled, false); assert.deepEqual(closed.destinations, []); assert.equal(service.getState(player.id).expeditions.enabled, false); assert.throws(() => service.expeditions.startSolo(player.id, soloBody({ day: closed.day, destinations: [{ id: "light-currents" }] }, rares.slice(0, 2)), "k1"), (error) => error.code === "EXPEDITIONS_CLOSED"); assert.throws(() => service.expeditions.updateSettings(player.id, { ...service.expeditions.settings, enabled: true }), (error) => error.code === "ADMIN_REQUIRED"); open(); const view = service.expeditions.getExpeditions(player.id); assert.equal(view.enabled, true); assert.equal(view.day, "2026-11-15"); assert.equal(view.destinations.length, 4); assert.deepEqual(Object.keys(view.destinations[0].stars), ["1", "2", "3", "4"]); assert.equal(view.destinations[0].stars[4].dangers.length, 1); assert.equal(view.destinations[0].stars[2].condition, null); assert.equal(view.cards.length, 4); // Le tirage du jour est commun à tous et gardé en base. assert.deepEqual(service.expeditions.getExpeditions(player.id).destinations.map((item) => item.id), view.destinations.map((item) => item.id)); }); test("a solo expedition freezes its team, hides its result until it returns and pays once", () => { const { clock, service, player, open, rares, database } = expeditionService(); open(); const view = service.expeditions.getExpeditions(player.id); const body = soloBody(view, rares.slice(0, 2), { difficulty: 2, durationHours: 6 }); const preview = service.expeditions.preview(player.id, body).preview; assert.ok(["struggle", "success", "triumph"].includes(preview.tier)); assert.equal(preview.requirements.length, 2); assert.ok(preview.expected.eclats > 0); const started = service.expeditions.startSolo(player.id, body, "start-1"); assert.equal(started.expedition.status, "running"); assert.equal(started.expedition.result, null); assert.equal(started.expedition.reward, null); assert.equal(started.expedition.returnsAt, clock.now + 6 * HOUR); assert.equal(started.state.expeditions.running, 1); assert.equal(started.state.expeditions.launchedToday, true); assert.deepEqual(started.state.expeditions.busyEditions.map((item) => item.editionId).sort(), rares.slice(0, 2).sort()); // Même clé : même expédition ; nouvelle clé : la limite solo s'applique, et les cartes sont occupées. assert.equal(service.expeditions.startSolo(player.id, body, "start-1").expedition.id, started.expedition.id); assert.throws(() => service.expeditions.startSolo(player.id, body, "start-2"), (error) => error.code === "EXPEDITION_CARD_BUSY"); assert.throws(() => service.expeditions.startSolo(player.id, { ...body, slots: rares.slice(2, 4) }, "start-3"), (error) => error.code === "EXPEDITION_LIMIT"); assert.throws(() => service.expeditions.claim(player.id, started.expedition.id), (error) => error.code === "EXPEDITION_NOT_RETURNED"); // Une amélioration des réglages pendant le trajet ne change rien : tout est figé au départ. clock.now += 6 * HOUR; const before = service.getState(player.id); assert.equal(before.expeditions.returned, 1); const returned = service.expeditions.getExpeditions(player.id).expeditions[0]; assert.equal(returned.status, "returned"); assert.equal(returned.result.tier, preview.tier); const claimed = service.expeditions.claim(player.id, started.expedition.id); assert.equal(claimed.expedition.status, "completed"); assert.equal(claimed.state.wallet.eclats, returned.reward.eclats); assert.equal(claimed.state.wallet.stardust, before.wallet.stardust + returned.reward.stardust); assert.ok(returned.reward.eclats >= Math.floor(preview.expected.eclats)); // random() = 0 : tous les tirages réussissent, donc un paquet rapporté, rangé avec les paquets offerts. assert.equal(returned.reward.packs.length, 1); assert.equal(claimed.state.giftPacks.length, 1); assert.equal(claimed.state.giftPacks[0].source, "expedition"); assert.equal(claimed.state.giftPacks[0].sourceName, returned.destination.name); const history = claimed.state.history.find((entry) => entry.type === "expedition_completed"); assert.equal(history.details.eclats, returned.reward.eclats); // Deuxième retour : même rapport, aucun crédit en plus ; les cartes sont libres. const again = service.expeditions.claim(player.id, started.expedition.id); assert.equal(again.state.wallet.eclats, claimed.state.wallet.eclats); assert.deepEqual(again.state.expeditions.busyEditions, []); assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM gift_packs WHERE source = 'expedition'").get().count, 1); // Le paquet rapporté s'ouvre comme un paquet offert. const opened = service.openGiftPack(player.id, claimed.state.giftPacks[0].id, "open-expedition-pack"); assert.equal(opened.opening.cards.length, 3); }); test("unlucky rolls keep the average and never hand out a pack", () => { const { clock, service, player, open, rares } = expeditionService({ random: (max) => max - 1 }); open(); const view = service.expeditions.getExpeditions(player.id); const started = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "unlucky"); clock.now += 2 * HOUR; const returned = service.expeditions.claim(player.id, started.expedition.id).expedition; assert.deepEqual(returned.reward.packs, []); assert.equal(returned.reward.eclats, Math.floor(returned.reward.eclats)); }); test("solo departures refuse stale days, unknown destinations, commons, duplicates and cards the player lacks", () => { const { clock, service, player, open, rares } = expeditionService(); open(); const view = service.expeditions.getExpeditions(player.id); const start = (changes, key) => () => service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2), changes), key); assert.throws(start({ destinationId: "nowhere" }, "a"), (error) => error.code === "EXPEDITION_INVALID"); assert.throws(start({ difficulty: 5 }, "b"), (error) => error.code === "EXPEDITION_INVALID"); assert.throws(start({ durationHours: 3 }, "c"), (error) => error.code === "EXPEDITION_INVALID"); assert.throws(start({ slots: [rares[0]] }, "d"), (error) => error.code === "EXPEDITION_CARD_INVALID"); assert.throws(start({ slots: [rares[0], rares[0]] }, "e"), (error) => error.code === "EXPEDITION_CARD_INVALID"); assert.throws(start({ slots: [rares[0], editionsOf("common")[0]] }, "f"), (error) => error.code === "EXPEDITION_CARD_INVALID"); assert.throws(start({ slots: [rares[0], rares[10]] }, "g"), (error) => error.code === "CARD_NOT_OWNED"); assert.throws(() => service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), ""), (error) => error.code === "IDEMPOTENCY_REQUIRED"); clock.now += 24 * HOUR; assert.throws(start({}, "h"), (error) => error.code === "EXPEDITION_DAY_EXPIRED"); assert.equal(rarityOf("starvoid-dragon"), "legendary"); }); test("administrators tune settings with bounds and history, and can cancel an expedition", () => { const { service, admin, player, open, rares, database } = expeditionService(); assert.throws(() => service.expeditions.updateSettings(admin.id, { ...service.expeditions.settings, score: { ...service.expeditions.settings.score, successPct: 500 } }), (error) => error.code === "EXPEDITION_SETTINGS_INVALID"); open(); assert.throws(() => open(), (error) => error.code === "EXPEDITION_SETTINGS_UNCHANGED"); const audit = database.db.prepare("SELECT details_json FROM audit_log WHERE event_type = 'expedition_settings_updated'").get(); assert.deepEqual(JSON.parse(audit.details_json).changes, [{ path: "enabled", previous: false, next: true }]); assert.ok(service.getAdminHistory(admin.id).entries.some((entry) => entry.type === "expedition_settings_updated")); const dashboard = service.getAdminDashboard(admin.id); assert.equal(dashboard.expeditionSettings.settings.enabled, true); assert.equal(dashboard.expeditionSettings.destinations.length, 12); assert.ok(dashboard.expeditionSettings.schema.some((field) => field.path === "loot.eclatsPerHourCents")); const view = service.expeditions.getExpeditions(player.id); const started = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "cancel-me"); assert.equal(service.getAdminDashboard(admin.id).expeditionsToday.running, 1); assert.throws(() => service.expeditions.cancel(player.id, started.expedition.id), (error) => error.code === "ADMIN_REQUIRED"); service.expeditions.cancel(admin.id, started.expedition.id); const state = service.getState(player.id); assert.deepEqual(state.expeditions.busyEditions, []); assert.ok(state.history.some((entry) => entry.type === "expedition_cancelled_by_guild")); assert.throws(() => service.expeditions.claim(player.id, started.expedition.id), (error) => error.code === "EXPEDITION_NOT_FOUND"); assert.throws(() => service.expeditions.cancel(admin.id, started.expedition.id), (error) => error.code === "EXPEDITION_FINISHED"); }); test("deleting an account cancels its expeditions and resets its Éclats", () => { const { clock, service, player, open, rares, database } = expeditionService(); open(); const view = service.expeditions.getExpeditions(player.id); const first = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "first"); clock.now += 2 * HOUR; service.expeditions.claim(player.id, first.expedition.id); const second = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(2, 4)), "second"); service.deleteAccount(player.id); assert.equal(database.db.prepare("SELECT eclats FROM players WHERE id = ?").get(player.id).eclats, 0); assert.equal(database.db.prepare("SELECT status FROM expeditions WHERE id = ?").get(second.expedition.id).status, "cancelled"); }); function mockRequest({ method = "GET", path, body, headers = {} }) { const req = Readable.from(body == null ? [] : [Buffer.from(JSON.stringify(body))]); req.method = method; req.url = path; req.headers = { host: "localhost:5173", ...headers }; req.socket = { remoteAddress: "127.0.0.1" }; return req; } async function call(handler, options) { const response = { status: 0, headers: {}, chunks: [] }; const res = { setHeader(name, value) { response.headers[name.toLowerCase()] = value; }, writeHead(status, headers = {}) { response.status = status; for (const [name, value] of Object.entries(headers)) response.headers[name.toLowerCase()] = value; }, end(value = "") { response.chunks.push(Buffer.from(value)); } }; await handler(mockRequest(options), res); response.raw = Buffer.concat(response.chunks); response.json = response.headers["content-type"]?.startsWith("application/json") && response.raw.length ? JSON.parse(response.raw.toString("utf8")) : null; return response; } test("the expeditions API requires a session, CSRF protection, an administrator for settings and an idempotency key to start", async (t) => { const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: true, databasePath: ":memory:", env: { NODE_ENV: "test" }, random: () => 0 }); t.after(() => handler.close()); assert.equal((await call(handler, { path: "/api/cards/expeditions" })).status, 401); const login = await call(handler, { method: "POST", path: "/api/cards/auth/dev", body: {} }); const cookie = login.headers["set-cookie"].split(";")[0]; const headers = { cookie, "x-csrf-token": login.json.csrfToken }; const closed = await call(handler, { path: "/api/cards/expeditions", headers: { cookie } }); assert.equal(closed.status, 200); assert.equal(closed.json.enabled, false); assert.equal((await call(handler, { method: "PUT", path: "/api/cards/admin/expeditions/settings", headers: { cookie }, body: {} })).status, 403); const dashboard = await call(handler, { path: "/api/cards/admin/dashboard", headers: { cookie } }); const settings = { ...dashboard.json.expeditionSettings.settings, enabled: true }; const invalid = await call(handler, { method: "PUT", path: "/api/cards/admin/expeditions/settings", headers, body: { settings: { ...settings, solo: { ...settings.solo, maxStars: 9 } } } }); assert.equal(invalid.status, 400); assert.equal(invalid.json.error.code, "EXPEDITION_SETTINGS_INVALID"); const opened = await call(handler, { method: "PUT", path: "/api/cards/admin/expeditions/settings", headers, body: { settings } }); assert.equal(opened.status, 200); assert.equal(opened.json.expeditionSettings.settings.enabled, true); const devId = handler.service.db.prepare("SELECT id FROM players WHERE discord_id = 'dev-admin'").get().id; handler.service.database.transaction(() => editionsOf("rare").slice(0, 2).forEach((editionId) => handler.service.addCard(devId, editionId))); const view = (await call(handler, { path: "/api/cards/expeditions", headers: { cookie } })).json; const slots = view.cards.slice(0, 2).map((card) => card.editionId); assert.equal(slots.length, 2, "the development account owns rare or better cards"); const body = soloBody(view, slots); const preview = await call(handler, { method: "POST", path: "/api/cards/expeditions/preview", headers, body }); assert.equal(preview.status, 200); const noKey = await call(handler, { method: "POST", path: "/api/cards/expeditions", headers, body }); assert.equal(noKey.json.error.code, "IDEMPOTENCY_REQUIRED"); const started = await call(handler, { method: "POST", path: "/api/cards/expeditions", headers: { ...headers, "idempotency-key": "api-start" }, body }); assert.equal(started.status, 201); assert.equal(started.json.expedition.status, "running"); const early = await call(handler, { method: "POST", path: `/api/cards/expeditions/${started.json.expedition.id}/claim`, headers }); assert.equal(early.status, 409); assert.equal(early.json.error.code, "EXPEDITION_NOT_RETURNED"); const cancelled = await call(handler, { method: "POST", path: `/api/cards/admin/expeditions/${started.json.expedition.id}/cancel`, headers }); assert.equal(cancelled.status, 200); });