sokko-g/tests/nebula-cards-api.test.mjs
Shinuwa 9ce0c3e33a
All checks were successful
Validate and deploy Sokko G / validate (push) Successful in 19m52s
Validate and deploy Sokko G / deploy (push) Successful in 10s
Tighten the remaining Cards and dev server security defaults
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>
2026-11-06 14:27:22 +01:00

361 lines
24 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 { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { createCardsApiHandler } from "../services/cards/api.js";
import { DEV_DISCORD_ID } from "../services/cards/service.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 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);
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);
});
test("development login cannot be enabled in production by configuration alone", async (t) => {
const originalError = console.error;
const logged = [];
console.error = (...values) => logged.push(values.join(" "));
t.after(() => { console.error = originalError; });
const env = { NODE_ENV: "production", CARDS_ENABLED: "true", CARDS_DEV_AUTH: "true", CARDS_DB_PATH: ":memory:", CARDS_PUBLIC_ORIGIN: "https://cards.invalid", CARDS_PRIVACY_CONTACT: "privacy@example.invalid", CARDS_PRIVACY_CONTROLLER: "Exploitant de test" };
const refused = createCardsApiHandler({ projectRoot: resolve("."), env });
t.after(() => refused.close());
assert.equal((await call(refused, { path: "/api/cards/config" })).json.devAuth, false);
assert.equal((await call(refused, { method: "POST", path: "/api/cards/auth/dev" })).status, 404);
assert.match(logged.join("\n"), /CARDS_DEV_AUTH/);
const explicit = createCardsApiHandler({ projectRoot: resolve("."), env, allowProductionDevAuth: true });
t.after(() => explicit.close());
assert.equal((await call(explicit, { path: "/api/cards/config" })).json.devAuth, true);
});
test("the administrator list is applied to existing accounts at startup", async (t) => {
const directory = await mkdtemp(join(tmpdir(), "sokko-cards-admins-"));
t.after(() => rm(directory, { recursive: true, force: true }));
const databasePath = join(directory, "cards.sqlite");
const start = (adminIds, devAuth = false) => createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth, databasePath, env: { NODE_ENV: "test", CARDS_ADMIN_DISCORD_IDS: adminIds } });
const isAdmin = (handler, discordId) => Boolean(handler.service.db.prepare("SELECT is_admin FROM players WHERE discord_id = ?").get(discordId).is_admin);
const first = start("removed,kept");
for (const discordId of ["removed", "kept"]) first.service.upsertPlayer({ discordId, displayName: discordId, isAdmin: true });
first.service.upsertPlayer({ discordId: "promoted", displayName: "promoted" });
first.service.upsertPlayer({ discordId: DEV_DISCORD_ID, displayName: "dev", isAdmin: true });
const removedPlayer = first.service.upsertPlayer({ discordId: "removed", displayName: "removed", isAdmin: true });
const openSession = first.service.createSession(removedPlayer.id);
first.close();
const second = start("kept,promoted", true);
assert.deepEqual(["removed", "kept", "promoted", DEV_DISCORD_ID].map((id) => isAdmin(second, id)), [false, true, true, true]);
const forbidden = await call(second, { path: "/api/cards/admin/dashboard", headers: { cookie: `sokkog_cards_session=${openSession.token}` } });
assert.equal(forbidden.status, 403);
second.close();
const third = start("kept");
assert.equal(isAdmin(third, DEV_DISCORD_ID), false);
third.close();
});
test("the privacy contact is published only when valid and required to enable the game in production", async (t) => {
const base = { NODE_ENV: "production", CARDS_DB_PATH: ":memory:", CARDS_PUBLIC_ORIGIN: "https://cards.invalid", CARDS_PRIVACY_CONTROLLER: "Exploitant de test" };
for (const contact of [undefined, "", "not-an-email"]) {
assert.throws(() => createCardsApiHandler({ projectRoot: resolve("."), enabled: true, env: { ...base, CARDS_PRIVACY_CONTACT: contact } }), /CARDS_PRIVACY_CONTACT/);
}
for (const controller of [undefined, " "]) {
assert.throws(() => createCardsApiHandler({ projectRoot: resolve("."), enabled: true, env: { ...base, CARDS_PRIVACY_CONTACT: "privacy@example.invalid", CARDS_PRIVACY_CONTROLLER: controller } }), /CARDS_PRIVACY_CONTROLLER/);
}
const disabled = createCardsApiHandler({ projectRoot: resolve("."), enabled: false, env: { ...base, CARDS_PRIVACY_CONTACT: "privacy@example.invalid" } });
const disabledConfig = (await call(disabled, { path: "/api/cards/config" })).json;
assert.equal(disabledConfig.privacyContact, null);
assert.equal(disabledConfig.privacyController, null);
const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, env: { ...base, CARDS_PRIVACY_CONTACT: "privacy@example.invalid" } });
t.after(() => handler.close());
const config = (await call(handler, { path: "/api/cards/config" })).json;
assert.equal(config.privacyContact, "privacy@example.invalid");
assert.equal(config.privacyController, "Exploitant de test");
const development = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, databasePath: ":memory:", env: { NODE_ENV: "test" } });
t.after(() => development.close());
assert.equal((await call(development, { path: "/api/cards/config" })).json.privacyContact, null);
});
test("account deletion needs a CSRF token, clears the session cookie and logs the player out", async (t) => {
const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: false, databasePath: ":memory:", env: { NODE_ENV: "test" } });
t.after(() => handler.close());
const player = handler.service.upsertPlayer({ discordId: "api-leaver", displayName: "Leaver" });
const session = handler.service.createSession(player.id);
const cookie = `sokkog_cards_session=${session.token}`;
assert.equal((await call(handler, { method: "DELETE", path: "/api/cards/account" })).status, 401);
assert.equal((await call(handler, { method: "DELETE", path: "/api/cards/account", headers: { cookie } })).status, 403);
const deleted = await call(handler, { method: "DELETE", path: "/api/cards/account", headers: { cookie, "x-csrf-token": session.csrfToken } });
assert.equal(deleted.status, 200);
assert.match(String(deleted.headers["set-cookie"]), /sokkog_cards_session=;.*Max-Age=0/);
assert.equal((await call(handler, { path: "/api/cards/session", headers: { cookie } })).json.authenticated, false);
});
test("without explicit settings the game and the fake admin login stay off, whatever NODE_ENV says", async (t) => {
for (const env of [{}, { NODE_ENV: "test" }]) {
const handler = createCardsApiHandler({ projectRoot: resolve("."), databasePath: ":memory:", env });
t.after(() => handler.close());
const { json } = await call(handler, { path: "/api/cards/config" });
assert.equal(json.enabled, false);
assert.equal(json.devAuth, false);
}
const enabledOnly = createCardsApiHandler({ projectRoot: resolve("."), databasePath: ":memory:", env: { CARDS_ENABLED: "true" } });
t.after(() => enabledOnly.close());
const { json } = await call(enabledOnly, { path: "/api/cards/config" });
assert.equal(json.enabled, true);
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);
});