Let Cards players delete their account and read a privacy notice

Add a Compte section with a privacy notice and a confirmed deletion that
anonymises the player row, erases their possessions and cancels open trades.
The public contact comes from CARDS_PRIVACY_CONTACT, which production now
requires before enabling the game. The admin E2E no longer relies on a pull
from the previous test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-05 18:05:41 +01:00
parent 155187d01f
commit e60fbd4e9b
16 changed files with 319 additions and 10 deletions

View file

@ -6,6 +6,8 @@ CARDS_ENABLED=false
CARDS_DB_PATH=/var/lib/sokko-g/cards/nebula-cards.sqlite CARDS_DB_PATH=/var/lib/sokko-g/cards/nebula-cards.sqlite
# La recharge des ouvertures, l'ouverture des paquets et les taux de tirage se règlent depuis l'administration. # La recharge des ouvertures, l'ouverture des paquets et les taux de tirage se règlent depuis l'administration.
CARDS_PUBLIC_ORIGIN=https://sokkog.example.com CARDS_PUBLIC_ORIGIN=https://sokkog.example.com
# Adresse e-mail publique affichée dans la notice de confidentialité ; obligatoire pour activer le jeu en production.
CARDS_PRIVACY_CONTACT=
DISCORD_CLIENT_ID= DISCORD_CLIENT_ID=
DISCORD_CLIENT_SECRET= DISCORD_CLIENT_SECRET=
DISCORD_REDIRECT_URI=https://sokkog.example.com/api/cards/auth/callback DISCORD_REDIRECT_URI=https://sokkog.example.com/api/cards/auth/callback

View file

