Add the server-backed card game: Discord login, recharging pack openings, album, trades, gifts, stardust shop, campaign codes and its administration, stored in SQLite and disabled in production until configured. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
229 lines
16 KiB
JavaScript
229 lines
16 KiB
JavaScript
// Rôle : vérifie le contrat HTTP, la session, le CSRF et l'idempotence de l'API Sokko TCG.
|
|
import assert from "node:assert/strict";
|
|
import { Readable } from "node:stream";
|
|
import { test } from "node:test";
|
|
import { resolve } from "node:path";
|
|
import { createCardsApiHandler } from "../services/cards/api.js";
|
|
|
|
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: {}, body: "" };
|
|
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.body += value; }
|
|
};
|
|
await handler(mockRequest(options), res);
|
|
response.json = response.body ? JSON.parse(response.body) : null;
|
|
return response;
|
|
}
|
|
|
|
test("Discord OAuth preserves the dedicated admin route", async (t) => {
|
|
const handler = createCardsApiHandler({
|
|
projectRoot: resolve("."),
|
|
enabled: true,
|
|
devAuth: false,
|
|
databasePath: ":memory:",
|
|
env: {
|
|
NODE_ENV: "test",
|
|
DISCORD_CLIENT_ID: "discord-client",
|
|
DISCORD_CLIENT_SECRET: "discord-secret",
|
|
CARDS_ADMIN_DISCORD_IDS: "discord-admin"
|
|
},
|
|
fetchImpl: async (url) => {
|
|
if (String(url).includes("/oauth2/token")) return { ok: true, json: async () => ({ access_token: "discord-token" }) };
|
|
return { ok: true, json: async () => ({ id: "discord-admin", username: "Admin", global_name: "TCG Admin", avatar: null }) };
|
|
}
|
|
});
|
|
t.after(() => handler.close());
|
|
|
|
const authorization = await call(handler, { path: "/api/cards/auth/discord?returnTo=%2Fcards%2Fadmin" });
|
|
assert.equal(authorization.status, 302);
|
|
const authorizationUrl = new URL(authorization.headers.location);
|
|
const state = authorizationUrl.searchParams.get("state");
|
|
const oauthCookies = authorization.headers["set-cookie"];
|
|
assert.ok(oauthCookies.some((cookie) => cookie.startsWith("sokkog_cards_oauth_return=%2Fcards%2Fadmin;")));
|
|
// Le retour après connexion accepte les sections joueur, jamais une adresse hors de Sokko TCG.
|
|
for (const [returnTo, expected] of [["/cards/shop", "%2Fcards%2Fshop"], ["/cards/admin/collections/nebula", "%2Fcards%2Fadmin%2Fcollections%2Fnebula"], ["/cards/shop/extra", "%2Fcards"], ["//evil.example/cards", "%2Fcards"], ["/cards/../toolboxes", "%2Fcards"]]) {
|
|
const response = await call(handler, { path: `/api/cards/auth/discord?returnTo=${encodeURIComponent(returnTo)}` });
|
|
assert.ok(response.headers["set-cookie"].some((cookie) => cookie.startsWith(`sokkog_cards_oauth_return=${expected};`)), returnTo);
|
|
}
|
|
|
|
const callback = await call(handler, {
|
|
path: `/api/cards/auth/callback?state=${encodeURIComponent(state)}&code=discord-code`,
|
|
headers: { cookie: oauthCookies.map((cookie) => cookie.split(";")[0]).join("; ") }
|
|
});
|
|
assert.equal(callback.status, 302);
|
|
assert.equal(callback.headers.location, "http://localhost:5173/#/cards/admin");
|
|
assert.ok(callback.headers["set-cookie"].some((cookie) => cookie.startsWith("sokkog_cards_oauth_return=;")));
|
|
});
|
|
|
|
test("Discord OAuth failures return to the login screen without opening a session", async (t) => {
|
|
const env = { NODE_ENV: "test", DISCORD_CLIENT_ID: "discord-client", DISCORD_CLIENT_SECRET: "discord-secret" };
|
|
let discordResponse = { ok: false, status: 400 };
|
|
const logged = [];
|
|
t.mock.method(console, "error", (error) => logged.push(error));
|
|
const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: false, databasePath: ":memory:", env, fetchImpl: async () => discordResponse });
|
|
t.after(() => handler.close());
|
|
const authorization = await call(handler, { path: "/api/cards/auth/discord?returnTo=%2Fcards%2Fshop" });
|
|
const state = new URL(authorization.headers.location).searchParams.get("state");
|
|
const cookie = authorization.headers["set-cookie"].map((value) => value.split(";")[0]).join("; ");
|
|
const callback = (query, headers = { cookie }) => call(handler, { path: `/api/cards/auth/callback?${query}`, headers });
|
|
|
|
for (const [query, headers, reason] of [
|
|
[`state=${state}&error=access_denied`, { cookie }, "denied"],
|
|
[`state=${state}&code=abc`, {}, "expired"],
|
|
[`state=other&code=abc`, { cookie }, "expired"],
|
|
[`state=${state}&code=abc`, { cookie }, "failed"],
|
|
[`state=${state}`, { cookie }, "failed"]
|
|
]) {
|
|
const response = await callback(query, headers);
|
|
assert.equal(response.status, 302, query);
|
|
assert.equal(response.headers.location, `http://localhost:5173/?cardsAuth=${reason}#${reason === "expired" && !headers.cookie ? "/cards" : "/cards/shop"}`, query);
|
|
assert.equal(response.headers["set-cookie"].some((value) => value.startsWith("sokkog_cards_session=")), false, query);
|
|
assert.ok(response.headers["set-cookie"].some((value) => value.startsWith("sokkog_cards_oauth_state=;")), query);
|
|
}
|
|
assert.equal(logged.length, 2);
|
|
assert.equal(logged.some((error) => String(error.message).includes("discord-secret")), false);
|
|
|
|
discordResponse = { ok: true, status: 200, json: async () => { throw new Error("invalid body"); } };
|
|
assert.equal((await callback(`state=${state}&code=abc`)).headers.location, "http://localhost:5173/?cardsAuth=failed#/cards/shop");
|
|
});
|
|
|
|
test("production refuses to start Sokko TCG without a public origin", () => {
|
|
assert.throws(() => createCardsApiHandler({ projectRoot: resolve("."), enabled: true, databasePath: ":memory:", env: { NODE_ENV: "production", CARDS_DB_PATH: ":memory:" } }), /CARDS_PUBLIC_ORIGIN/);
|
|
});
|
|
|
|
test("cards API authenticates dev sessions and protects mutations", async (t) => {
|
|
const handler = createCardsApiHandler({
|
|
projectRoot: resolve("."),
|
|
enabled: true,
|
|
devAuth: true,
|
|
databasePath: ":memory:",
|
|
env: { NODE_ENV: "test" },
|
|
random: () => 0
|
|
});
|
|
t.after(() => handler.close());
|
|
|
|
const config = await call(handler, { path: "/api/cards/config" });
|
|
assert.equal(config.status, 200);
|
|
assert.equal(config.json.enabled, true);
|
|
assert.equal(config.json.catalog.collections.length, 3);
|
|
|
|
const login = await call(handler, { method: "POST", path: "/api/cards/auth/dev", body: {} });
|
|
assert.equal(login.status, 200);
|
|
assert.equal(login.json.player.isAdmin, true);
|
|
const sessionCookie = login.headers["set-cookie"].split(";")[0];
|
|
const csrfToken = login.json.csrfToken;
|
|
|
|
const rejected = await call(handler, { method: "POST", path: "/api/cards/openings", headers: { cookie: sessionCookie, "idempotency-key": "one" }, body: { collectionId: "primordial-nebula" } });
|
|
assert.equal(rejected.status, 403);
|
|
assert.equal(rejected.json.error.code, "CSRF");
|
|
|
|
const opened = 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(opened.status, 201);
|
|
assert.equal(opened.json.opening.cards.length, 3);
|
|
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 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);
|
|
|
|
const dashboard = await call(handler, { path: "/api/cards/admin/dashboard", headers: { cookie: sessionCookie } });
|
|
assert.equal(dashboard.status, 200);
|
|
assert.equal(dashboard.json.stats.totalPlayers, 1);
|
|
assert.equal(dashboard.json.players[0].totalCards, 3);
|
|
assert.equal(dashboard.json.shopSetting.openingPrice, 30);
|
|
|
|
const recycled = await call(handler, { method: "POST", path: "/api/cards/recycle", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: {} });
|
|
assert.ok([200, 409].includes(recycled.status));
|
|
const shopUpdate = await call(handler, { method: "PUT", path: "/api/cards/admin/shop", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { stardustValues: dashboard.json.shopSetting.stardustValues, openingPrice: 1 } });
|
|
assert.equal(shopUpdate.status, 200);
|
|
assert.equal(shopUpdate.json.shopSetting.openingPrice, 1);
|
|
const noCsrf = await call(handler, { method: "POST", path: "/api/cards/shop/openings", headers: { cookie: sessionCookie }, body: {} });
|
|
assert.equal(noCsrf.status, 403);
|
|
assert.equal("discordId" in dashboard.json.players[0], false);
|
|
|
|
const regularPlayer = handler.service.upsertPlayer({ discordId: "regular-player", displayName: "Regular" });
|
|
const regularSession = handler.service.createSession(regularPlayer.id);
|
|
const forbidden = await call(handler, { path: "/api/cards/admin/dashboard", headers: { cookie: `sokkog_cards_session=${regularSession.token}` } });
|
|
assert.equal(forbidden.status, 403);
|
|
assert.equal(forbidden.json.error.code, "ADMIN_REQUIRED");
|
|
const forbiddenHistory = await call(handler, { path: "/api/cards/admin/history", headers: { cookie: `sokkog_cards_session=${regularSession.token}` } });
|
|
assert.equal(forbiddenHistory.status, 403);
|
|
assert.equal((await call(handler, { path: "/api/cards/admin/history?before=abc", headers: { cookie: sessionCookie } })).status, 400);
|
|
assert.equal((await call(handler, { path: "/api/cards/admin/history", headers: { cookie: sessionCookie } })).status, 200);
|
|
|
|
const mythicPath = "/api/cards/admin/catalog/cards/mythic-card-pull/mythic";
|
|
const mythicBody = { finishIds: ["spectral-prism-solar", "spectral-prism-cosmic"], opening: { particleShapeId: "snowflakes", particlePaletteId: null } };
|
|
const missingCsrf = await call(handler, { method: "PUT", path: mythicPath, headers: { cookie: sessionCookie }, body: mythicBody });
|
|
assert.equal(missingCsrf.status, 403);
|
|
assert.equal(missingCsrf.json.error.code, "CSRF");
|
|
const regularCsrf = await call(handler, { method: "PUT", path: mythicPath, headers: { cookie: `sokkog_cards_session=${regularSession.token}`, "x-csrf-token": regularSession.csrfToken }, body: mythicBody });
|
|
assert.equal(regularCsrf.status, 403);
|
|
assert.equal(regularCsrf.json.error.code, "ADMIN_REQUIRED");
|
|
const updated = await call(handler, { method: "PUT", path: mythicPath, headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: mythicBody });
|
|
assert.equal(updated.status, 200);
|
|
assert.ok(updated.json.catalog.editions.some((edition) => edition.id === "mythic-card-pull-spectral-prism-cosmic"));
|
|
const collectionOpening = await call(handler, { method: "PUT", path: "/api/cards/admin/catalog/collections/astral-genesis/mythic-opening", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { particleShapeId: null, particlePaletteId: "match-holo" } });
|
|
assert.equal(collectionOpening.status, 200);
|
|
const refreshedConfig = await call(handler, { path: "/api/cards/config" });
|
|
assert.ok(refreshedConfig.json.catalog.editions.some((edition) => edition.id === "mythic-card-pull-spectral-prism-cosmic"));
|
|
assert.deepEqual(refreshedConfig.json.catalog.mythicOpeningSettings.map((item) => item.scope).sort(), ["card", "collection"]);
|
|
|
|
const dropPath = "/api/cards/admin/collections/astral-genesis/drop-rates";
|
|
const weights = { common: 60, rare: 25, epic: 10, legendary: 4, mythic: 1 };
|
|
const dropForbidden = await call(handler, { method: "PUT", path: dropPath, headers: { cookie: `sokkog_cards_session=${regularSession.token}`, "x-csrf-token": regularSession.csrfToken }, body: { rarityWeights: weights } });
|
|
assert.equal(dropForbidden.status, 403);
|
|
const dropUpdated = await call(handler, { method: "PUT", path: dropPath, headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { rarityWeights: weights } });
|
|
assert.equal(dropUpdated.status, 200);
|
|
assert.deepEqual(dropUpdated.json.catalog.collections.find((collection) => collection.id === "astral-genesis").dropWeights, weights);
|
|
const dropUnchanged = await call(handler, { method: "PUT", path: dropPath, headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { rarityWeights: weights } });
|
|
assert.equal(dropUnchanged.status, 409);
|
|
const closed = await call(handler, { method: "PUT", path: "/api/cards/admin/collections/astral-genesis/state", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { active: false } });
|
|
assert.equal(closed.status, 200);
|
|
const afterClose = await call(handler, { path: "/api/cards/config" });
|
|
assert.equal(afterClose.json.catalog.collections.find((collection) => collection.id === "astral-genesis").active, false);
|
|
assert.equal("dropTables" in afterClose.json.catalog, false);
|
|
|
|
const rechargeForbidden = await call(handler, { method: "PUT", path: "/api/cards/admin/recharge", headers: { cookie: `sokkog_cards_session=${regularSession.token}`, "x-csrf-token": regularSession.csrfToken }, body: { intervalMs: 7_200_000 } });
|
|
assert.equal(rechargeForbidden.status, 403);
|
|
const rechargeUpdated = await call(handler, { method: "PUT", path: "/api/cards/admin/recharge", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { intervalMs: 7_200_000 } });
|
|
assert.equal(rechargeUpdated.status, 200);
|
|
assert.equal(rechargeUpdated.json.rechargeSetting.intervalMs, 7_200_000);
|
|
const rechargeInvalid = await call(handler, { method: "PUT", path: "/api/cards/admin/recharge", headers: { cookie: sessionCookie, "x-csrf-token": csrfToken }, body: { intervalMs: "1h" } });
|
|
assert.equal(rechargeInvalid.status, 400);
|
|
const dashboardAfterRecharge = await call(handler, { path: "/api/cards/admin/dashboard", headers: { cookie: sessionCookie } });
|
|
assert.equal(dashboardAfterRecharge.json.rechargeSetting.intervalMs, 7_200_000);
|
|
});
|
|
|
|
test("gift pack codes are claimed and opened through the API", async (t) => {
|
|
const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: true, databasePath: ":memory:", env: { NODE_ENV: "test" }, random: () => 0 });
|
|
t.after(() => handler.close());
|
|
const login = await call(handler, { method: "POST", path: "/api/cards/auth/dev", body: {} });
|
|
const headers = { cookie: login.headers["set-cookie"].split(";")[0], "x-csrf-token": login.json.csrfToken };
|
|
const created = await call(handler, { method: "POST", path: "/api/cards/admin/campaigns", headers, body: { name: "Live", reward: { items: [{ type: "pack", collectionId: "astral-genesis", guarantee: { type: "rarity", rarity: "epic", count: 1 } }] }, code: "API-LIVE", maxClaims: null, expiresAt: Date.now() + 60_000 } });
|
|
assert.equal(created.status, 201);
|
|
const detail = await call(handler, { path: `/api/cards/admin/campaigns/${created.json.campaign.id}`, headers });
|
|
assert.equal(detail.json.campaign.code, "API-LIVE");
|
|
const claimed = await call(handler, { method: "POST", path: "/api/cards/rewards/claim", headers, body: { code: "api-live" } });
|
|
assert.equal(claimed.status, 200);
|
|
assert.equal(claimed.json.state.giftPacks.length, 1);
|
|
const opened = await call(handler, { method: "POST", path: `/api/cards/gift-packs/${claimed.json.state.giftPacks[0].id}/open`, headers: { ...headers, "idempotency-key": "gift" } });
|
|
assert.equal(opened.status, 201);
|
|
assert.equal(opened.json.opening.cards.length, 3);
|
|
const extended = await call(handler, { method: "PUT", path: `/api/cards/admin/campaigns/${created.json.campaign.id}/expiry`, headers, body: { expiresAt: Date.now() + 120_000 } });
|
|
assert.equal(extended.status, 200);
|
|
});
|