@ -282,6 +282,9 @@ test("player opens and reveals a three-card pack", async ({ page }) => {
await expect(page.getByText("Cartes à révéler", { exact: true })).toBeVisible(); await expect(page.getByText("Cartes à révéler", { exact: true })).toBeVisible();
await expect(page.getByRole("list", { name: "Cartes obtenues" })).toHaveCount(0); await expect(page.getByRole("list", { name: "Cartes obtenues" })).toHaveCount(0);
await page.goto("/#/cards"); await page.goto("/#/cards");
// L'accueil ne dévoile pas non plus la meilleure carte d'un tirage encore caché.
await expect(page.getByRole("button", { name: "Reprendre l’ouverture", exact: true })).toBeVisible();
await expect(page.locator(".nebula-home-rarest-card")).toHaveCount(0);
await page.getByRole("button", { name: "Reprendre l’ouverture", exact: true }).click(); await page.getByRole("button", { name: "Reprendre l’ouverture", exact: true }).click();
await expect(page.getByRole("button", { name: "Révéler la carte" })).toHaveCount(3); await expect(page.getByRole("button", { name: "Révéler la carte" })).toHaveCount(3);
await page.getByRole("button", { name: "Tout révéler" }).click(); await page.getByRole("button", { name: "Tout révéler" }).click();
@ -1461,3 +1464,53 @@ test("administrator previews the mythic opening from a base without any mythic v
await mythicPreview.getByRole("button", { name: "Révéler la carte Mythique", exact: true }).click(); await mythicPreview.getByRole("button", { name: "Révéler la carte Mythique", exact: true }).click();
await expect(mythicPreview.locator(".nebula-card-particles i").first()).toBeAttached(); await expect(mythicPreview.locator(".nebula-card-particles i").first()).toBeAttached();
}); });
test("a player reads the privacy notice and deletes the account for good", async ({ browser, page }) => {
test.setTimeout(60_000);
const cachedSnapshots = () => page.evaluate(() => new Promise((resolve, reject) => {
const request = globalThis.indexedDB.open("sokkog-nebula-cards", 1);
request.onerror = () => reject(request.error);
request.onsuccess = () => {
const count = request.result.transaction("snapshots").objectStore("snapshots").count();
count.onsuccess = () => { request.result.close(); resolve(count.result); };
count.onerror = () => reject(count.error);
};
}));
const login = page.getByRole("button", { name: "Version développement", exact: true });
await page.goto("/#/cards");
await page.locator(".nebula-privacy-details summary").click();
await expect(page.locator(".nebula-privacy-details").getByRole("link", { name: "privacy@example.invalid" })).toHaveAttribute("href", "mailto:privacy@example.invalid");
await login.click();
await page.getByRole("navigation", { name: "Sections de Sokko TCG" }).getByRole("link", { name: "Compte", exact: true }).click();
await expect(page.getByRole("heading", { name: "Compte", exact: true })).toBeVisible();
await expect(page.locator(".nebula-account-summary dd").first()).toHaveText("Version développement");
await expect(page.locator(".nebula-account").getByRole("link", { name: "privacy@example.invalid" })).toBeVisible();
await expect.poll(cachedSnapshots).toBe(1);
const deleteButton = page.getByRole("button", { name: "Supprimer mon compte", exact: true });
await deleteButton.click();
await page.getByRole("dialog").getByRole("button", { name: "Annuler", exact: true }).click();
await expect(page.getByRole("dialog")).toHaveCount(0);
await expect(page.getByRole("heading", { name: "Compte", exact: true })).toBeVisible();
await deleteButton.click();
await page.getByRole("dialog").getByRole("button", { name: "Supprimer définitivement", exact: true }).click();
await expect(page.getByRole("status")).toContainText("Votre compte a bien été supprimé.");
await expect(page).toHaveURL(/#\/cards$/);
await expect(login).toBeVisible();
expect(await cachedSnapshots()).toBe(0);
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();
expect(traders.map((trader) => trader.displayName)).not.toContain("Version développement");
await partnerContext.close();
// Une nouvelle connexion repart d'un compte neuf, et la déconnexion ne laisse aucune copie dans le navigateur.
await login.click();
await expect(page.locator('.nebula-opening-reserve[aria-label="Ouvertures disponibles"] .nebula-opening-reserve-value')).toContainText("3/ 5");
await expect.poll(cachedSnapshots).toBe(1);
await page.getByRole("button", { name: "Déconnexion", exact: true }).click();
await expect(login).toBeVisible();
expect(await cachedSnapshots()).toBe(0);
});

View file

@ -10,6 +10,7 @@ process.env.CARDS_ENABLED = "true";
process.env.CARDS_DEV_AUTH = "true"; process.env.CARDS_DEV_AUTH = "true";
process.env.CARDS_DB_PATH = join(directory, "cards.sqlite"); process.env.CARDS_DB_PATH = join(directory, "cards.sqlite");
process.env.CARDS_PUBLIC_ORIGIN = `http://127.0.0.1:${process.env.PORT}`; process.env.CARDS_PUBLIC_ORIGIN = `http://127.0.0.1:${process.env.PORT}`;
process.env.CARDS_PRIVACY_CONTACT = "privacy@example.invalid";
// Rend le bouton Discord visible ; les parcours ne le suivent jamais jusqu'à Discord. // Rend le bouton Discord visible ; les parcours ne le suivent jamais jusqu'à Discord.
process.env.DISCORD_CLIENT_ID = "e2e-client"; process.env.DISCORD_CLIENT_ID = "e2e-client";
process.env.DISCORD_CLIENT_SECRET = "e2e-secret"; process.env.DISCORD_CLIENT_SECRET = "e2e-secret";
@ -28,6 +29,8 @@ for (const cardId of ["starvoid-dragon", "crimson-moon-kitsune", "milky-way-pand
for (const finishId of ["spectral-prism-aurora", "spectral-prism-cosmic"]) insertVariation.run(`${cardId}-${finishId}`, cardId, finishId); for (const finishId of ["spectral-prism-aurora", "spectral-prism-cosmic"]) insertVariation.run(`${cardId}-${finishId}`, cardId, finishId);
} }
insertVariation.run("mythic-card-pull-spectral-prism-solar", "mythic-card-pull", "spectral-prism-solar"); insertVariation.run("mythic-card-pull-spectral-prism-solar", "mythic-card-pull", "spectral-prism-solar");
// L'administration distingue les variations déjà possédées : ses parcours ne doivent pas dépendre d'un tirage d'un autre test.
seedService.addCard(partner.id, "starvoid-dragon-spectral-prism-aurora");
seedDatabase.close(); seedDatabase.close();
const { startServer } = await import("../server.mjs"); const { startServer } = await import("../server.mjs");

View file

@ -7,6 +7,7 @@ import { CardsService, DEV_DISCORD_ID } from "./service.js";
const JSON_LIMIT = 64 * 1024; const JSON_LIMIT = 64 * 1024;
const DISCORD_TIMEOUT_MS = 10_000; const DISCORD_TIMEOUT_MS = 10_000;
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
function bool(value, fallback = false) { function bool(value, fallback = false) {
if (value == null || value === "") return fallback; if (value == null || value === "") return fallback;
@ -131,12 +132,16 @@ export function createCardsApiHandler({
// Cette connexion accorde les droits administrateur à n'importe quel visiteur. // Cette connexion accorde les droits administrateur à n'importe quel visiteur.
const devAuth = requestedDevAuth && (env.NODE_ENV !== "production" || allowProductionDevAuth); const devAuth = requestedDevAuth && (env.NODE_ENV !== "production" || allowProductionDevAuth);
if (requestedDevAuth && !devAuth) console.error("CARDS_DEV_AUTH is ignored in production."); if (requestedDevAuth && !devAuth) console.error("CARDS_DEV_AUTH is ignored in production.");
const configuredContact = String(env.CARDS_PRIVACY_CONTACT || "").trim();
const privacyContact = EMAIL_PATTERN.test(configuredContact) ? configuredContact : null;
let database = null; let database = null;
let service = null; let service = null;
if (enabled) { if (enabled) {
if (env.NODE_ENV === "production" && !env.CARDS_DB_PATH) throw new TypeError("CARDS_DB_PATH is required when Sokko TCG is enabled in production."); if (env.NODE_ENV === "production" && !env.CARDS_DB_PATH) throw new TypeError("CARDS_DB_PATH is required when Sokko TCG is enabled in production.");
// Sans origine fixe, le retour OAuth et le contrôle CSRF dépendraient de l'en-tête Host envoyé par le client. // Sans origine fixe, le retour OAuth et le contrôle CSRF dépendraient de l'en-tête Host envoyé par le client.
if (env.NODE_ENV === "production" && !env.CARDS_PUBLIC_ORIGIN) throw new TypeError("CARDS_PUBLIC_ORIGIN is required when Sokko TCG is enabled in production."); if (env.NODE_ENV === "production" && !env.CARDS_PUBLIC_ORIGIN) throw new TypeError("CARDS_PUBLIC_ORIGIN is required when Sokko TCG is enabled in production.");
// La notice de confidentialité doit indiquer à qui s'adresser avant d'ouvrir le jeu à de vrais comptes.
if (env.NODE_ENV === "production" && !privacyContact) throw new TypeError("CARDS_PRIVACY_CONTACT must be a valid e-mail address when Sokko TCG is enabled in production.");
const catalog = loadCardsCatalog(catalogPath); const catalog = loadCardsCatalog(catalogPath);
database = new CardsDatabase(databasePath); database = new CardsDatabase(databasePath);
service = new CardsService({ database, catalog, now, random, devPerks }); service = new CardsService({ database, catalog, now, random, devPerks });
@ -179,7 +184,8 @@ export function createCardsApiHandler({
enabled, enabled,
devAuth: enabled && devAuth, devAuth: enabled && devAuth,
discordConfigured: enabled && Boolean(env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET), discordConfigured: enabled && Boolean(env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET),
catalog: enabled ? publicCatalog(service.catalog) : null catalog: enabled ? publicCatalog(service.catalog) : null,
privacyContact: enabled ? privacyContact : null
}); });
return true; return true;
} }
@ -259,6 +265,12 @@ export function createCardsApiHandler({
json(res, 200, { ok: true }); json(res, 200, { ok: true });
return true; return true;
} }
if (req.method === "DELETE" && url.pathname === "/api/cards/account") {
service.deleteAccount(session.player.id);
res.setHeader("Set-Cookie", sessionCookie("", secureCookies, 0));
json(res, 200, { ok: true });
return true;
}
if (req.method === "GET" && url.pathname === "/api/cards/state") { if (req.method === "GET" && url.pathname === "/api/cards/state") {
json(res, 200, service.getState(session.player.id)); json(res, 200, service.getState(session.player.id));
return true; return true;

View file

@ -187,6 +187,10 @@ const MIGRATIONS = [
ALTER TABLE shop_settings ADD COLUMN shop_pack_share INTEGER NOT NULL DEFAULT 50 CHECK (shop_pack_share BETWEEN 0 AND 100); ALTER TABLE shop_settings ADD COLUMN shop_pack_share INTEGER NOT NULL DEFAULT 50 CHECK (shop_pack_share BETWEEN 0 AND 100);
INSERT OR IGNORE INTO collection_states(collection_id, active, updated_at, updated_by) VALUES ('stardust', 1, 0, NULL); INSERT OR IGNORE INTO collection_states(collection_id, active, updated_at, updated_by) VALUES ('stardust', 1, 0, NULL);
INSERT OR IGNORE INTO drop_rates(collection_id, rarity_weights_json, updated_at, updated_by) VALUES ('stardust', '{"common":64,"rare":24,"epic":8,"legendary":3,"mythic":1}', 0, NULL); INSERT OR IGNORE INTO drop_rates(collection_id, rarity_weights_json, updated_at, updated_by) VALUES ('stardust', '{"common":64,"rare":24,"epic":8,"legendary":3,"mythic":1}', 0, NULL);
`,
// Suppression de compte : la ligne du joueur reste, anonymisée, car les ouvertures, échanges et journaux y font référence.
`
ALTER TABLE players ADD COLUMN deleted_at INTEGER;
` `
]; ];

View file

@ -37,6 +37,7 @@ const PLAYER_HISTORY_EVENTS = Object.freeze([
"gift_created", "gift_joined", "gift_completed", "gift_cancelled" "gift_created", "gift_joined", "gift_completed", "gift_cancelled"
]); ]);
const DEV_STARDUST = 1000; const DEV_STARDUST = 1000;
const DELETED_PLAYER_NAME = "Joueur supprimé";
export class CardsService { export class CardsService {
constructor({ database, catalog, now = Date.now, random, devPerks = false } = {}) { constructor({ database, catalog, now = Date.now, random, devPerks = false } = {}) {
@ -491,7 +492,7 @@ export class CardsService {
(SELECT COALESCE(SUM(c.quantity), 0) FROM collection_cards c WHERE c.player_id = p.id) AS total_cards, (SELECT COALESCE(SUM(c.quantity), 0) FROM collection_cards c WHERE c.player_id = p.id) AS total_cards,
(SELECT COUNT(*) FROM gift_packs g WHERE g.player_id = p.id AND g.opening_id IS NULL) AS gift_packs, (SELECT COUNT(*) FROM gift_packs g WHERE g.player_id = p.id AND g.opening_id IS NULL) AS gift_packs,
(SELECT COUNT(*) FROM transfers t WHERE t.status = 'completed' AND (t.initiator_id = p.id OR t.recipient_id = p.id)) AS transfers_count (SELECT COUNT(*) FROM transfers t WHERE t.status = 'completed' AND (t.initiator_id = p.id OR t.recipient_id = p.id)) AS transfers_count
FROM players p ORDER BY p.display_name COLLATE NOCASE`).all().map((row) => { FROM players p WHERE p.deleted_at IS NULL ORDER BY p.display_name COLLATE NOCASE`).all().map((row) => {
const recharge = this.refreshRecharge(row.id); const recharge = this.refreshRecharge(row.id);
return { return {
id: row.id, id: row.id,
@ -516,7 +517,7 @@ export class CardsService {
generatedAt: now, generatedAt: now,
stats: { stats: {
totalPlayers: players.length, totalPlayers: players.length,
activePlayers7d: this.db.prepare("SELECT COUNT(DISTINCT player_id) AS count FROM openings WHERE created_at >= ?").get(now - 7 * 24 * 3_600_000).count activePlayers7d: this.db.prepare("SELECT COUNT(DISTINCT o.player_id) AS count FROM openings o JOIN players p ON p.id = o.player_id WHERE o.created_at >= ? AND p.deleted_at IS NULL").get(now - 7 * 24 * 3_600_000).count
}, },
players, players,
rechargeSetting: this.rechargeSetting, rechargeSetting: this.rechargeSetting,
@ -663,7 +664,7 @@ export class CardsService {
// Joueurs à qui donner ou proposer un échange : seuls leur identité publique et leurs doublons disponibles sont exposés, jamais leur collection. // Joueurs à qui donner ou proposer un échange : seuls leur identité publique et leurs doublons disponibles sont exposés, jamais leur collection.
listTraders(playerId) { listTraders(playerId) {
this.expireTransfers(); this.expireTransfers();
const rows = this.db.prepare("SELECT id, display_name, avatar_url FROM players WHERE id != ? ORDER BY display_name COLLATE NOCASE").all(playerId); 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);
return { return {
traders: rows.map((row) => ({ traders: rows.map((row) => ({
id: row.id, id: row.id,
@ -682,7 +683,28 @@ export class CardsService {
requireRecipient(playerId, recipientId) { requireRecipient(playerId, recipientId) {
if (recipientId === playerId) fail(409, "SELF_TRANSFER", "Vous ne pouvez pas vous envoyer une carte."); if (recipientId === playerId) fail(409, "SELF_TRANSFER", "Vous ne pouvez pas vous envoyer une carte.");
if (!recipientId || !this.db.prepare("SELECT 1 FROM players WHERE id = ?").get(recipientId)) fail(404, "PLAYER_NOT_FOUND", "Ce joueur est introuvable."); if (!recipientId || !this.db.prepare("SELECT 1 FROM players WHERE id = ? AND deleted_at IS NULL").get(recipientId)) fail(404, "PLAYER_NOT_FOUND", "Ce joueur est introuvable.");
}
// Efface l'identité Discord et les possessions du joueur. Sa ligne reste, anonymisée, pour que l'historique des autres joueurs garde son sens ;
// une reconnexion avec le même compte Discord crée un compte neuf.
deleteAccount(playerId) {
this.database.transaction(() => {
if (!this.db.prepare("SELECT 1 FROM players WHERE id = ? AND deleted_at IS NULL").get(playerId)) fail(404, "PLAYER_NOT_FOUND", "Profil introuvable.");
for (const transfer of this.db.prepare("SELECT * FROM transfers WHERE status = 'open' AND (initiator_id = ?1 OR recipient_id = ?1)").all(playerId)) {
this.db.prepare("UPDATE transfers SET status = 'cancelled' WHERE id = ?").run(transfer.id);
const initiatorLeft = transfer.initiator_id === playerId;
this.audit(initiatorLeft ? transfer.recipient_id : transfer.initiator_id, "trade_cancelled", transfer.id, initiatorLeft
? { sent: transfer.requested_edition_id, received: transfer.offered_edition_id }
: { sent: transfer.offered_edition_id, received: transfer.requested_edition_id });
}
this.db.prepare("UPDATE openings SET status = 'completed', completed_at = ? WHERE player_id = ? AND status = 'pending'").run(this.now(), playerId);
for (const table of ["sessions", "collection_cards", "favorites", "idempotency"]) this.db.prepare(`DELETE FROM ${table} WHERE player_id = ?`).run(playerId);
this.db.prepare("DELETE FROM gift_packs WHERE player_id = ? AND opening_id IS NULL").run(playerId);
this.db.prepare(`UPDATE players SET discord_id = ?, display_name = ?, avatar_url = '', is_admin = 0, openings_balance = 0, recharge_anchor = NULL, stardust = 0, purchased_openings = 0, deleted_at = ? WHERE id = ?`)
.run(`deleted:${randomUUID()}`, DELETED_PLAYER_NAME, this.now(), playerId);
this.audit(playerId, "account_deleted", playerId, {});
});
} }
// Un don arrive immédiatement. Un échange réserve le doublon proposé jusqu'à la réponse, l'annulation ou l'expiration. // Un don arrive immédiatement. Un échange réserve le doublon proposé jusqu'à la réponse, l'annulation ou l'expiration.

View file

@ -196,6 +196,8 @@ export function validateSiteContent(site) {
"cards.collection.title", "cards.collection.title",
"cards.collection.resetFilters", "cards.collection.resetFilters",
"cards.history.pendingCards", "cards.history.pendingCards",
...["eyebrow", "title", "description", "summaryTitle", "summaryName", "summaryCards", "summaryOpenings", "deleteTitle", "deleteText", "deleteButton", "confirmTitle", "confirmMessage", "confirmLabel", "deleted"].map((key) => `cards.account.${key}`),
...["title", "intro", "collectedTitle", "collected", "purposeTitle", "purpose", "visibilityTitle", "visibility", "retentionTitle", "retention", "rightsTitle", "rights", "contactLabel", "contactMissing"].map((key) => `cards.privacy.${key}`),
"cards.recycling.barLabel", "cards.recycling.barLabel",
"cards.recycling.viewDuplicates", "cards.recycling.viewDuplicates",
"cards.recycling.viewAll", "cards.recycling.viewAll",

View file

@ -278,3 +278,34 @@ test("the administrator list is applied to existing accounts at startup", async
assert.equal(isAdmin(third, DEV_DISCORD_ID), false); assert.equal(isAdmin(third, DEV_DISCORD_ID), false);
third.close(); 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" };
for (const contact of [undefined, "", "not-an-email"]) {
assert.throws(() => createCardsApiHandler({ projectRoot: resolve("."), enabled: true, env: { ...base, CARDS_PRIVACY_CONTACT: contact } }), /CARDS_PRIVACY_CONTACT/);
}
const disabled = createCardsApiHandler({ projectRoot: resolve("."), enabled: false, env: { ...base, CARDS_PRIVACY_CONTACT: "privacy@example.invalid" } });
assert.equal((await call(disabled, { path: "/api/cards/config" })).json.privacyContact, null);
const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, env: { ...base, CARDS_PRIVACY_CONTACT: "privacy@example.invalid" } });
t.after(() => handler.close());
assert.equal((await call(handler, { path: "/api/cards/config" })).json.privacyContact, "privacy@example.invalid");
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);
});

View file

@ -701,6 +701,61 @@ test("displayed odds only count the rarities a pack can really give", () => {
assert.ok(Math.abs(filtered.common - 64 / 99 * 100) < 1e-9); assert.ok(Math.abs(filtered.common - 64 / 99 * 100) < 1e-9);
}); });
test("deleting an account erases the identity and possessions but keeps shared history consistent", () => {
let now = 1_800_000_000_000;
const database = new CardsDatabase(":memory:");
const service = new CardsService({ database, catalog: baseCatalog, now: () => now, random: () => 0 });
const leaver = service.upsertPlayer({ discordId: "leaver-discord", displayName: "Leaver", avatarUrl: "https://cdn.invalid/a.png" });
const friend = service.upsertPlayer({ discordId: "friend-discord", displayName: "Friend" });
const admin = service.upsertPlayer({ discordId: "admin-discord", displayName: "Admin", isAdmin: true });
const session = service.createSession(leaver.id);
const editionId = "aurora-wolf-standard";
for (const player of [leaver, friend]) for (let copy = 0; copy < 3; copy += 1) service.addCard(player.id, editionId);
service.addCard(friend.id, "starvoid-dragon-standard");
service.addCard(friend.id, "starvoid-dragon-standard");
service.setFavorite(leaver.id, editionId, true);
const { opening } = service.openPack(leaver.id, "primordial-nebula", "leaver-pack");
service.completeOpening(leaver.id, opening.id);
const trade = service.createTransfer(leaver.id, { type: "trade", recipientId: friend.id, editionId, requestedEditionId: "starvoid-dragon-standard" }).transfer;
database.db.prepare("UPDATE players SET stardust = 50, purchased_openings = 2 WHERE id = ?").run(leaver.id);
const campaign = service.createCampaign(admin.id, { name: "Gift", code: "LEAVER-GIFT", reward: { items: [{ type: "pack", collectionId: "primordial-nebula", quantity: 1 }] } }).campaign;
service.claimCampaign(leaver.id, "LEAVER-GIFT");
service.deleteAccount(leaver.id);
assert.equal(service.getSession(session.token), null);
const row = database.db.prepare("SELECT * FROM players WHERE id = ?").get(leaver.id);
assert.equal(row.discord_id.startsWith("deleted:"), true);
assert.equal(row.display_name, "Joueur supprimé");
assert.equal(row.avatar_url, "");
assert.equal(row.is_admin, 0);
assert.equal(row.stardust, 0);
assert.equal(row.purchased_openings, 0);
assert.equal(row.deleted_at, now);
for (const table of ["collection_cards", "favorites", "idempotency", "sessions"]) assert.equal(database.db.prepare(`SELECT COUNT(*) AS count FROM ${table} WHERE player_id = ?`).get(leaver.id).count, 0, table);
assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM gift_packs WHERE player_id = ? AND opening_id IS NULL").get(leaver.id).count, 0);
assert.equal(JSON.stringify(database.db.prepare("SELECT * FROM players WHERE id = ?").get(leaver.id)).includes("leaver-discord"), false);
const friendState = service.getState(friend.id);
const friendTrade = friendState.transfers.find((transfer) => transfer.id === trade.id);
assert.equal(friendTrade.status, "cancelled");
assert.equal(friendTrade.initiator.displayName, "Joueur supprimé");
assert.equal(service.listTraders(friend.id).traders.some((trader) => trader.id === leaver.id), false);
assert.throws(() => service.createTransfer(friend.id, { type: "gift", recipientId: leaver.id, editionId }), /introuvable/);
const dashboard = service.getAdminDashboard(admin.id);
assert.equal(dashboard.stats.totalPlayers, 2);
assert.equal(dashboard.stats.activePlayers7d, 0);
assert.equal(dashboard.players.some((player) => player.id === leaver.id), false);
assert.equal(service.campaignDetail(admin.id, campaign.id).claims[0].playerName, "Joueur supprimé");
now += 1000;
const returning = service.upsertPlayer({ discordId: "leaver-discord", displayName: "Leaver" });
assert.notEqual(returning.id, leaver.id);
assert.deepEqual(service.getState(returning.id).collection, []);
assert.throws(() => service.deleteAccount(leaver.id), /introuvable/);
database.close();
});
test("restoring replaces the database even when the stopped service left a write-ahead log", async () => { 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 directory = await mkdtemp(join(tmpdir(), "sokko-cards-restore-wal-"));
const live = join(directory, "live.sqlite"); const live = join(directory, "live.sqlite");

View file

@ -59,7 +59,8 @@
"collection": "Collection", "collection": "Collection",
"shop": "Boutique", "shop": "Boutique",
"transfers": "Échanges et dons", "transfers": "Échanges et dons",
"history": "Historique" "history": "Historique",
"account": "Compte"
}, },
"shop": { "shop": {
"packDescription": "Les cartes de toutes les collections actives et les légendaires et mythiques exclusives de cette collection.", "packDescription": "Les cartes de toutes les collections actives et les légendaires et mythiques exclusives de cette collection.",
@ -121,6 +122,38 @@
"history": { "history": {
"pendingCards": "Cartes à révéler" "pendingCards": "Cartes à révéler"
}, },
"account": {
"eyebrow": "Vos données",
"title": "Compte",
"description": "Retrouvez ce que Sokko TCG conserve pour votre compte et supprimez-le quand vous le souhaitez.",
"summaryTitle": "Ce qui est lié à votre compte",
"summaryName": "Pseudo Discord",
"summaryCards": "Cartes en collection",
"summaryOpenings": "Paquets ouverts",
"deleteTitle": "Supprimer mon compte",
"deleteText": "Votre identité Discord, votre collection, vos favoris, vos poussières d’étoiles et vos ouvertures sont effacés, et vos propositions d’échange en cours sont annulées. Les échanges passés restent visibles par les autres joueurs sous le nom « Joueur supprimé ». Cette action est définitive : une nouvelle connexion crée un compte neuf.",
"deleteButton": "Supprimer mon compte",
"confirmTitle": "Supprimer définitivement votre compte ?",
"confirmMessage": "Votre collection et vos ressources seront perdues. Cette action ne peut pas être annulée.",
"confirmLabel": "Supprimer définitivement",
"deleted": "Votre compte a bien été supprimé."
},
"privacy": {
"title": "Confidentialité de Sokko TCG",
"intro": "Sokko TCG est le seul espace de Sokko G à stocker des données sur le serveur. Vos toolboxes restent dans votre navigateur.",
"collectedTitle": "Données conservées",
"collected": "Votre identifiant, votre pseudo et votre avatar Discord, ainsi que votre collection, vos ouvertures, vos échanges et votre historique de jeu. La connexion Discord ne demande ni votre e-mail ni vos messages. Un cookie garde votre session ouverte et une copie de votre collection reste dans ce navigateur pour la consultation hors connexion.",
"purposeTitle": "Utilisation",
"purpose": "Ces données servent uniquement à faire fonctionner votre compte et le jeu. Votre adresse IP sert à limiter les abus ; elle n’est pas enregistrée dans la base du jeu.",
"visibilityTitle": "Visibilité",
"visibility": "Les joueurs connectés voient votre pseudo, votre avatar et vos doublons disponibles, afin de vous proposer des dons et des échanges. Le reste de votre collection n’est pas partagé.",
"retentionTitle": "Durée de conservation",
"retention": "Vos données sont conservées tant que votre compte existe. Après sa suppression, elles disparaissent des sauvegardes sous 14 jours.",
"rightsTitle": "Vos droits",
"rights": "Vous pouvez supprimer votre compte depuis la section Compte, et demander l’accès à vos données ou leur correction à l’adresse ci-dessous. Vous pouvez aussi saisir la CNIL.",
"contactLabel": "Contact",
"contactMissing": "Contact non configuré sur ce serveur."
},
"recycling": { "recycling": {
"barLabel": "Recyclage des doublons", "barLabel": "Recyclage des doublons",
"viewDuplicates": "Voir les doublons", "viewDuplicates": "Voir les doublons",
@ -1856,7 +1889,7 @@
"about": { "about": {
"eyebrow": "À propos", "eyebrow": "À propos",
"title": "C'est quoi Sokko G ?", "title": "C'est quoi Sokko G ?",
"description": "Sokko G est un espace local pour organiser vos notes, outils et repères de jeu. Il est pensé pour rester ouvert à côté de votre partie, sans compte et sans synchronisation obligatoire.", "description": "Sokko G est un espace local pour organiser vos notes, outils et repères de jeu. Il est pensé pour rester ouvert à côté de votre partie : les toolboxes fonctionnent sans compte et sans synchronisation obligatoire. Seul le mini-jeu Sokko TCG utilise un compte Discord et conserve ses données sur le serveur.",
"sectionsEyebrow": "Concept", "sectionsEyebrow": "Concept",
"sectionsTitle": "Faciliter vos sessions gaming", "sectionsTitle": "Faciliter vos sessions gaming",
"sections": [ "sections": [

View file

@ -0,0 +1,39 @@
// Rôle : présente au joueur les données liées à son compte, la notice de confidentialité et la suppression du compte.
import { useState } from "react";
import { ConfirmModal } from "../../components/ToolboxModals.jsx";
import { PrivacyNotice } from "./PrivacyNotice.jsx";
export function AccountPanel({ state, busy, content, privacy, privacyContact, onDelete }) {
const [confirming, setConfirming] = useState(false);
const cards = state.collection.reduce((total, entry) => total + entry.quantity, 0);
return <div className="nebula-account">
<div className="nds-section-heading nebula-section-heading"><div><p className="eyebrow">{content.eyebrow}</p><h2>{content.title}</h2><p>{content.description}</p></div></div>
<section className="nds-panel nebula-account-summary" aria-labelledby="nebula-account-summary-title">
<h3 id="nebula-account-summary-title">{content.summaryTitle}</h3>
<dl>
<div><dt>{content.summaryName}</dt><dd>{state.player.displayName}</dd></div>
<div><dt>{content.summaryCards}</dt><dd>{cards.toLocaleString("fr-FR")}</dd></div>
<div><dt>{content.summaryOpenings}</dt><dd>{state.stats.openingsCount.toLocaleString("fr-FR")}</dd></div>
</dl>
</section>
<section className="nds-panel" aria-labelledby="nebula-account-privacy-title">
<h3 id="nebula-account-privacy-title">{privacy.title}</h3>
<PrivacyNotice content={privacy} contact={privacyContact} />
</section>
<section className="nds-panel nebula-account-delete" aria-labelledby="nebula-account-delete-title">
<h3 id="nebula-account-delete-title">{content.deleteTitle}</h3>
<p>{content.deleteText}</p>
<button className="nds-button" data-size="sm" data-variant="danger" type="button" disabled={busy} onClick={() => setConfirming(true)}>{content.deleteButton}</button>
</section>
{confirming && <ConfirmModal
title={content.confirmTitle}
message={content.confirmMessage}
confirmLabel={content.confirmLabel}
danger
onClose={(confirmed) => {
setConfirming(false);
if (confirmed) void onDelete();
}}
/>}
</div>;
}

View file

@ -3,17 +3,19 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { navigate } from "../../router/hashRouter.js"; import { navigate } from "../../router/hashRouter.js";
import { AdminPanel } from "./admin/AdminPanel.jsx"; import { AdminPanel } from "./admin/AdminPanel.jsx";
import { clearCardsCache, readLatestCardsCache, writeCardsCache } from "./cardCache.js"; import { clearCardsCache, readLatestCardsCache, writeCardsCache } from "./cardCache.js";
import { devLogin, loadCardsSession, loadCardsState, logoutCards } from "./cardsApi.js"; import { AccountPanel } from "./AccountPanel.jsx";
import { deleteCardsAccount, devLogin, loadCardsSession, loadCardsState, logoutCards } from "./cardsApi.js";
import { CardsAccount, CardsDashboardLayout } from "./CardsDashboard.jsx"; import { CardsAccount, CardsDashboardLayout } from "./CardsDashboard.jsx";
import { CardsHomePanel } from "./CardsHomePanel.jsx"; import { CardsHomePanel } from "./CardsHomePanel.jsx";
import { CollectionPanel } from "./CollectionPanel.jsx"; import { CollectionPanel } from "./CollectionPanel.jsx";
import { HistoryPanel } from "./HistoryPanel.jsx"; import { HistoryPanel } from "./HistoryPanel.jsx";
import { PackPanel } from "./PackPanel.jsx"; import { PackPanel } from "./PackPanel.jsx";
import { PrivacyNotice } from "./PrivacyNotice.jsx";
import { ShopPanel } from "./ShopPanel.jsx"; import { ShopPanel } from "./ShopPanel.jsx";
import { TransfersPanel } from "./TransfersPanel.jsx"; import { TransfersPanel } from "./TransfersPanel.jsx";
// Le jeu, puis l'économie et les échanges, puis le journal : mêmes groupes séparés par un filet que l'administration. // Le jeu, puis l'économie et les échanges, puis le journal : mêmes groupes séparés par un filet que l'administration.
const PLAYER_NAVIGATION = [["home", "packs", "collection"], ["shop", "transfers"], ["history"]]; const PLAYER_NAVIGATION = [["home", "packs", "collection"], ["shop", "transfers"], ["history", "account"]];
const PLAYER_SECTIONS = new Set(PLAYER_NAVIGATION.flat()); const PLAYER_SECTIONS = new Set(PLAYER_NAVIGATION.flat());
// Ancienne adresse conservée pour les favoris : le recyclage vit désormais dans la Collection. // Ancienne adresse conservée pour les favoris : le recyclage vit désormais dans la Collection.
const PLAYER_SECTION_ALIASES = { recycling: "collection" }; const PLAYER_SECTION_ALIASES = { recycling: "collection" };
@ -42,6 +44,7 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", adminM
const [error, setError] = useState(""); const [error, setError] = useState("");
const [authFailure] = useState(readDiscordAuthFailure); const [authFailure] = useState(readDiscordAuthFailure);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const [accountDeleted, setAccountDeleted] = useState(false);
const resolvedSection = PLAYER_SECTION_ALIASES[playerSection] || playerSection; const resolvedSection = PLAYER_SECTION_ALIASES[playerSection] || playerSection;
const section = PLAYER_SECTIONS.has(resolvedSection) ? resolvedSection : "home"; const section = PLAYER_SECTIONS.has(resolvedSection) ? resolvedSection : "home";
const [transferDraft, setTransferDraft] = useState(null); const [transferDraft, setTransferDraft] = useState(null);
@ -180,9 +183,24 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", adminM
{!cardsConfig.discordConfigured && <p className="nds-inline-notice" data-variant="warning" role="status">{content.discordUnavailable}</p>} {!cardsConfig.discordConfigured && <p className="nds-inline-notice" data-variant="warning" role="status">{content.discordUnavailable}</p>}
{authFailure && <p className="nds-inline-notice" data-variant="danger" role="alert">{content.discordErrors[authFailure] || content.discordErrors.failed}</p>} {authFailure && <p className="nds-inline-notice" data-variant="danger" role="alert">{content.discordErrors[authFailure] || content.discordErrors.failed}</p>}
{error && <p className="nds-inline-notice" data-variant="danger" role="alert">{error}</p>} {error && <p className="nds-inline-notice" data-variant="danger" role="alert">{error}</p>}
{accountDeleted && <p className="nds-inline-notice" data-variant="success" role="status">{content.account.deleted}</p>}
<details className="nebula-privacy-details">
<summary>{content.privacy.title}</summary>
<PrivacyNotice content={content.privacy} contact={cardsConfig.privacyContact} />
</details>
</div> </div>
</section>; </section>;
async function deleteAccount() {
const result = await runMutation(() => deleteCardsAccount());
if (!result?.ok) return;
await clearCardsCache().catch(() => {});
setState(null);
setAccountDeleted(true);
setStatus("anonymous");
navigate("/cards");
}
async function logout() { async function logout() {
await logoutCards(); await logoutCards();
await clearCardsCache().catch(() => {}); await clearCardsCache().catch(() => {});
@ -234,6 +252,7 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", adminM
{section === "shop" && <ShopPanel {...panelProps} content={content.shop} onOpenPacks={openPacks} />} {section === "shop" && <ShopPanel {...panelProps} content={content.shop} onOpenPacks={openPacks} />}
{section === "transfers" && <TransfersPanel {...panelProps} content={content.transfers} draft={transferDraft} onDraftUsed={clearTransferDraft} />} {section === "transfers" && <TransfersPanel {...panelProps} content={content.transfers} draft={transferDraft} onDraftUsed={clearTransferDraft} />}
{section === "history" && <HistoryPanel catalog={catalog} state={state} content={content.history} />} {section === "history" && <HistoryPanel catalog={catalog} state={state} content={content.history} />}
{section === "account" && <AccountPanel state={state} busy={busy || offline} content={content.account} privacy={content.privacy} privacyContact={cardsConfig.privacyContact} onDelete={deleteAccount} />}
</CardsDashboardLayout> </CardsDashboardLayout>
</div>} </div>}
</div>; </div>;

View file

@ -0,0 +1,13 @@
// Rôle : présente la notice de confidentialité de Sokko TCG et le contact configuré sur le serveur.
const SECTIONS = ["collected", "purpose", "visibility", "retention", "rights"];
export function PrivacyNotice({ content, contact }) {
return <div className="nebula-privacy-notice">
<p>{content.intro}</p>
{SECTIONS.map((section) => <section key={section}>
<h4>{content[`${section}Title`]}</h4>
<p>{content[section]}</p>
</section>)}
<p className="nebula-privacy-contact"><strong>{content.contactLabel}</strong> {contact ? <a href={`mailto:${contact}`}>{contact}</a> : content.contactMissing}</p>
</div>;
}

View file

@ -14,7 +14,8 @@ const EVENT_LABELS = {
drop_rates_updated: "Taux de tirage modifiés", drop_rates_updated: "Taux de tirage modifiés",
campaign_created: "Campagne créée", campaign_created: "Campagne créée",
campaign_revoked: "Campagne révoquée", campaign_revoked: "Campagne révoquée",
campaign_extended: "Campagne prolongée" campaign_extended: "Campagne prolongée",
account_deleted: "Compte joueur supprimé"
}; };
const collectionName = (entry, catalog) => catalog.collections.find((item) => item.id === entry.entityId)?.name || entry.entityId; const collectionName = (entry, catalog) => catalog.collections.find((item) => item.id === entry.entityId)?.name || entry.entityId;

View file

@ -49,6 +49,12 @@ export async function logoutCards() {
return result; return result;
} }
export async function deleteCardsAccount() {
const result = await request("/account", { method: "DELETE" });
csrfToken = "";
return result;
}
// `purchased` : utilise une ouverture achetée en boutique au lieu de la réserve rechargeable. // `purchased` : utilise une ouverture achetée en boutique au lieu de la réserve rechargeable.
export function openPack(collectionId, { purchased = false } = {}) { export function openPack(collectionId, { purchased = false } = {}) {
const requestKey = crypto.randomUUID(); const requestKey = crypto.randomUUID();

View file

@ -853,3 +853,17 @@ main:has(.nebula-dashboard) { overflow-x: clip; }
.nebula-admin-collection-settings .nebula-admin-drop-table td:first-of-type .nds-input { width: 56px; } .nebula-admin-collection-settings .nebula-admin-drop-table td:first-of-type .nds-input { width: 56px; }
.nebula-admin-collection-settings .nebula-admin-drop-table tbody th { padding-left: var(--space-2); } .nebula-admin-collection-settings .nebula-admin-drop-table tbody th { padding-left: var(--space-2); }
} }
// Compte du joueur et notice de confidentialité.
.nebula-account { display: grid; gap: var(--space-4); }
.nebula-account-summary dl { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: var(--space-3); margin: var(--space-3) 0 0; }
.nebula-account-summary dt { color: var(--color-text-muted); font-size: var(--font-size-xs); }
.nebula-account-summary dd { margin: 0; overflow-wrap: anywhere; }
.nebula-account-delete > .nds-button { justify-self: start; margin-top: var(--space-3); }
.nebula-privacy-details { margin-top: var(--space-3); color: var(--color-text-muted); font-size: var(--font-size-xs); }
.nebula-privacy-details summary { width: fit-content; cursor: pointer; }
.nebula-privacy-details summary:focus-visible { outline: 2px solid var(--color-primary); outline-offset: 2px; }
.nebula-privacy-notice { display: grid; gap: var(--space-2); margin-top: var(--space-2); }
.nebula-privacy-notice p { margin: 0; }
.nebula-privacy-notice h4 { margin: 0 0 var(--space-1); }
.nebula-privacy-contact a { overflow-wrap: anywhere; }