Add the Sokko TCG collectible card mini-game

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>
This commit is contained in:
Shinuwa 2026-11-05 17:47:35 +01:00
parent 243465720f
commit 5ce35cd7ba
193 changed files with 12159 additions and 28 deletions

View file

@ -0,0 +1,21 @@
// Rôle : contenu de départ des tables gérées depuis l'administration, inséré par la migration 2.
// Listes figées : elles décrivent l'état initial de la base ; la suite se gère depuis l'administration.
// Paquets ouvrables au départ.
export const INITIAL_COLLECTION_STATES = Object.freeze([
Object.freeze({ collectionId: "primordial-nebula", active: true }),
Object.freeze({ collectionId: "astral-genesis", active: true })
]);
// Taux de tirage de départ, égaux aux poids recommandés des raretés (catalog.json).
const LAUNCH_WEIGHTS = Object.freeze({ common: 64, rare: 24, epic: 8, legendary: 3, mythic: 1 });
export const INITIAL_DROP_RATES = Object.freeze(["primordial-nebula", "astral-genesis"].map((collectionId) => Object.freeze({ collectionId, rarityWeights: LAUNCH_WEIGHTS })));
// Recharge de départ : une ouverture toutes les heures, réserve plafonnée à 5.
export const INITIAL_RECHARGE_SETTING = Object.freeze({ intervalMs: 60 * 60 * 1000, maxOpenings: 5 });
// Boutique de départ : poussière d'étoiles gagnée par doublon recyclé, selon sa rareté, et prix d'une ouverture achetée.
export const INITIAL_SHOP_SETTING = Object.freeze({
stardustValues: Object.freeze({ common: 1, rare: 3, epic: 10, legendary: 40, mythic: 150 }),
openingPrice: 30
});

362
services/cards/api.js Normal file
View file

@ -0,0 +1,362 @@
// Rôle : expose l'API HTTP, l'authentification Discord et les protections de session Sokko TCG.
import { randomBytes } from "node:crypto";
import { join, resolve } from "node:path";
import { CardsDatabase } from "./database.js";
import { loadCardsCatalog, publicCatalog } from "./catalog.js";
import { CardsService, DEV_DISCORD_ID } from "./service.js";
const JSON_LIMIT = 64 * 1024;
const DISCORD_TIMEOUT_MS = 10_000;
function bool(value, fallback = false) {
if (value == null || value === "") return fallback;
return /^(1|true|yes|on)$/i.test(String(value));
}
function json(res, status, body) {
const payload = JSON.stringify(body);
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": Buffer.byteLength(payload),
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff"
});
res.end(payload);
}
function redirect(res, location, cookies = []) {
const headers = { Location: location, "Cache-Control": "no-store" };
if (cookies.length) headers["Set-Cookie"] = cookies;
res.writeHead(302, headers);
res.end();
}
function parseCookies(req) {
return Object.fromEntries(String(req.headers.cookie || "").split(";").map((entry) => entry.trim()).filter(Boolean).map((entry) => {
const separator = entry.indexOf("=");
return [decodeURIComponent(entry.slice(0, separator)), decodeURIComponent(entry.slice(separator + 1))];
}));
}
function sessionCookie(value, secure, maxAge = 30 * 24 * 60 * 60) {
return `sokkog_cards_session=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? "; Secure" : ""}`;
}
function stateCookie(value, secure, maxAge = 600) {
return `sokkog_cards_oauth_state=${encodeURIComponent(value)}; Path=/api/cards/auth; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? "; Secure" : ""}`;
}
function oauthReturnCookie(value, secure, maxAge = 600) {
return `sokkog_cards_oauth_return=${encodeURIComponent(value)}; Path=/api/cards/auth; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? "; Secure" : ""}`;
}
function cardsReturnPath(value) {
return /^\/cards(?:\/admin(?:\/[a-z0-9-]{1,40}){0,2}|\/[a-z0-9-]{1,40})?$/.test(String(value || "")) ? value : "/cards";
}
async function readBody(req) {
let size = 0;
const chunks = [];
for await (const chunk of req) {
size += chunk.length;
if (size > JSON_LIMIT) throw Object.assign(new Error("Requête trop volumineuse."), { status: 413, code: "BODY_TOO_LARGE" });
chunks.push(chunk);
}
if (!chunks.length) return {};
try {
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
} catch {
throw Object.assign(new Error("Corps JSON invalide."), { status: 400, code: "INVALID_JSON" });
}
}
function requestOrigin(req) {
const protocol = String(req.headers["x-forwarded-proto"] || "http").split(",")[0].trim();
return `${protocol}://${req.headers.host}`;
}
function routeMatch(pathname, pattern) {
const match = pathname.match(pattern);
return match ? match.slice(1).map(decodeURIComponent) : null;
}
function createRateLimiter(now) {
const buckets = new Map();
return (req, scope, limit = 60) => {
const key = `${String(req.headers["x-forwarded-for"] || req.socket?.remoteAddress || "unknown").split(",")[0]}:${scope}`;
const minute = Math.floor(now() / 60_000);
const current = buckets.get(key);
if (!current || current.minute !== minute) {
buckets.set(key, { minute, count: 1 });
return;
}
current.count += 1;
if (current.count > limit) throw Object.assign(new Error("Trop de tentatives. Réessayez dans quelques instants."), { status: 429, code: "RATE_LIMITED" });
};
}
export function createCardsApiHandler({
projectRoot = resolve("."),
env = process.env,
enabled = bool(env.CARDS_ENABLED, env.NODE_ENV !== "production"),
devAuth = bool(env.CARDS_DEV_AUTH, env.NODE_ENV !== "production"),
databasePath = env.CARDS_DB_PATH || join(projectRoot, ".local", "nebula-cards.sqlite"),
catalogPath = join(projectRoot, "website", "public", "data", "cards", "catalog.json"),
now = Date.now,
random,
fetchImpl = fetch,
devPerks = false,
apiRateLimit = 60
} = {}) {
let database = null;
let service = null;
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.");
// 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.");
const catalog = loadCardsCatalog(catalogPath);
database = new CardsDatabase(databasePath);
service = new CardsService({ database, catalog, now, random, devPerks });
}
const secureCookies = env.NODE_ENV === "production";
const adminIds = new Set(String(env.CARDS_ADMIN_DISCORD_IDS || "").split(",").map((item) => item.trim()).filter(Boolean));
const rateLimit = createRateLimiter(now);
const publicOrigin = (req) => env.CARDS_PUBLIC_ORIGIN || requestOrigin(req);
const discordCallbackUrl = (req) => env.DISCORD_REDIRECT_URI || `${publicOrigin(req)}/api/cards/auth/callback`;
// Échange le code contre le profil Discord ; toute erreur reste côté serveur et devient un retour lisible pour le joueur.
async function fetchDiscordUser(req, code) {
const signal = AbortSignal.timeout(DISCORD_TIMEOUT_MS);
const tokenResponse = await fetchImpl("https://discord.com/api/oauth2/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ client_id: env.DISCORD_CLIENT_ID, client_secret: env.DISCORD_CLIENT_SECRET, grant_type: "authorization_code", code, redirect_uri: discordCallbackUrl(req) }),
signal
});
if (!tokenResponse.ok) throw new Error(`Discord token exchange failed with status ${tokenResponse.status}.`);
const { access_token: accessToken } = await tokenResponse.json();
const userResponse = await fetchImpl("https://discord.com/api/users/@me", { headers: { Authorization: `Bearer ${accessToken}` }, signal });
if (!userResponse.ok) throw new Error(`Discord profile request failed with status ${userResponse.status}.`);
return userResponse.json();
}
async function handler(req, res) {
const url = new URL(req.url || "/", requestOrigin(req));
if (!url.pathname.startsWith("/api/cards")) return false;
try {
if (req.method === "GET" && url.pathname === "/api/cards/config") {
json(res, 200, {
enabled,
devAuth: enabled && devAuth,
discordConfigured: enabled && Boolean(env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET),
catalog: enabled ? publicCatalog(service.catalog) : null
});
return true;
}
rateLimit(req, "api", apiRateLimit);
if (!enabled) {
json(res, 503, { error: { code: "CARDS_DISABLED", message: "Sokko TCG est désactivé." } });
return true;
}
const cookies = parseCookies(req);
const session = service.getSession(cookies.sokkog_cards_session);
if (req.method === "GET" && url.pathname === "/api/cards/auth/discord") {
if (!env.DISCORD_CLIENT_ID || !env.DISCORD_CLIENT_SECRET) throw Object.assign(new Error("Connexion Discord non configurée."), { status: 503, code: "DISCORD_NOT_CONFIGURED" });
const state = randomBytes(24).toString("base64url");
const returnTo = cardsReturnPath(url.searchParams.get("returnTo"));
const target = new URL("https://discord.com/oauth2/authorize");
target.search = new URLSearchParams({ client_id: env.DISCORD_CLIENT_ID, response_type: "code", redirect_uri: discordCallbackUrl(req), scope: "identify", state }).toString();
redirect(res, target.toString(), [stateCookie(state, secureCookies), oauthReturnCookie(returnTo, secureCookies)]);
return true;
}
if (req.method === "GET" && url.pathname === "/api/cards/auth/callback") {
const state = url.searchParams.get("state");
const code = url.searchParams.get("code");
const returnTo = cardsReturnPath(cookies.sokkog_cards_oauth_return);
const clearedCookies = [stateCookie("", secureCookies, 0), oauthReturnCookie("", secureCookies, 0)];
// Cette route est une navigation : le joueur revient toujours sur le site, jamais sur une réponse JSON.
const fail = (reason) => redirect(res, `${publicOrigin(req)}/?cardsAuth=${reason}#${returnTo}`, clearedCookies);
if (!state || state !== cookies.sokkog_cards_oauth_state) {
fail("expired");
return true;
}
if (url.searchParams.get("error") === "access_denied") {
fail("denied");
return true;
}
try {
if (!code) throw new Error("Discord callback has no authorization code.");
const user = await fetchDiscordUser(req, code);
const avatarUrl = user.avatar ? `https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png?size=128` : "";
const player = service.upsertPlayer({ discordId: String(user.id), displayName: user.global_name || user.username, avatarUrl, isAdmin: adminIds.has(String(user.id)) });
const created = service.createSession(player.id);
redirect(res, `${publicOrigin(req)}/#${returnTo}`, [sessionCookie(created.token, secureCookies), ...clearedCookies]);
} catch (error) {
console.error(error);
fail("failed");
}
return true;
}
if (req.method === "POST" && url.pathname === "/api/cards/auth/dev") {
if (!devAuth) throw Object.assign(new Error("Connexion de développement indisponible."), { status: 404, code: "NOT_FOUND" });
rateLimit(req, "dev-auth", 10);
const player = service.upsertPlayer({ discordId: DEV_DISCORD_ID, displayName: "Version développement", isAdmin: true });
const created = service.createSession(player.id);
res.setHeader("Set-Cookie", sessionCookie(created.token, secureCookies));
json(res, 200, { player, csrfToken: created.csrfToken });
return true;
}
if (req.method === "GET" && url.pathname === "/api/cards/session") {
json(res, 200, session ? { authenticated: true, ...session } : { authenticated: false });
return true;
}
if (!session) throw Object.assign(new Error("Connectez-vous pour accéder à votre collection."), { status: 401, code: "AUTH_REQUIRED" });
if (req.method !== "GET") {
const origin = req.headers.origin;
if (origin && origin !== publicOrigin(req)) throw Object.assign(new Error("Origine de requête refusée."), { status: 403, code: "ORIGIN" });
if (req.headers["x-csrf-token"] !== session.csrfToken) throw Object.assign(new Error("Session expirée ou requête invalide."), { status: 403, code: "CSRF" });
}
if (req.method === "POST" && url.pathname === "/api/cards/auth/logout") {
service.deleteSession(cookies.sokkog_cards_session);
res.setHeader("Set-Cookie", sessionCookie("", secureCookies, 0));
json(res, 200, { ok: true });
return true;
}
if (req.method === "GET" && url.pathname === "/api/cards/state") {
json(res, 200, service.getState(session.player.id));
return true;
}
if (req.method === "GET" && url.pathname === "/api/cards/admin/dashboard") {
json(res, 200, service.getAdminDashboard(session.player.id));
return true;
}
if (req.method === "GET" && url.pathname === "/api/cards/admin/history") {
const before = url.searchParams.get("before");
if (before != null && !/^[1-9]\d{0,15}$/.test(before)) throw Object.assign(new Error("Curseur d'historique invalide."), { status: 400, code: "INVALID_CURSOR" });
json(res, 200, service.getAdminHistory(session.player.id, { before: before == null ? null : Number(before) }));
return true;
}
if (req.method === "POST" && url.pathname === "/api/cards/openings") {
const body = await readBody(req);
json(res, 201, service.openPack(session.player.id, body.collectionId, req.headers["idempotency-key"], { purchased: body.purchased === true }));
return true;
}
const giftOpen = routeMatch(url.pathname, /^\/api\/cards\/gift-packs\/([^/]+)\/open$/);
if (req.method === "POST" && giftOpen) {
json(res, 201, service.openGiftPack(session.player.id, giftOpen[0], req.headers["idempotency-key"]));
return true;
}
const openingComplete = routeMatch(url.pathname, /^\/api\/cards\/openings\/([^/]+)\/complete$/);
if (req.method === "POST" && openingComplete) {
json(res, 200, service.completeOpening(session.player.id, openingComplete[0]));
return true;
}
if (req.method === "PUT" && url.pathname === "/api/cards/favorites") {
const body = await readBody(req);
json(res, 200, service.setFavorite(session.player.id, body.editionId, Boolean(body.favorite)));
return true;
}
if (req.method === "GET" && url.pathname === "/api/cards/traders") {
json(res, 200, service.listTraders(session.player.id));
return true;
}
if (req.method === "POST" && url.pathname === "/api/cards/transfers") {
rateLimit(req, "transfer", 30);
json(res, 201, service.createTransfer(session.player.id, await readBody(req)));
return true;
}
for (const [action, method] of [["accept", "acceptTransfer"], ["decline", "declineTransfer"], ["cancel", "cancelTransfer"]]) {
const match = routeMatch(url.pathname, new RegExp(`^/api/cards/transfers/([^/]+)/${action}$`));
if (req.method === "POST" && match) {
json(res, 200, service[method](session.player.id, match[0]));
return true;
}
}
if (req.method === "POST" && url.pathname === "/api/cards/rewards/claim") {
rateLimit(req, "reward-code", 20);
json(res, 200, service.claimCampaign(session.player.id, (await readBody(req)).code));
return true;
}
if (req.method === "POST" && url.pathname === "/api/cards/admin/campaigns") {
json(res, 201, service.createCampaign(session.player.id, await readBody(req)));
return true;
}
const cardMythic = routeMatch(url.pathname, /^\/api\/cards\/admin\/catalog\/cards\/([^/]+)\/mythic$/);
if (req.method === "PUT" && cardMythic) {
const body = await readBody(req);
json(res, 200, service.setCardMythicConfig(session.player.id, cardMythic[0], { finishIds: body.finishIds, opening: { particleShapeId: body.opening?.particleShapeId ?? null, particlePaletteId: body.opening?.particlePaletteId ?? null } }));
return true;
}
if (req.method === "POST" && url.pathname === "/api/cards/recycle") {
json(res, 200, service.recycleDuplicates(session.player.id, { editionId: (await readBody(req)).editionId ?? null }));
return true;
}
if (req.method === "POST" && url.pathname === "/api/cards/shop/pack") {
json(res, 201, service.buyShopPack(session.player.id, req.headers["idempotency-key"]));
return true;
}
if (req.method === "POST" && url.pathname === "/api/cards/shop/openings") {
json(res, 200, service.buyOpening(session.player.id));
return true;
}
if (req.method === "PUT" && url.pathname === "/api/cards/admin/shop") {
const body = await readBody(req);
json(res, 200, service.updateShopSetting(session.player.id, { stardustValues: body.stardustValues, openingPrice: body.openingPrice, shopPackPrice: body.shopPackPrice, shopPackShare: body.shopPackShare }));
return true;
}
if (req.method === "PUT" && url.pathname === "/api/cards/admin/recharge") {
json(res, 200, service.updateRechargeSetting(session.player.id, { intervalMs: (await readBody(req)).intervalMs }));
return true;
}
const collectionState = routeMatch(url.pathname, /^\/api\/cards\/admin\/collections\/([^/]+)\/state$/);
if (req.method === "PUT" && collectionState) {
json(res, 200, service.setCollectionActive(session.player.id, collectionState[0], (await readBody(req)).active));
return true;
}
const dropRates = routeMatch(url.pathname, /^\/api\/cards\/admin\/collections\/([^/]+)\/drop-rates$/);
if (req.method === "PUT" && dropRates) {
json(res, 200, service.setDropRates(session.player.id, dropRates[0], (await readBody(req)).rarityWeights));
return true;
}
const collectionOpening = routeMatch(url.pathname, /^\/api\/cards\/admin\/catalog\/collections\/([^/]+)\/mythic-opening$/);
if (req.method === "PUT" && collectionOpening) {
const body = await readBody(req);
json(res, 200, service.setCollectionMythicOpening(session.player.id, collectionOpening[0], { particleShapeId: body.particleShapeId ?? null, particlePaletteId: body.particlePaletteId ?? null }));
return true;
}
const campaignDetail = routeMatch(url.pathname, /^\/api\/cards\/admin\/campaigns\/([^/]+)$/);
if (req.method === "GET" && campaignDetail) {
json(res, 200, service.campaignDetail(session.player.id, campaignDetail[0]));
return true;
}
const campaignExpiry = routeMatch(url.pathname, /^\/api\/cards\/admin\/campaigns\/([^/]+)\/expiry$/);
if (req.method === "PUT" && campaignExpiry) {
json(res, 200, service.extendCampaign(session.player.id, campaignExpiry[0], (await readBody(req)).expiresAt));
return true;
}
const revokeCampaign = routeMatch(url.pathname, /^\/api\/cards\/admin\/campaigns\/([^/]+)\/revoke$/);
if (req.method === "POST" && revokeCampaign) {
json(res, 200, service.revokeCampaign(session.player.id, revokeCampaign[0]));
return true;
}
json(res, 404, { error: { code: "NOT_FOUND", message: "Route Sokko TCG introuvable." } });
return true;
} catch (error) {
json(res, error.status || 500, { error: { code: error.code || "INTERNAL_ERROR", message: error.status ? error.message : "Une erreur serveur est survenue." } });
if (!error.status) console.error(error);
return true;
}
}
handler.close = () => database?.close();
handler.service = service;
return handler;
}

42
services/cards/backup.js Normal file
View file

@ -0,0 +1,42 @@
// Rôle : crée, vérifie et restaure des sauvegardes cohérentes de la base Sokko TCG.
import { copyFileSync, mkdirSync, renameSync, rmSync } from "node:fs";
import { dirname } from "node:path";
import { backup, DatabaseSync } from "node:sqlite";
export async function backupCardsDatabase(sourcePath, destinationPath) {
mkdirSync(dirname(destinationPath), { recursive: true });
const temporaryPath = `${destinationPath}.tmp`;
rmSync(temporaryPath, { force: true });
const source = new DatabaseSync(sourcePath, { readOnly: true });
try {
await backup(source, temporaryPath);
} finally {
source.close();
}
verifyCardsDatabase(temporaryPath);
renameSync(temporaryPath, destinationPath);
return destinationPath;
}
export function verifyCardsDatabase(path) {
const database = new DatabaseSync(path, { readOnly: true });
try {
const result = database.prepare("PRAGMA integrity_check").get();
if (result.integrity_check !== "ok") throw new Error(`SQLite integrity check failed: ${result.integrity_check}`);
database.prepare("SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1").get();
return true;
} finally {
database.close();
}
}
export function restoreCardsDatabase(backupPath, destinationPath) {
verifyCardsDatabase(backupPath);
mkdirSync(dirname(destinationPath), { recursive: true });
const temporaryPath = `${destinationPath}.restore`;
rmSync(temporaryPath, { force: true });
copyFileSync(backupPath, temporaryPath);
verifyCardsDatabase(temporaryPath);
renameSync(temporaryPath, destinationPath);
return destinationPath;
}

301
services/cards/catalog.js Normal file
View file

@ -0,0 +1,301 @@
// Rôle : charge et valide le catalogue public, ses finitions et effets Sokko TCG.
import { readFileSync } from "node:fs";
const RARITY_IDS = new Set(["common", "rare", "epic", "legendary", "mythic"]);
const PARTICLE_SHAPE_KINDS = new Set(["sparks", "snowflakes"]);
const PACK_CATEGORIES = new Set(["permanent", "event", "shop"]);
const PACK_BACK_SYMBOLS = new Set(["star", "rift", "orbit"]);
const COLOR_PATTERN = /^#[0-9a-f]{6}$/i;
// Formats d'une variation mythique : le premier est le format de référence ; `full-art` utilise `card.fullImage` sur toute la carte.
const STANDARD_FORMAT = "standard";
export const FULL_ART_FORMAT = "full-art";
// Palette d'ouverture spéciale : reprend les couleurs de la palette holographique de la variation.
export const MATCH_HOLO_PALETTE_ID = "match-holo";
const CARD_IMAGE_PATTERN = /^\/static\/img\/cards\/[a-z0-9-]+\/(?:common|rare|epic|legendary)\/[a-z0-9_]+\.webp$/;
const PACK_BACK_IMAGE_PATTERN = /^\/static\/img\/cards\/[a-z0-9-]+\/back\.webp$/;
function requireUnique(items, label) {
const ids = new Set();
for (const item of items) {
if (!item?.id || typeof item.id !== "string") throw new TypeError(`${label}: every item needs a string id.`);
if (ids.has(item.id)) throw new TypeError(`${label}: duplicate id ${item.id}.`);
ids.add(item.id);
}
return ids;
}
export function validateCardsCatalog(catalog) {
if (!catalog || catalog.version !== 1) throw new TypeError("Cards catalog version must be 1.");
for (const key of ["rarities", "effectPresets", "effectPalettes", "particleShapes", "particlePalettes", "particlePresets", "openingEffects", "finishes", "collections", "cards", "editions"]) {
if (!Array.isArray(catalog[key]) || !catalog[key].length) throw new TypeError(`Cards catalog ${key} must be a non-empty array.`);
}
const rarityIds = requireUnique(catalog.rarities, "rarities");
const effectPresetIds = requireUnique(catalog.effectPresets, "effectPresets");
const effectPaletteIds = requireUnique(catalog.effectPalettes, "effectPalettes");
const particleShapeIds = requireUnique(catalog.particleShapes, "particleShapes");
const particlePaletteIds = requireUnique(catalog.particlePalettes, "particlePalettes");
const particlePresetIds = requireUnique(catalog.particlePresets, "particlePresets");
requireUnique(catalog.openingEffects, "openingEffects");
const finishIds = requireUnique(catalog.finishes, "finishes");
const collectionIds = requireUnique(catalog.collections, "collections");
const cardIds = requireUnique(catalog.cards, "cards");
requireUnique(catalog.editions, "editions");
if ([...RARITY_IDS].some((id) => !rarityIds.has(id))) throw new TypeError("Cards catalog must declare all supported rarities.");
// Poids recommandés, proposés par l'administration pour réinitialiser les taux de tirage d'un paquet.
validateRarityWeights(Object.fromEntries(catalog.rarities.map((rarity) => [rarity.id, rarity.recommendedWeight])), rarityIds, "recommended weights");
for (const preset of catalog.effectPresets) {
if (!preset.label || preset.kind !== "holographic") throw new TypeError(`Invalid holographic effect preset ${preset.id}.`);
}
if (catalog.cardFormats?.[0]?.id !== STANDARD_FORMAT || catalog.cardFormats.some((format) => !format.label) || !catalog.cardFormats.some((format) => format.id === FULL_ART_FORMAT)) {
throw new TypeError("Cards catalog must declare the standard and full-art formats.");
}
for (const palette of catalog.effectPalettes) {
if (!palette.label || !Array.isArray(palette.colors) || palette.colors.length !== 7
|| new Set(palette.colors).size !== 7
|| palette.colors.some((color) => !COLOR_PATTERN.test(color)) || !COLOR_PATTERN.test(palette.highlight)) {
throw new TypeError(`Invalid effect palette ${palette.id}.`);
}
}
for (const shape of catalog.particleShapes) {
if (!shape.label || !PARTICLE_SHAPE_KINDS.has(shape.kind)) throw new TypeError(`Invalid particle shape ${shape.id}.`);
}
for (const palette of catalog.particlePalettes) {
if (!palette.label || !Array.isArray(palette.colors) || palette.colors.length < 1 || palette.colors.length > 7
|| palette.colors.some((color) => !COLOR_PATTERN.test(color))) {
throw new TypeError(`Invalid particle palette ${palette.id}.`);
}
}
for (const preset of catalog.particlePresets) {
if (!preset.label || !particleShapeIds.has(preset.shapeId) || !particlePaletteIds.has(preset.paletteId)
|| !Number.isInteger(preset.count) || preset.count < 1 || preset.count > 64) {
throw new TypeError(`Invalid particle preset ${preset.id}.`);
}
}
// Un seul effet d'ouverture par rareté ; les variantes mythiques passent par les réglages d'ouverture.
const openingEffectRarities = new Set();
for (const effect of catalog.openingEffects) {
if (!effect.label || !RARITY_IDS.has(effect.rarity) || effect.rarity === "common"
|| !Array.isArray(effect.auraColors) || effect.auraColors.length < 1 || effect.auraColors.length > 7
|| effect.auraColors.some((color) => !COLOR_PATTERN.test(color))
|| Object.hasOwn(effect, "collectionId")
|| !Number.isInteger(effect.auraDurationMs) || effect.auraDurationMs < 0 || effect.auraDurationMs > 2_000
|| !Number.isInteger(effect.particleDurationMs) || effect.particleDurationMs < 0 || effect.particleDurationMs > 2_000) {
throw new TypeError(`Invalid opening effect ${effect.id}.`);
}
if (effect.particlePresetId != null && !particlePresetIds.has(effect.particlePresetId)) throw new TypeError(`Opening effect ${effect.id} needs a known particle preset.`);
if (effect.particlePresetId == null && effect.particleDurationMs !== 0) throw new TypeError(`Opening effect ${effect.id} cannot animate missing particles.`);
if (openingEffectRarities.has(effect.rarity)) throw new TypeError(`Duplicate opening effect for rarity ${effect.rarity}.`);
openingEffectRarities.add(effect.rarity);
}
for (const rarity of ["rare", "epic", "legendary", "mythic"]) {
if (!openingEffectRarities.has(rarity)) throw new TypeError(`Cards catalog needs an opening effect for rarity ${rarity}.`);
}
const defaultMythicOpening = catalog.openingEffects.find((effect) => effect.rarity === "mythic");
if (!particlePresetIds.has(defaultMythicOpening.particlePresetId)) throw new TypeError("The default mythic opening effect needs particles.");
for (const finish of catalog.finishes) {
if (!finish.label
|| !Object.hasOwn(finish, "effectPresetId")
|| !Object.hasOwn(finish, "paletteId")) {
throw new TypeError(`Invalid finish ${finish.id}.`);
}
const hasEffect = finish.effectPresetId != null;
if (hasEffect && !effectPresetIds.has(finish.effectPresetId)) throw new TypeError(`Finish ${finish.id} needs a known holographic effect.`);
if (hasEffect && !effectPaletteIds.has(finish.paletteId)) throw new TypeError(`Holographic finish ${finish.id} needs a known palette.`);
if (!hasEffect && finish.paletteId != null) throw new TypeError(`Finish ${finish.id} cannot use a palette without a holographic effect.`);
}
for (const collection of catalog.collections) {
if (!collection.name || !collection.systemName || !collection.description || (collection.active != null && typeof collection.active !== "boolean") || typeof collection.promotional !== "boolean") {
throw new TypeError(`Invalid collection ${collection.id}.`);
}
if (!PACK_CATEGORIES.has(collection.packCategory)
|| !PACK_BACK_SYMBOLS.has(collection.back?.symbol)
|| !PACK_BACK_IMAGE_PATTERN.test(collection.back?.image)
|| !COLOR_PATTERN.test(collection.back?.primary)
|| !COLOR_PATTERN.test(collection.back?.secondary)) {
throw new TypeError(`Invalid pack presentation for collection ${collection.id}.`);
}
}
for (const card of catalog.cards) {
if (!collectionIds.has(card.collectionId)) throw new TypeError(`Unknown collection for card ${card.id}.`);
if (!card.name || card.name.length > 40) throw new TypeError(`Card ${card.id} name must contain 1 to 40 characters.`);
if (!card.description || card.description.length > 200) throw new TypeError(`Card ${card.id} description must contain 1 to 200 characters.`);
if (card.image != null && !CARD_IMAGE_PATTERN.test(card.image)) throw new TypeError(`Card ${card.id} image must use a canonical WebP path.`);
if (card.fullImage != null && !CARD_IMAGE_PATTERN.test(card.fullImage)) throw new TypeError(`Card ${card.id} full image must use a canonical WebP path.`);
}
for (const edition of catalog.editions) {
if (!cardIds.has(edition.cardId)) throw new TypeError(`Unknown card for edition ${edition.id}.`);
if (!RARITY_IDS.has(edition.rarity)) throw new TypeError(`Unknown rarity for edition ${edition.id}.`);
if (!Array.isArray(edition.finishIds) || edition.finishIds.some((id) => !finishIds.has(id))) throw new TypeError(`Unknown finish for edition ${edition.id}.`);
if (edition.retired != null && typeof edition.retired !== "boolean") throw new TypeError(`Edition ${edition.id} retired flag must be a boolean.`);
if (edition.promotional && edition.legendaryEditionId) throw new TypeError(`Promotional edition ${edition.id} cannot require a legendary parent.`);
if (edition.rarity === "mythic" && !edition.promotional) {
const parent = catalog.editions.find((candidate) => candidate.id === edition.legendaryEditionId);
if (!parent || parent.cardId !== edition.cardId || parent.rarity !== "legendary") throw new TypeError(`Mythic edition ${edition.id} needs a legendary edition of the same card.`);
}
}
if (catalog.mythicOpeningSettings != null) {
if (!Array.isArray(catalog.mythicOpeningSettings)) throw new TypeError("Cards catalog mythicOpeningSettings must be an array.");
const settingKeys = new Set();
for (const setting of catalog.mythicOpeningSettings) {
const targets = setting?.scope === "collection" ? collectionIds : setting?.scope === "card" ? cardIds : null;
if (!targets?.has(setting.targetId)
|| (setting.particleShapeId != null && !particleShapeIds.has(setting.particleShapeId))
|| (setting.particlePaletteId != null && setting.particlePaletteId !== MATCH_HOLO_PALETTE_ID && !particlePaletteIds.has(setting.particlePaletteId))) {
throw new TypeError(`Invalid mythic opening setting ${setting?.scope}:${setting?.targetId}.`);
}
const key = `${setting.scope}:${setting.targetId}`;
if (settingKeys.has(key)) throw new TypeError(`Duplicate mythic opening setting ${key}.`);
settingKeys.add(key);
}
}
// Les taux de tirage n'existent que dans le catalogue publié (ils viennent de la base).
for (const collection of catalog.collections) {
if (collection.dropWeights != null) validateRarityWeights(collection.dropWeights, rarityIds, collection.id);
}
return catalog;
}
export const MAX_RARITY_WEIGHT = 1_000_000;
// Poids entiers, positifs ou nuls, une entrée par rareté connue, total strictement positif.
export function validateRarityWeights(weights, rarityIds, label = "drop weights") {
if (!weights || typeof weights !== "object" || Array.isArray(weights)) throw new TypeError(`Invalid drop weights in ${label}.`);
const entries = Object.entries(weights);
if (entries.length !== rarityIds.size || entries.some(([rarity, weight]) => !rarityIds.has(rarity) || !Number.isInteger(weight) || weight < 0 || weight > MAX_RARITY_WEIGHT)) {
throw new TypeError(`Invalid drop weight in ${label}.`);
}
if (entries.reduce((sum, [, weight]) => sum + weight, 0) <= 0) throw new TypeError(`Drop weights in ${label} must have a positive total.`);
return weights;
}
export const STANDARD_FINISH_ID = "standard";
// Les finitions ne sont pas déclarées : « standard » plus une finition par combinaison effet holographique × palette.
export function withGeneratedFinishes(catalog) {
const finishes = [{ id: STANDARD_FINISH_ID, label: "Standard", effectPresetId: null, paletteId: null, formatId: STANDARD_FORMAT }];
for (const format of catalog.cardFormats || []) {
for (const effect of catalog.effectPresets || []) {
for (const palette of catalog.effectPalettes || []) {
// Le format de référence garde des identifiants courts ; les autres sont préfixés par leur format.
const standard = format.id === STANDARD_FORMAT;
finishes.push({
id: `${standard ? "" : `${format.id}-`}${effect.id}-${palette.id}`,
label: `${standard ? "" : `${format.label} · `}${effect.label} — ${palette.label}`,
effectPresetId: effect.id,
paletteId: palette.id,
formatId: format.id
});
}
}
}
return { ...catalog, finishes };
}
// catalog.json ne déclare ni finitions (générées) ni contenu géré en base depuis l'administration :
// variations mythiques, activation des paquets et taux de tirage.
export function assertVersionedCatalogScope(catalog) {
if (catalog.finishes) throw new TypeError("Finishes are generated from effect presets and palettes: remove finishes from catalog.json.");
if (catalog.dropTables) throw new TypeError("Drop rates are managed from the admin database: remove dropTables from catalog.json.");
const withRates = catalog.collections?.find((collection) => Object.hasOwn(collection, "dropWeights"));
if (withRates) throw new TypeError(`Collection ${withRates.id} drop rates are managed from the admin database: remove dropWeights from catalog.json.`);
const withState = catalog.collections?.find((collection) => Object.hasOwn(collection, "active"));
if (withState) throw new TypeError(`Collection ${withState.id} availability is managed from the admin database: remove active from catalog.json.`);
const mythic = catalog.editions?.find((edition) => edition.rarity === "mythic" && !edition.promotional);
if (mythic) throw new TypeError(`Mythic edition ${mythic.id} must be managed from the admin database, not catalog.json.`);
return catalog;
}
// Prépare le catalogue versionné tel qu'il est lu depuis catalog.json.
export function prepareVersionedCatalog(raw) {
return validateCardsCatalog(withGeneratedFinishes(assertVersionedCatalogScope(raw)));
}
export function loadCardsCatalog(path) {
return prepareVersionedCatalog(JSON.parse(readFileSync(path, "utf8")));
}
export function createCatalogIndex(catalog) {
return {
collections: new Map(catalog.collections.map((item) => [item.id, item])),
cards: new Map(catalog.cards.map((item) => [item.id, item])),
editions: new Map(catalog.editions.map((item) => [item.id, item])),
finishes: new Map(catalog.finishes.map((item) => [item.id, item])),
effectPresets: new Map(catalog.effectPresets.map((item) => [item.id, item])),
effectPalettes: new Map(catalog.effectPalettes.map((item) => [item.id, item])),
particleShapes: new Map(catalog.particleShapes.map((item) => [item.id, item])),
particlePalettes: new Map(catalog.particlePalettes.map((item) => [item.id, item])),
particlePresets: new Map(catalog.particlePresets.map((item) => [item.id, item])),
openingEffects: new Map(catalog.openingEffects.map((item) => [item.id, item]))
};
}
export function isDrawableEdition(edition) {
return !edition.promotional && !edition.retired;
}
export function holographicFinishIds(catalog) {
return new Set(catalog.finishes.filter((finish) => finish.effectPresetId != null).map((finish) => finish.id));
}
export function legendaryParentEdition(catalog, cardId) {
return catalog.editions.find((edition) => edition.cardId === cardId && edition.rarity === "legendary" && !edition.promotional) || null;
}
export function mythicEditionId(cardId, finishId) {
return `${cardId}-${finishId}`;
}
// Construit le catalogue publié : catalogue versionné + variations mythiques et réglages d'ouverture enregistrés en base.
// `variations` : [{ editionId, cardId, finishId, status: "active" | "retired" }]
// `openingSettings` : [{ scope: "collection" | "card", targetId, particleShapeId | null, particlePaletteId | null }]
// `collectionStates` : [{ collectionId, active }] ; une collection sans état est inactive.
// `dropRates` : [{ collectionId, rarityWeights }] ; publiés sur chaque collection dans `dropWeights`.
export function buildPublishedCatalog(versionedCatalog, { variations = [], openingSettings = [], collectionStates = [], dropRates = [] } = {}) {
const catalog = structuredClone(versionedCatalog);
const states = new Map(collectionStates.map((state) => [state.collectionId, Boolean(state.active)]));
const rates = new Map(dropRates.map((rate) => [rate.collectionId, rate.rarityWeights]));
catalog.collections = catalog.collections.map((collection) => {
const dropWeights = rates.get(collection.id);
return { ...collection, active: states.get(collection.id) ?? false, ...(dropWeights ? { dropWeights: { ...dropWeights } } : {}) };
});
for (const collection of catalog.collections.filter((item) => item.active)) {
if (!collection.dropWeights) throw new TypeError(`Active collection ${collection.id} needs drop rates.`);
}
const holographic = holographicFinishIds(catalog);
const knownIds = new Set(catalog.editions.map((edition) => edition.id));
const mythics = variations.map((variation) => {
const parent = legendaryParentEdition(catalog, variation.cardId);
if (!parent || !holographic.has(variation.finishId) || variation.editionId !== mythicEditionId(variation.cardId, variation.finishId) || knownIds.has(variation.editionId)) {
throw new TypeError(`Mythic variation ${variation.editionId} needs a legendary card and a holographic finish.`);
}
knownIds.add(variation.editionId);
return {
id: variation.editionId,
cardId: variation.cardId,
rarity: "mythic",
finishIds: [variation.finishId],
promotional: false,
legendaryEditionId: parent.id,
...(variation.status === "retired" ? { retired: true } : {})
};
});
// Chaque variation suit sa carte légendaire, dans l'ordre des finitions.
const finishOrder = new Map(catalog.finishes.map((finish, index) => [finish.id, index]));
mythics.sort((left, right) => finishOrder.get(left.finishIds[0]) - finishOrder.get(right.finishIds[0]));
catalog.editions = catalog.editions.flatMap((edition) => edition.rarity === "legendary" && !edition.promotional
? [edition, ...mythics.filter((mythic) => mythic.legendaryEditionId === edition.id)]
: [edition]);
catalog.mythicOpeningSettings = openingSettings
.map(({ scope, targetId, particleShapeId = null, particlePaletteId = null }) => ({ scope, targetId, particleShapeId, particlePaletteId }))
.filter((setting) => setting.particleShapeId || setting.particlePaletteId);
return validateCardsCatalog(catalog);
}
export function publicCatalog(catalog) {
return JSON.parse(JSON.stringify(catalog));
}

229
services/cards/database.js Normal file
View file

@ -0,0 +1,229 @@
// Rôle : encapsule la base SQLite et les migrations du mini-jeu Sokko TCG.
import { mkdirSync } from "node:fs";
import { dirname } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES, INITIAL_RECHARGE_SETTING, INITIAL_SHOP_SETTING } from "./admin-seed.js";
const MIGRATIONS = [
`
CREATE TABLE players (
id TEXT PRIMARY KEY,
discord_id TEXT NOT NULL UNIQUE,
display_name TEXT NOT NULL,
avatar_url TEXT NOT NULL DEFAULT '',
is_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_admin IN (0, 1)),
created_at INTEGER NOT NULL,
openings_balance INTEGER NOT NULL DEFAULT 1 CHECK (openings_balance BETWEEN 0 AND 5),
recharge_anchor INTEGER,
stardust INTEGER NOT NULL DEFAULT 0 CHECK (stardust >= 0),
purchased_openings INTEGER NOT NULL DEFAULT 0 CHECK (purchased_openings >= 0)
) STRICT;
CREATE TABLE sessions (
token_hash TEXT PRIMARY KEY,
player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE,
csrf_token TEXT NOT NULL,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
) STRICT;
CREATE INDEX sessions_player_idx ON sessions(player_id);
CREATE TABLE openings (
id TEXT PRIMARY KEY,
player_id TEXT NOT NULL REFERENCES players(id),
collection_id TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('pending', 'completed')),
created_at INTEGER NOT NULL,
completed_at INTEGER
) STRICT;
CREATE INDEX openings_player_idx ON openings(player_id, created_at DESC);
-- Collection : une ligne par carte possédée, avec sa quantité. Un joueur garde toujours au moins un exemplaire de
-- chaque carte obtenue (seuls les doublons s'échangent, se donnent ou se recyclent) : une ligne n'est jamais supprimée.
CREATE TABLE collection_cards (
player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE,
edition_id TEXT NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity >= 1),
acquired_at INTEGER NOT NULL,
PRIMARY KEY (player_id, edition_id)
) STRICT;
CREATE TABLE opening_cards (
opening_id TEXT NOT NULL REFERENCES openings(id) ON DELETE CASCADE,
position INTEGER NOT NULL CHECK (position BETWEEN 0 AND 2),
edition_id TEXT NOT NULL,
was_new_card INTEGER NOT NULL CHECK (was_new_card IN (0, 1)),
was_new_edition INTEGER NOT NULL CHECK (was_new_edition IN (0, 1)),
quantity_before INTEGER NOT NULL,
PRIMARY KEY (opening_id, position)
) STRICT;
CREATE TABLE favorites (
player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE,
edition_id TEXT NOT NULL,
PRIMARY KEY (player_id, edition_id)
) STRICT;
CREATE TABLE transfers (
id TEXT PRIMARY KEY,
code TEXT NOT NULL UNIQUE,
type TEXT NOT NULL CHECK (type IN ('trade', 'gift')),
initiator_id TEXT NOT NULL REFERENCES players(id),
recipient_id TEXT REFERENCES players(id),
offered_edition_id TEXT NOT NULL,
requested_edition_id TEXT,
initiator_confirmed INTEGER NOT NULL DEFAULT 0 CHECK (initiator_confirmed IN (0, 1)),
recipient_confirmed INTEGER NOT NULL DEFAULT 0 CHECK (recipient_confirmed IN (0, 1)),
status TEXT NOT NULL CHECK (status IN ('open', 'joined', 'completed', 'cancelled', 'expired')),
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
completed_at INTEGER
) STRICT;
CREATE INDEX transfers_participants_idx ON transfers(initiator_id, recipient_id, status);
-- Un transfert en cours (open, joined) réserve un doublon de chaque carte engagée.
CREATE TABLE campaigns (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
code TEXT NOT NULL UNIQUE,
reward_json TEXT NOT NULL,
max_claims INTEGER CHECK (max_claims IS NULL OR max_claims > 0),
created_by TEXT NOT NULL REFERENCES players(id),
created_at INTEGER NOT NULL,
expires_at INTEGER,
revoked_at INTEGER
) STRICT;
CREATE TABLE campaign_claims (
id TEXT PRIMARY KEY,
campaign_id TEXT NOT NULL REFERENCES campaigns(id) ON DELETE CASCADE,
player_id TEXT NOT NULL REFERENCES players(id),
claimed_at INTEGER NOT NULL,
UNIQUE (campaign_id, player_id)
) STRICT;
CREATE TABLE gift_packs (
id TEXT PRIMARY KEY,
player_id TEXT NOT NULL REFERENCES players(id),
campaign_id TEXT NOT NULL REFERENCES campaigns(id),
collection_id TEXT NOT NULL,
options_json TEXT NOT NULL,
created_at INTEGER NOT NULL,
opening_id TEXT REFERENCES openings(id),
opened_at INTEGER
) STRICT;
CREATE INDEX gift_packs_player_idx ON gift_packs(player_id, opened_at);
CREATE TABLE idempotency (
player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE,
scope TEXT NOT NULL,
request_key TEXT NOT NULL,
response_json TEXT NOT NULL,
created_at INTEGER NOT NULL,
PRIMARY KEY (player_id, scope, request_key)
) STRICT;
CREATE TABLE audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
player_id TEXT REFERENCES players(id),
event_type TEXT NOT NULL,
entity_id TEXT NOT NULL,
details_json TEXT NOT NULL,
created_at INTEGER NOT NULL
) STRICT;
CREATE INDEX audit_player_idx ON audit_log(player_id, created_at DESC);
`,
// Contenu géré depuis l'administration : variations mythiques, réglages d'ouverture, état des paquets,
// tables de tirage, recharge des ouvertures et boutique (barème de poussière d'étoiles, prix d'une ouverture). Ces données n'existent qu'ici ; la migration insère le contenu de départ (admin-seed.js).
`
CREATE INDEX collection_cards_edition_idx ON collection_cards(edition_id);
CREATE INDEX opening_cards_edition_idx ON opening_cards(edition_id);
CREATE TABLE mythic_variations (
edition_id TEXT PRIMARY KEY,
card_id TEXT NOT NULL,
finish_id TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('active', 'retired')),
updated_at INTEGER NOT NULL,
updated_by TEXT REFERENCES players(id)
) STRICT;
CREATE TABLE mythic_opening_settings (
scope TEXT NOT NULL CHECK (scope IN ('collection', 'card')),
target_id TEXT NOT NULL,
particle_shape_id TEXT,
particle_palette_id TEXT,
updated_at INTEGER NOT NULL,
updated_by TEXT REFERENCES players(id),
PRIMARY KEY (scope, target_id)
) STRICT;
CREATE TABLE collection_states (
collection_id TEXT PRIMARY KEY,
active INTEGER NOT NULL CHECK (active IN (0, 1)),
updated_at INTEGER NOT NULL,
updated_by TEXT REFERENCES players(id)
) STRICT;
CREATE TABLE drop_rates (
collection_id TEXT PRIMARY KEY,
rarity_weights_json TEXT NOT NULL,
updated_at INTEGER NOT NULL,
updated_by TEXT REFERENCES players(id)
) STRICT;
CREATE TABLE recharge_settings (
id INTEGER PRIMARY KEY CHECK (id = 1),
interval_ms INTEGER NOT NULL CHECK (interval_ms >= 60000),
max_openings INTEGER NOT NULL CHECK (max_openings BETWEEN 1 AND 5),
updated_at INTEGER NOT NULL,
updated_by TEXT REFERENCES players(id)
) STRICT;
CREATE TABLE shop_settings (
id INTEGER PRIMARY KEY CHECK (id = 1),
stardust_values_json TEXT NOT NULL,
opening_price INTEGER NOT NULL CHECK (opening_price > 0),
updated_at INTEGER NOT NULL,
updated_by TEXT REFERENCES players(id)
) STRICT;
INSERT INTO shop_settings(id, stardust_values_json, opening_price, updated_at, updated_by) VALUES (1, '${JSON.stringify(INITIAL_SHOP_SETTING.stardustValues)}', ${INITIAL_SHOP_SETTING.openingPrice}, 0, NULL);
INSERT INTO recharge_settings(id, interval_ms, max_openings, updated_at, updated_by) VALUES (1, ${INITIAL_RECHARGE_SETTING.intervalMs}, ${INITIAL_RECHARGE_SETTING.maxOpenings}, 0, NULL);
${INITIAL_COLLECTION_STATES.map(({ collectionId, active }) => `INSERT INTO collection_states(collection_id, active, updated_at, updated_by) VALUES ('${collectionId}', ${active ? 1 : 0}, 0, NULL);`).join("\n ")}
${INITIAL_DROP_RATES.map(({ collectionId, rarityWeights }) => `INSERT INTO drop_rates(collection_id, rarity_weights_json, updated_at, updated_by) VALUES ('${collectionId}', '${JSON.stringify(rarityWeights)}', 0, NULL);`).join("\n ")}
`,
// Propositions directes : plus de code à rejoindre. Les transferts en cours de l'ancien système sont annulés,
// ce qui libère leurs doublons réservés. Les anciens statuts et colonnes restent pour relire l'historique.
`
ALTER TABLE transfers ADD COLUMN declined INTEGER NOT NULL DEFAULT 0 CHECK (declined IN (0, 1));
UPDATE transfers SET status = 'cancelled' WHERE status IN ('open', 'joined');
`,
// Paquet de la Boutique : la collection stardust s'ouvre avec les poids recommandés ; prix et part de ses cartes se règlent dans l'administration.
`
ALTER TABLE shop_settings ADD COLUMN shop_pack_price INTEGER NOT NULL DEFAULT 60 CHECK (shop_pack_price >= 1);
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 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);
`
];
export class CardsDatabase {
constructor(path) {
if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true });
this.db = new DatabaseSync(path);
this.db.exec("PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;");
this.migrate();
}
migrate() {
this.db.exec("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at INTEGER NOT NULL) STRICT;");
const applied = new Set(this.db.prepare("SELECT version FROM schema_migrations").all().map((row) => row.version));
MIGRATIONS.forEach((sql, index) => {
const version = index + 1;
if (applied.has(version)) return;
this.transaction(() => {
this.db.exec(sql);
this.db.prepare("INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)").run(version, Date.now());
});
});
}
transaction(callback) {
this.db.exec("BEGIN IMMEDIATE");
try {
const result = callback();
this.db.exec("COMMIT");
return result;
} catch (error) {
this.db.exec("ROLLBACK");
throw error;
}
}
close() {
this.db.close();
}
}

View file

@ -0,0 +1,125 @@
// Rôle : calcule la recharge des ouvertures et sélectionne les éditions d'un paquet.
import { randomInt } from "node:crypto";
import { isDrawableEdition } from "./catalog.js";
// Réglage de recharge unique (table recharge_settings) : un délai entre deux ouvertures et une réserve maximale.
// Un changement de délai s'applique aussi au temps déjà écoulé depuis la dernière recharge du joueur.
export const MIN_RECHARGE_INTERVAL_MS = 60_000;
export const MAX_RECHARGE_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000;
function checkedSetting({ intervalMs, maxOpenings }) {
if (!Number.isInteger(intervalMs) || intervalMs < 1 || !Number.isInteger(maxOpenings) || maxOpenings < 1) throw new TypeError("Recharge setting is invalid.");
return { intervalMs, maxOpenings };
}
export function calculateRecharge(player, now, setting) {
const { intervalMs, maxOpenings } = checkedSetting(setting);
const balance = Math.max(0, Number(player.openingsBalance) || 0);
if (balance >= maxOpenings) return { openingsBalance: maxOpenings, rechargeAnchor: null, nextOpeningAt: null };
const anchor = player.rechargeAnchor == null ? now : Number(player.rechargeAnchor);
const earned = Math.max(0, Math.floor((now - anchor) / intervalMs));
const openingsBalance = Math.min(maxOpenings, balance + earned);
if (openingsBalance >= maxOpenings) return { openingsBalance: maxOpenings, rechargeAnchor: null, nextOpeningAt: null };
const rechargeAnchor = anchor + earned * intervalMs;
return { openingsBalance, rechargeAnchor, nextOpeningAt: rechargeAnchor + intervalMs };
}
// Réserve figée juste sous le maximum, pour le compte de développement : le minuteur continue de tourner et repart à chaque échéance.
export function pinnedRecharge(player, now, setting) {
const { intervalMs, maxOpenings } = checkedSetting(setting);
const anchor = player.rechargeAnchor == null ? now : Number(player.rechargeAnchor);
const rechargeAnchor = anchor + Math.max(0, Math.floor((now - anchor) / intervalMs)) * intervalMs;
return { openingsBalance: Math.max(1, maxOpenings - 1), rechargeAnchor, nextOpeningAt: rechargeAnchor + intervalMs };
}
export function spendOpening(recharge, now, setting) {
const { intervalMs, maxOpenings } = checkedSetting(setting);
if (recharge.openingsBalance < 1) throw Object.assign(new Error("Aucune ouverture disponible."), { status: 409, code: "NO_OPENING" });
const wasFull = recharge.openingsBalance >= maxOpenings || recharge.rechargeAnchor == null;
const rechargeAnchor = wasFull ? now : recharge.rechargeAnchor;
return { openingsBalance: recharge.openingsBalance - 1, rechargeAnchor, nextOpeningAt: rechargeAnchor + intervalMs };
}
function weightedChoice(entries, random = (max) => randomInt(max)) {
const total = entries.reduce((sum, [, weight]) => sum + weight, 0);
if (total <= 0) throw new TypeError("A weighted choice needs a positive total.");
let cursor = random(total);
for (const [value, weight] of entries) {
cursor -= weight;
if (cursor < 0) return value;
}
return entries.at(-1)[0];
}
const pick = (random, max) => (random || ((limit) => randomInt(limit)))(max);
// Paquet de la Boutique : les cartes de toutes les autres collections actives, plus les légendaires et mythiques de sa propre collection.
// Quand une de ces deux raretés sort, `share` % des tirages reviennent aux cartes de sa collection, quel que soit leur nombre.
const FEATURED_RARITIES = new Set(["legendary", "mythic"]);
export function drawShopPack(catalog, collectionId, random, share) {
const collection = catalog.collections.find((item) => item.id === collectionId && item.active);
if (!collection) throw Object.assign(new Error("Ce paquet n'est pas disponible."), { status: 404, code: "COLLECTION_UNAVAILABLE" });
if (!collection.dropWeights) throw new TypeError(`No drop rates for ${collectionId}.`);
const sourceOf = new Map(catalog.cards.map((card) => [card.id, card.collectionId]));
const activeIds = new Set(catalog.collections.filter((item) => item.active && item.packCategory !== "shop").map((item) => item.id));
const drawableEditions = catalog.editions.filter(isDrawableEdition);
const others = drawableEditions.filter((edition) => activeIds.has(sourceOf.get(edition.cardId)));
const featured = drawableEditions.filter((edition) => sourceOf.get(edition.cardId) === collectionId && FEATURED_RARITIES.has(edition.rarity));
const ofRarity = (editions, rarity) => editions.filter((edition) => edition.rarity === rarity);
const rarityEntries = Object.entries(collection.dropWeights).filter(([rarity, weight]) => weight > 0 && (ofRarity(others, rarity).length || ofRarity(featured, rarity).length));
if (!rarityEntries.length) throw Object.assign(new Error("Aucune carte ne peut être tirée avec ces taux."), { status: 409, code: "NOTHING_DRAWABLE" });
return Array.from({ length: 3 }, () => {
const rarity = weightedChoice(rarityEntries, random);
const featuredCandidates = ofRarity(featured, rarity);
const otherCandidates = ofRarity(others, rarity);
const useFeatured = featuredCandidates.length > 0 && (!otherCandidates.length || pick(random, 100) < share);
const candidates = useFeatured ? featuredCandidates : otherCandidates;
return candidates[pick(random, candidates.length)].id;
});
}
// Tire les trois cartes d'un paquet. Options des paquets offerts :
// - `weights` : poids personnalisés (sinon ceux de la collection) ;
// - `guarantee` : { type: "rarity", rarity, count } (au moins `count` cartes de cette rareté ou mieux)
// ou { type: "edition", editionId } (cette variation figure dans le paquet) ;
// - `requireActive` : un paquet offert s'ouvre même si la collection est fermée.
export function drawPack(catalog, collectionId, random, { weights = null, guarantee = null, requireActive = true } = {}) {
const collection = catalog.collections.find((item) => item.id === collectionId && (item.active || !requireActive));
if (!collection) throw Object.assign(new Error("Cette collection n'est pas disponible."), { status: 404, code: "COLLECTION_UNAVAILABLE" });
const rarityWeights = weights || collection.dropWeights;
if (!rarityWeights) throw new TypeError(`No drop rates for ${collectionId}.`);
const cardIds = new Set(catalog.cards.filter((card) => card.collectionId === collectionId).map((card) => card.id));
const editions = catalog.editions.filter((edition) => cardIds.has(edition.cardId) && isDrawableEdition(edition));
const drawable = (rarity) => editions.some((edition) => edition.rarity === rarity);
const rarityEntries = Object.entries(rarityWeights).filter(([rarity, weight]) => weight > 0 && drawable(rarity));
if (!rarityEntries.length) throw Object.assign(new Error("Aucune carte ne peut être tirée avec ces taux."), { status: 409, code: "NOTHING_DRAWABLE" });
const rank = new Map(catalog.rarities.map((rarity, index) => [rarity.id, index]));
const slots = Array.from({ length: 3 }, () => weightedChoice(rarityEntries, random));
if (guarantee?.type === "rarity") {
const eligible = catalog.rarities.filter((rarity) => rank.get(rarity.id) >= rank.get(guarantee.rarity) && drawable(rarity.id)).map((rarity) => rarity.id);
if (!eligible.length) throw Object.assign(new Error("Aucune carte de cette rareté ou mieux ne peut être tirée."), { status: 409, code: "GUARANTEE_UNAVAILABLE" });
const weighted = eligible.map((rarity) => [rarity, rarityWeights[rarity] || 0]).filter(([, weight]) => weight > 0);
let missing = guarantee.count - slots.filter((rarity) => rank.get(rarity) >= rank.get(guarantee.rarity)).length;
// On améliore d'abord les cartes les plus communes.
const order = slots.map((rarity, index) => index).sort((left, right) => rank.get(slots[left]) - rank.get(slots[right]));
for (const index of order) {
if (missing <= 0) break;
if (rank.get(slots[index]) >= rank.get(guarantee.rarity)) continue;
slots[index] = weighted.length ? weightedChoice(weighted, random) : eligible[0];
missing -= 1;
}
}
const picked = slots.map((rarity) => {
const candidates = editions.filter((edition) => edition.rarity === rarity);
return candidates[pick(random, candidates.length)];
});
if (guarantee?.type === "edition" && !picked.some((edition) => edition.id === guarantee.editionId)) {
const guaranteed = catalog.editions.find((edition) => edition.id === guarantee.editionId && cardIds.has(edition.cardId));
if (!guaranteed) throw Object.assign(new Error("La carte garantie n'appartient pas à cette collection."), { status: 409, code: "GUARANTEE_UNAVAILABLE" });
const lowest = picked.reduce((best, edition, index) => (rank.get(edition.rarity) < rank.get(picked[best].rarity) ? index : best), 0);
picked[lowest] = guaranteed;
}
return picked.map((edition) => edition.id);
}

69
services/cards/rewards.js Normal file
View file

@ -0,0 +1,69 @@
// Rôle : valide et normalise les récompenses distribuées par codes (des cartes et des paquets avec leurs options).
import { isDrawableEdition, validateRarityWeights } from "./catalog.js";
function invalid(message) {
throw Object.assign(new Error(message), { status: 400, code: "REWARD_INVALID" });
}
export const MAX_REWARD_ITEMS = 50;
export const MAX_ITEM_QUANTITY = 10;
// Une récompense est une liste d'éléments : { items: [élément, …] }, au plus 50 éléments.
// Élément « carte » : { type: "card", editionId, quantity: 1 }, chaque carte au plus une fois
// Élément « paquet » : { type: "pack", collectionId, rarityWeights | null, guarantee | null, quantity }
// guarantee : { type: "rarity", rarity, count (1 à 3) } ou { type: "edition", editionId }
export function normalizeReward(reward, catalog) {
const items = reward?.items;
if (!Array.isArray(items) || !items.length) invalid("Ajoutez au moins une carte ou un paquet à offrir.");
if (items.length > MAX_REWARD_ITEMS) invalid(`Au plus ${MAX_REWARD_ITEMS} éléments par récompense.`);
const cardIds = items.filter((item) => item?.type === "card").map((item) => item.editionId);
if (new Set(cardIds).size !== cardIds.length) invalid("Chaque carte ne peut être offerte qu’une fois par récompense.");
return { items: items.map((item) => {
const quantity = item?.quantity ?? 1;
if (item?.type === "card" && quantity !== 1) invalid("Une carte s’offre en un seul exemplaire.");
if (!Number.isInteger(quantity) || quantity < 1 || quantity > MAX_ITEM_QUANTITY) invalid(`Quantité invalide : de 1 à ${MAX_ITEM_QUANTITY} par élément.`);
return { ...normalizeItem(item, catalog), quantity };
}) };
}
function normalizeItem(reward, catalog) {
if (reward?.type === "card") {
if (!catalog.editions.some((edition) => edition.id === reward.editionId)) invalid("Choisissez une carte du catalogue.");
return { type: "card", editionId: reward.editionId };
}
if (reward?.type !== "pack") invalid("Choisissez une carte ou un paquet à offrir.");
const collection = catalog.collections.find((item) => item.id === reward.collectionId);
if (!collection) invalid("Choisissez une collection.");
const cardIds = new Set(catalog.cards.filter((card) => card.collectionId === collection.id).map((card) => card.id));
if (collection.packCategory === "shop") invalid("Ce paquet ne s’obtient que dans la boutique.");
const drawable = catalog.editions.filter((edition) => cardIds.has(edition.cardId) && isDrawableEdition(edition));
const rarityIds = new Set(catalog.rarities.map((rarity) => rarity.id));
let rarityWeights = null;
if (reward.rarityWeights != null) {
try {
validateRarityWeights(reward.rarityWeights, rarityIds, collection.id);
} catch {
invalid("Taux personnalisés invalides : un entier positif ou nul par rareté, pour un total strictement positif.");
}
if (!drawable.some((edition) => reward.rarityWeights[edition.rarity] > 0)) invalid("Ces taux ne permettent de tirer aucune carte de la collection.");
rarityWeights = Object.fromEntries(catalog.rarities.map((rarity) => [rarity.id, reward.rarityWeights[rarity.id]]));
}
let guarantee = null;
if (reward.guarantee?.type === "rarity") {
const { rarity, count } = reward.guarantee;
const rank = catalog.rarities.findIndex((item) => item.id === rarity);
if (rank < 0 || !Number.isInteger(count) || count < 1 || count > 3) invalid("Garantie invalide : de 1 à 3 cartes d’une rareté connue.");
if (!drawable.some((edition) => catalog.rarities.findIndex((item) => item.id === edition.rarity) >= rank)) invalid("Cette collection n’a aucune carte tirable de cette rareté ou mieux.");
guarantee = { type: "rarity", rarity, count };
} else if (reward.guarantee?.type === "edition") {
const edition = catalog.editions.find((item) => item.id === reward.guarantee.editionId);
if (!edition || !cardIds.has(edition.cardId)) invalid("La carte garantie doit appartenir à la collection du paquet.");
guarantee = { type: "edition", editionId: edition.id };
} else if (reward.guarantee != null) {
invalid("Garantie inconnue.");
}
if (!rarityWeights && !collection.dropWeights) invalid("Cette collection n’a pas de taux de tirage : définissez des taux personnalisés.");
return { type: "pack", collectionId: collection.id, rarityWeights, guarantee };
}

854
services/cards/service.js Normal file
View file

@ -0,0 +1,854 @@
// Rôle : applique les règles serveur de propriété, paquets, transferts et distributions Sokko TCG.
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { normalizeReward } from "./rewards.js";
import { planRecycling, spareQuantity, validateShopSetting } from "./stardust.js";
import { FULL_ART_FORMAT, buildPublishedCatalog, createCatalogIndex, holographicFinishIds, legendaryParentEdition, MATCH_HOLO_PALETTE_ID, mythicEditionId, publicCatalog, validateRarityWeights } from "./catalog.js";
import { calculateRecharge, pinnedRecharge, drawPack, drawShopPack, MAX_RECHARGE_INTERVAL_MS, MIN_RECHARGE_INTERVAL_MS, spendOpening } from "./game-rules.js";
const TRANSFER_TTL_MS = 7 * 24 * 60 * 60 * 1000;
const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const RARITY_RANK = new Map(["common", "rare", "epic", "legendary", "mythic"].map((rarity, index) => [rarity, index]));
function fail(status, code, message) {
throw Object.assign(new Error(message), { status, code });
}
function token(bytes = 24) {
return randomBytes(bytes).toString("base64url");
}
function tokenHash(value) {
return createHash("sha256").update(value).digest("hex");
}
function publicPlayer(row) {
return { id: row.id, displayName: row.display_name, avatarUrl: row.avatar_url, isAdmin: Boolean(row.is_admin) };
}
// Compte de la connexion « Version développement » et son solde de poussière figé par `devPerks`.
export const DEV_DISCORD_ID = "dev-admin";
const WELCOME_OPENINGS = 3;
const ADMIN_HISTORY_PAGE_SIZE = 50;
// Liste blanche : audit_log garde aussi les actions d'administration, qui n'ont pas leur place dans le journal d'un joueur.
// Les types gift_created, gift_joined, gift_cancelled et trade_joined ne sont plus écrits, mais restent lisibles dans les anciens comptes.
const PLAYER_HISTORY_EVENTS = Object.freeze([
"welcome_opening", "pack_opened", "gift_pack_opened", "cards_recycled", "opening_purchased", "campaign_claimed",
"trade_created", "trade_received", "trade_declined", "trade_joined", "trade_completed", "trade_cancelled",
"gift_created", "gift_joined", "gift_completed", "gift_cancelled"
]);
const DEV_STARDUST = 1000;
export class CardsService {
constructor({ database, catalog, now = Date.now, random, devPerks = false } = {}) {
// Serveur Vite local uniquement : ressources permanentes du compte de développement pour tester le jeu sans attendre.
this.devPerks = devPerks;
this.database = database;
this.db = database.db;
// Catalogue versionné préparé par loadCardsCatalog / prepareVersionedCatalog (finitions générées, sans mythiques).
this.versionedCatalog = catalog;
this.now = now;
this.random = random;
this.reloadCatalog();
}
get rechargeSetting() {
const row = this.db.prepare("SELECT interval_ms, max_openings, updated_at FROM recharge_settings WHERE id = 1").get();
return { intervalMs: row.interval_ms, maxOpenings: row.max_openings, updatedAt: row.updated_at };
}
// Le délai s'applique immédiatement à tous les joueurs, y compris au temps écoulé depuis leur dernière recharge.
updateRechargeSetting(playerId, { intervalMs } = {}) {
this.requireAdmin(playerId);
if (!Number.isInteger(intervalMs) || intervalMs < MIN_RECHARGE_INTERVAL_MS || intervalMs > MAX_RECHARGE_INTERVAL_MS || intervalMs % MIN_RECHARGE_INTERVAL_MS !== 0) {
fail(400, "RECHARGE_INTERVAL_INVALID", "Délai invalide : un nombre entier de minutes, entre 1 minute et 7 jours.");
}
const current = this.rechargeSetting;
if (current.intervalMs === intervalMs) fail(409, "RECHARGE_UNCHANGED", "Ce délai est déjà en vigueur.");
this.database.transaction(() => {
this.db.prepare("UPDATE recharge_settings SET interval_ms = ?, updated_at = ?, updated_by = ? WHERE id = 1").run(intervalMs, this.now(), playerId);
this.audit(playerId, "recharge_updated", "recharge", { previousIntervalMs: current.intervalMs, intervalMs });
});
return { rechargeSetting: this.rechargeSetting };
}
get shopSetting() {
const row = this.db.prepare("SELECT stardust_values_json, opening_price, shop_pack_price, shop_pack_share, updated_at FROM shop_settings WHERE id = 1").get();
return { stardustValues: JSON.parse(row.stardust_values_json), openingPrice: row.opening_price, shopPackPrice: row.shop_pack_price, shopPackShare: row.shop_pack_share, updatedAt: row.updated_at };
}
updateShopSetting(playerId, { stardustValues, openingPrice, shopPackPrice, shopPackShare } = {}) {
this.requireAdmin(playerId);
const previous = this.shopSetting;
const next = { stardustValues, openingPrice, shopPackPrice: shopPackPrice ?? previous.shopPackPrice, shopPackShare: shopPackShare ?? previous.shopPackShare };
const error = validateShopSetting(next, this.catalog.rarities.map((rarity) => rarity.id));
if (error) fail(400, "SHOP_SETTING_INVALID", error);
this.database.transaction(() => {
this.db.prepare("UPDATE shop_settings SET stardust_values_json = ?, opening_price = ?, shop_pack_price = ?, shop_pack_share = ?, updated_at = ?, updated_by = ? WHERE id = 1")
.run(JSON.stringify(next.stardustValues), next.openingPrice, next.shopPackPrice, next.shopPackShare, this.now(), playerId);
this.audit(playerId, "shop_updated", "shop", { previous: { stardustValues: previous.stardustValues, openingPrice: previous.openingPrice, shopPackPrice: previous.shopPackPrice, shopPackShare: previous.shopPackShare }, ...next });
});
return { shopSetting: this.shopSetting };
}
// Ignore les lignes devenues incohérentes avec le catalogue versionné (carte, finition, forme ou palette supprimées)
// pour que le serveur démarre toujours ; elles restent en base et réapparaissent si la cible revient.
adminContent() {
const versioned = this.versionedCatalog;
const holographic = holographicFinishIds(versioned);
const cardIds = new Set(versioned.cards.map((card) => card.id));
const collectionIds = new Set(versioned.collections.map((collection) => collection.id));
const shapeIds = new Set(versioned.particleShapes.map((shape) => shape.id));
const paletteIds = new Set([...versioned.particlePalettes.map((palette) => palette.id), MATCH_HOLO_PALETTE_ID]);
const variations = this.db.prepare("SELECT edition_id, card_id, finish_id, status FROM mythic_variations").all()
.map((row) => ({ editionId: row.edition_id, cardId: row.card_id, finishId: row.finish_id, status: row.status }))
.filter((row) => holographic.has(row.finishId) && legendaryParentEdition(versioned, row.cardId) && row.editionId === mythicEditionId(row.cardId, row.finishId));
const openingSettings = this.db.prepare("SELECT scope, target_id, particle_shape_id, particle_palette_id FROM mythic_opening_settings ORDER BY scope, target_id").all()
.map((row) => ({
scope: row.scope,
targetId: row.target_id,
particleShapeId: shapeIds.has(row.particle_shape_id) ? row.particle_shape_id : null,
particlePaletteId: paletteIds.has(row.particle_palette_id) ? row.particle_palette_id : null
}))
.filter((row) => (row.scope === "card" ? cardIds : collectionIds).has(row.targetId));
const collectionStates = this.db.prepare("SELECT collection_id, active FROM collection_states").all()
.filter((row) => collectionIds.has(row.collection_id))
.map((row) => ({ collectionId: row.collection_id, active: Boolean(row.active) }));
const rarityIds = new Set(versioned.rarities.map((rarity) => rarity.id));
const dropRates = this.db.prepare("SELECT collection_id, rarity_weights_json FROM drop_rates").all()
.map((row) => ({ collectionId: row.collection_id, rarityWeights: JSON.parse(row.rarity_weights_json) }))
.filter((rate) => {
if (!collectionIds.has(rate.collectionId)) return false;
try {
validateRarityWeights(rate.rarityWeights, rarityIds, rate.collectionId);
return true;
} catch {
return false;
}
});
return { variations, openingSettings, collectionStates, dropRates };
}
reloadCatalog() {
const catalog = buildPublishedCatalog(this.versionedCatalog, this.adminContent());
this.catalog = catalog;
this.index = createCatalogIndex(catalog);
return catalog;
}
requireAdmin(playerId) {
const player = this.db.prepare("SELECT is_admin FROM players WHERE id = ?").get(playerId);
if (!player?.is_admin) fail(403, "ADMIN_REQUIRED", "Accès administrateur requis.");
}
validateOpeningStyle({ particleShapeId = null, particlePaletteId = null } = {}) {
if (particleShapeId != null && !this.versionedCatalog.particleShapes.some((shape) => shape.id === particleShapeId)) fail(400, "PARTICLE_SHAPE_INVALID", "Forme de particules inconnue.");
if (particlePaletteId != null && particlePaletteId !== MATCH_HOLO_PALETTE_ID && !this.versionedCatalog.particlePalettes.some((palette) => palette.id === particlePaletteId)) fail(400, "PARTICLE_PALETTE_INVALID", "Palette de particules inconnue.");
return { particleShapeId, particlePaletteId };
}
writeOpeningSetting(playerId, scope, targetId, { particleShapeId, particlePaletteId }) {
if (!particleShapeId && !particlePaletteId) {
this.db.prepare("DELETE FROM mythic_opening_settings WHERE scope = ? AND target_id = ?").run(scope, targetId);
return;
}
this.db.prepare(`INSERT INTO mythic_opening_settings(scope, target_id, particle_shape_id, particle_palette_id, updated_at, updated_by) VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(scope, target_id) DO UPDATE SET particle_shape_id = excluded.particle_shape_id, particle_palette_id = excluded.particle_palette_id, updated_at = excluded.updated_at, updated_by = excluded.updated_by`)
.run(scope, targetId, particleShapeId, particlePaletteId, this.now(), playerId);
}
// Édition encore possédée, ou citée par une ouverture ou un transfert passés (même si l'exemplaire a été recyclé).
editionReferenced(editionId) {
return Boolean(this.db.prepare(`SELECT 1 FROM collection_cards WHERE edition_id = ?1
UNION ALL SELECT 1 FROM opening_cards WHERE edition_id = ?1
UNION ALL SELECT 1 FROM transfers WHERE offered_edition_id = ?1 OR requested_edition_id = ?1 LIMIT 1`).get(editionId));
}
// Nombre de campagnes qui citent chaque édition, comme carte offerte ou carte garantie d'un paquet.
// Les paquets offerts reprennent la récompense de leur campagne : ils sont couverts aussi.
editionCampaignCounts() {
const counts = {};
for (const row of this.db.prepare("SELECT reward_json FROM campaigns").all()) {
const ids = new Set(JSON.parse(row.reward_json).items.map((item) => (item.type === "card" ? item.editionId : item.guarantee?.editionId)).filter(Boolean));
for (const id of ids) counts[id] = (counts[id] || 0) + 1;
}
return counts;
}
setCardMythicConfig(playerId, cardId, { finishIds, opening = {} } = {}) {
this.requireAdmin(playerId);
const versioned = this.versionedCatalog;
const card = versioned.cards.find((item) => item.id === cardId);
if (!card) fail(404, "CARD_NOT_FOUND", "Carte introuvable.");
if (!legendaryParentEdition(versioned, cardId)) fail(400, "LEGENDARY_REQUIRED", "Seule une carte légendaire peut recevoir une version mythique.");
const holographic = holographicFinishIds(versioned);
if (!Array.isArray(finishIds) || finishIds.some((id) => typeof id !== "string" || !holographic.has(id))) fail(400, "FINISH_INVALID", "Choisissez uniquement des finitions holographiques.");
const needsFullImage = (id) => versioned.finishes.find((item) => item.id === id)?.formatId === FULL_ART_FORMAT;
if (!card.fullImage && finishIds.some(needsFullImage)) fail(400, "FULL_IMAGE_REQUIRED", "Cette carte n’a pas d’illustration pleine.");
const openingStyle = this.validateOpeningStyle(opening);
const wanted = new Set(finishIds);
const now = this.now();
this.database.transaction(() => {
// Une seule règle pour toutes les variations : retirée des tirages si un joueur la possède ou si une campagne
// la cite (sinon ses codes et paquets offerts ne fonctionneraient plus), supprimée sinon.
const campaignCounts = this.editionCampaignCounts();
for (const finishId of holographic) {
const editionId = mythicEditionId(cardId, finishId);
const row = this.db.prepare("SELECT status FROM mythic_variations WHERE edition_id = ?").get(editionId);
if (wanted.has(finishId)) {
if (row?.status !== "active") {
this.db.prepare(`INSERT INTO mythic_variations(edition_id, card_id, finish_id, status, updated_at, updated_by) VALUES (?, ?, ?, 'active', ?, ?)
ON CONFLICT(edition_id) DO UPDATE SET status = 'active', updated_at = excluded.updated_at, updated_by = excluded.updated_by`).run(editionId, cardId, finishId, now, playerId);
}
} else if (row && (this.editionReferenced(editionId) || campaignCounts[editionId] > 0)) {
if (row.status !== "retired") this.db.prepare("UPDATE mythic_variations SET status = 'retired', updated_at = ?, updated_by = ? WHERE edition_id = ?").run(now, playerId, editionId);
} else if (row) {
this.db.prepare("DELETE FROM mythic_variations WHERE edition_id = ?").run(editionId);
}
}
this.writeOpeningSetting(playerId, "card", cardId, openingStyle);
this.audit(playerId, "catalog_card_mythic_updated", cardId, { finishIds: [...wanted], opening: openingStyle });
this.reloadCatalog();
});
return { catalog: publicCatalog(this.catalog) };
}
requireCollection(collectionId) {
if (!this.versionedCatalog.collections.some((collection) => collection.id === collectionId)) fail(404, "COLLECTION_NOT_FOUND", "Collection introuvable.");
}
setCollectionActive(playerId, collectionId, active) {
this.requireAdmin(playerId);
this.requireCollection(collectionId);
if (typeof active !== "boolean") fail(400, "COLLECTION_STATE_INVALID", "État du paquet invalide.");
if (active && !this.index.collections.get(collectionId)?.dropWeights) fail(409, "DROP_RATES_REQUIRED", "Définissez d’abord les taux de tirage de ce paquet.");
this.database.transaction(() => {
this.db.prepare(`INSERT INTO collection_states(collection_id, active, updated_at, updated_by) VALUES (?, ?, ?, ?)
ON CONFLICT(collection_id) DO UPDATE SET active = excluded.active, updated_at = excluded.updated_at, updated_by = excluded.updated_by`).run(collectionId, active ? 1 : 0, this.now(), playerId);
this.audit(playerId, active ? "collection_opened" : "collection_closed", collectionId, {});
this.reloadCatalog();
});
return { catalog: publicCatalog(this.catalog) };
}
// Les taux de tirage se modifient directement ; le journal d'audit garde les anciens et les nouveaux poids.
setDropRates(playerId, collectionId, rarityWeights) {
this.requireAdmin(playerId);
this.requireCollection(collectionId);
const rarityIds = new Set(this.versionedCatalog.rarities.map((rarity) => rarity.id));
try {
validateRarityWeights(rarityWeights, rarityIds, collectionId);
} catch {
fail(400, "DROP_WEIGHTS_INVALID", "Poids invalides : un entier positif ou nul par rareté, pour un total strictement positif.");
}
const previous = this.index.collections.get(collectionId)?.dropWeights || null;
if (previous && [...rarityIds].every((rarity) => previous[rarity] === rarityWeights[rarity])) fail(409, "DROP_RATES_UNCHANGED", "Ces taux sont déjà en vigueur.");
const weights = Object.fromEntries([...rarityIds].map((rarity) => [rarity, rarityWeights[rarity]]));
this.database.transaction(() => {
this.db.prepare(`INSERT INTO drop_rates(collection_id, rarity_weights_json, updated_at, updated_by) VALUES (?, ?, ?, ?)
ON CONFLICT(collection_id) DO UPDATE SET rarity_weights_json = excluded.rarity_weights_json, updated_at = excluded.updated_at, updated_by = excluded.updated_by`).run(collectionId, JSON.stringify(weights), this.now(), playerId);
this.audit(playerId, "drop_rates_updated", collectionId, { previous, rarityWeights: weights });
this.reloadCatalog();
});
return { catalog: publicCatalog(this.catalog) };
}
setCollectionMythicOpening(playerId, collectionId, opening = {}) {
this.requireAdmin(playerId);
if (!this.versionedCatalog.collections.some((collection) => collection.id === collectionId)) fail(404, "COLLECTION_NOT_FOUND", "Collection introuvable.");
const openingStyle = this.validateOpeningStyle(opening);
this.database.transaction(() => {
this.writeOpeningSetting(playerId, "collection", collectionId, openingStyle);
this.audit(playerId, "catalog_collection_opening_updated", collectionId, { opening: openingStyle });
this.reloadCatalog();
});
return { catalog: publicCatalog(this.catalog) };
}
upsertPlayer({ discordId, displayName, avatarUrl = "", isAdmin = false }) {
const now = this.now();
let row = this.db.prepare("SELECT * FROM players WHERE discord_id = ?").get(discordId);
if (!row) {
const id = randomUUID();
this.db.prepare(`INSERT INTO players(id, discord_id, display_name, avatar_url, is_admin, created_at, openings_balance, recharge_anchor)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(id, discordId, displayName, avatarUrl, isAdmin ? 1 : 0, now, WELCOME_OPENINGS, now);
row = this.db.prepare("SELECT * FROM players WHERE id = ?").get(id);
this.audit(id, "welcome_opening", id, { amount: WELCOME_OPENINGS });
} else {
this.db.prepare("UPDATE players SET display_name = ?, avatar_url = ?, is_admin = ? WHERE id = ?").run(displayName, avatarUrl, isAdmin ? 1 : 0, row.id);
row = this.db.prepare("SELECT * FROM players WHERE id = ?").get(row.id);
}
return publicPlayer(row);
}
createSession(playerId) {
const rawToken = token(32);
const csrfToken = token(24);
const now = this.now();
this.db.prepare("INSERT INTO sessions(token_hash, player_id, csrf_token, created_at, expires_at) VALUES (?, ?, ?, ?, ?)")
.run(tokenHash(rawToken), playerId, csrfToken, now, now + SESSION_TTL_MS);
return { token: rawToken, csrfToken, expiresAt: now + SESSION_TTL_MS };
}
getSession(rawToken) {
if (!rawToken) return null;
const row = this.db.prepare(`SELECT s.*, p.discord_id, p.display_name, p.avatar_url, p.is_admin
FROM sessions s JOIN players p ON p.id = s.player_id WHERE s.token_hash = ?`).get(tokenHash(rawToken));
if (!row || row.expires_at <= this.now()) {
if (row) this.db.prepare("DELETE FROM sessions WHERE token_hash = ?").run(tokenHash(rawToken));
return null;
}
return { player: publicPlayer({ id: row.player_id, ...row }), csrfToken: row.csrf_token, expiresAt: row.expires_at };
}
deleteSession(rawToken) {
if (rawToken) this.db.prepare("DELETE FROM sessions WHERE token_hash = ?").run(tokenHash(rawToken));
}
refreshRecharge(playerId) {
const player = this.db.prepare("SELECT * FROM players WHERE id = ?").get(playerId);
if (!player) fail(404, "PLAYER_NOT_FOUND", "Profil introuvable.");
const pinned = this.devPerks && player.discord_id === DEV_DISCORD_ID;
const recharge = (pinned ? pinnedRecharge : calculateRecharge)({
openingsBalance: player.openings_balance,
rechargeAnchor: player.recharge_anchor
}, this.now(), this.rechargeSetting);
this.db.prepare("UPDATE players SET openings_balance = ?, recharge_anchor = ? WHERE id = ?")
.run(recharge.openingsBalance, recharge.rechargeAnchor, playerId);
if (pinned) this.db.prepare("UPDATE players SET stardust = ? WHERE id = ?").run(DEV_STARDUST, playerId);
return recharge;
}
// Carte affichable à partir d'une édition (catalogue publié).
cardEntry(editionId, extra = {}) {
const edition = this.index.editions.get(editionId);
const card = edition ? this.index.cards.get(edition.cardId) : null;
return { editionId, edition, card, ...extra };
}
quantityOf(playerId, editionId) {
return this.db.prepare("SELECT quantity FROM collection_cards WHERE player_id = ? AND edition_id = ?").get(playerId, editionId)?.quantity ?? 0;
}
addCard(playerId, editionId) {
this.db.prepare(`INSERT INTO collection_cards(player_id, edition_id, quantity, acquired_at) VALUES (?, ?, 1, ?)
ON CONFLICT(player_id, edition_id) DO UPDATE SET quantity = quantity + 1`).run(playerId, editionId, this.now());
}
// Retire des doublons : l'exemplaire conservé ne peut jamais partir.
removeDuplicates(playerId, editionId, count) {
const removed = this.db.prepare("UPDATE collection_cards SET quantity = quantity - ?1 WHERE player_id = ?2 AND edition_id = ?3 AND quantity - ?1 >= 1").run(count, playerId, editionId);
if (!removed.changes) fail(409, "COLLECTION_CHANGED", "Votre collection a changé, réessayez.");
}
// Doublons réservés par les transferts en cours du joueur, par carte.
reservedCounts(playerId) {
const rows = this.db.prepare(`SELECT edition_id, COUNT(*) AS count FROM (
SELECT offered_edition_id AS edition_id FROM transfers WHERE initiator_id = ?1 AND status = 'open'
) GROUP BY edition_id`).all(playerId);
return new Map(rows.map((row) => [row.edition_id, row.count]));
}
// Collection du joueur : quantité, doublons réservés et doublons disponibles (échange, don, recyclage) par carte.
collectionOf(playerId) {
const reserved = this.reservedCounts(playerId);
return this.db.prepare("SELECT edition_id, quantity, acquired_at FROM collection_cards WHERE player_id = ? ORDER BY acquired_at DESC, edition_id").all(playerId)
.map((row) => {
const entry = { editionId: row.edition_id, quantity: row.quantity, reserved: reserved.get(row.edition_id) || 0, acquiredAt: row.acquired_at };
return { ...entry, spare: spareQuantity(entry) };
});
}
requireSpare(playerId, editionId) {
const entry = this.collectionOf(playerId).find((item) => item.editionId === editionId);
if (!entry) fail(404, "CARD_NOT_OWNED", "Vous ne possédez pas cette carte.");
if (!entry.spare) fail(409, "NOT_A_DUPLICATE", "Seuls les doublons peuvent être échangés ou donnés : gardez au moins un exemplaire.");
}
openingById(openingId, playerId) {
const opening = this.db.prepare("SELECT * FROM openings WHERE id = ? AND player_id = ?").get(openingId, playerId);
if (!opening) return null;
const cards = this.db.prepare("SELECT * FROM opening_cards WHERE opening_id = ? ORDER BY position").all(opening.id);
const gift = this.db.prepare("SELECT options_json FROM gift_packs WHERE opening_id = ?").get(opening.id);
return {
id: opening.id,
collectionId: opening.collection_id,
options: gift ? JSON.parse(gift.options_json) : null,
status: opening.status,
createdAt: opening.created_at,
cards: cards.map((row) => this.cardEntry(row.edition_id, { id: `${opening.id}:${row.position}`, position: row.position, isNewCard: Boolean(row.was_new_card), isNewEdition: Boolean(row.was_new_edition), quantityBefore: row.quantity_before }))
};
}
rarestPull(playerId) {
const pulls = this.db.prepare(`SELECT oc.edition_id, oc.position, o.id AS opening_id, o.created_at AS opened_at
FROM opening_cards oc
JOIN openings o ON o.id = oc.opening_id
WHERE o.player_id = ?
ORDER BY o.created_at DESC, oc.position DESC`).all(playerId);
let rarest = null;
for (const pull of pulls) {
const entry = this.cardEntry(pull.edition_id, { id: `${pull.opening_id}:${pull.position}`, openedAt: pull.opened_at });
if (!rarest || (RARITY_RANK.get(entry.edition?.rarity) ?? -1) > (RARITY_RANK.get(rarest.edition?.rarity) ?? -1)) rarest = entry;
}
return rarest;
}
// Un transfert expiré ou annulé libère simplement ses doublons réservés (la réservation découle du statut).
expireTransfers() {
this.db.prepare("UPDATE transfers SET status = 'expired' WHERE status = 'open' AND expires_at <= ?").run(this.now());
}
transferView(row, playerId) {
const initiator = this.db.prepare("SELECT id, display_name, avatar_url FROM players WHERE id = ?").get(row.initiator_id);
const recipient = row.recipient_id ? this.db.prepare("SELECT id, display_name, avatar_url FROM players WHERE id = ?").get(row.recipient_id) : null;
return {
id: row.id, type: row.type, status: row.status, declined: Boolean(row.declined), createdAt: row.created_at, expiresAt: row.expires_at, completedAt: row.completed_at,
direction: row.initiator_id === playerId ? "sent" : "received",
initiator: initiator && { id: initiator.id, displayName: initiator.display_name, avatarUrl: initiator.avatar_url },
recipient: recipient && { id: recipient.id, displayName: recipient.display_name, avatarUrl: recipient.avatar_url },
offered: this.cardEntry(row.offered_edition_id),
requested: row.requested_edition_id ? this.cardEntry(row.requested_edition_id) : null
};
}
getState(playerId) {
const recharge = this.database.transaction(() => this.refreshRecharge(playerId));
this.expireTransfers();
const player = this.db.prepare("SELECT * FROM players WHERE id = ?").get(playerId);
if (!player) fail(404, "PLAYER_NOT_FOUND", "Profil introuvable.");
const owned = this.collectionOf(playerId);
const collection = owned.map((entry) => this.cardEntry(entry.editionId, entry));
const favorites = this.db.prepare("SELECT edition_id FROM favorites WHERE player_id = ?").all(playerId).map((row) => row.edition_id);
const pending = this.db.prepare("SELECT id FROM openings WHERE player_id = ? AND status = 'pending' ORDER BY created_at DESC LIMIT 1").get(playerId);
const history = this.db.prepare("SELECT event_type, entity_id, details_json, created_at FROM audit_log WHERE player_id = ? AND event_type IN (" + PLAYER_HISTORY_EVENTS.map(() => "?").join(", ") + ") ORDER BY created_at DESC LIMIT 100").all(playerId, ...PLAYER_HISTORY_EVENTS)
.map((row) => ({ type: row.event_type, entityId: row.entity_id, details: JSON.parse(row.details_json), createdAt: row.created_at }));
const transferRows = this.db.prepare("SELECT * FROM transfers WHERE initiator_id = ? OR recipient_id = ? ORDER BY created_at DESC LIMIT 50").all(playerId, playerId);
const giftPacks = this.db.prepare(`SELECT g.id, g.collection_id, g.options_json, g.created_at, c.name AS campaign_name
FROM gift_packs g JOIN campaigns c ON c.id = g.campaign_id WHERE g.player_id = ? AND g.opening_id IS NULL ORDER BY g.created_at`).all(playerId)
.map((row) => ({ id: row.id, collectionId: row.collection_id, campaignName: row.campaign_name, receivedAt: row.created_at, options: JSON.parse(row.options_json) }));
const openingsCount = this.db.prepare("SELECT COUNT(*) AS count FROM openings WHERE player_id = ?").get(playerId).count;
const shop = this.shopSetting;
const recycling = this.recyclingPlan(owned);
return {
player: publicPlayer(player), recharge, collection, favorites,
wallet: { stardust: player.stardust, purchasedOpenings: player.purchased_openings },
shop: { stardustValues: shop.stardustValues, openingPrice: shop.openingPrice, shopPackPrice: shop.shopPackPrice, shopPackShare: shop.shopPackShare },
recycling: { count: recycling.count, stardust: recycling.stardust },
pendingOpening: pending ? this.openingById(pending.id, playerId) : null,
rarestPull: this.rarestPull(playerId), stats: { openingsCount },
history, transfers: transferRows.map((row) => this.transferView(row, playerId)), giftPacks
};
}
// Tout ce qui n'est pas un événement de jeu : une nouvelle action d'administration apparaît ici sans autre déclaration.
getAdminHistory(playerId, { before = null } = {}) {
this.requireAdmin(playerId);
const rows = this.db.prepare(`SELECT a.id, a.event_type, a.entity_id, a.details_json, a.created_at, p.display_name AS admin_name, c.name AS campaign_name
FROM audit_log a
LEFT JOIN players p ON p.id = a.player_id
LEFT JOIN campaigns c ON c.id = a.entity_id AND a.event_type LIKE 'campaign_%'
WHERE a.event_type NOT IN (${PLAYER_HISTORY_EVENTS.map(() => "?").join(", ")}) AND (? IS NULL OR a.id < ?)
ORDER BY a.id DESC LIMIT ?`).all(...PLAYER_HISTORY_EVENTS, before, before, ADMIN_HISTORY_PAGE_SIZE + 1);
const page = rows.slice(0, ADMIN_HISTORY_PAGE_SIZE);
return {
entries: page.map((row) => ({ id: row.id, type: row.event_type, entityId: row.entity_id, details: JSON.parse(row.details_json), createdAt: row.created_at, adminName: row.admin_name, campaignName: row.campaign_name })),
nextBefore: rows.length > ADMIN_HISTORY_PAGE_SIZE ? page.at(-1).id : null
};
}
getAdminDashboard(playerId) {
this.requireAdmin(playerId);
// Cartes possédées par joueur et par rareté (la rareté vient du catalogue publié).
const rarityCounts = new Map();
for (const row of this.db.prepare("SELECT player_id, edition_id, quantity FROM collection_cards").all()) {
const rarity = this.index.editions.get(row.edition_id)?.rarity;
if (!rarity) continue;
const counts = rarityCounts.get(row.player_id) || {};
counts[rarity] = (counts[rarity] || 0) + row.quantity;
rarityCounts.set(row.player_id, counts);
}
const players = this.database.transaction(() => this.db.prepare(`SELECT p.*,
(SELECT MAX(o.created_at) FROM openings o WHERE o.player_id = p.id) AS last_opening_at,
(SELECT COUNT(*) FROM openings o WHERE o.player_id = p.id) AS openings_count,
(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 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) => {
const recharge = this.refreshRecharge(row.id);
return {
id: row.id,
displayName: row.display_name,
avatarUrl: row.avatar_url,
isAdmin: Boolean(row.is_admin),
createdAt: row.created_at,
lastOpeningAt: row.last_opening_at ?? null,
openingsCount: row.openings_count,
openingsBalance: recharge.openingsBalance,
nextOpeningAt: recharge.nextOpeningAt,
totalCards: row.total_cards,
rarityCounts: rarityCounts.get(row.id) || {},
giftPacks: row.gift_packs,
transfersCount: row.transfers_count,
stardust: row.stardust,
purchasedOpenings: row.purchased_openings
};
}));
const now = this.now();
return {
generatedAt: now,
stats: {
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
},
players,
rechargeSetting: this.rechargeSetting,
shopSetting: this.shopSetting,
campaigns: this.campaignSummaries(),
editionCampaigns: this.editionCampaignCounts(),
// Variations possédées ou citées par une ouverture ou un transfert passés : elles ne peuvent qu'être retirées.
recordedEditions: this.db.prepare(`SELECT edition_id FROM collection_cards UNION SELECT edition_id FROM opening_cards
UNION SELECT offered_edition_id FROM transfers UNION SELECT requested_edition_id FROM transfers WHERE requested_edition_id IS NOT NULL`).all().map((row) => row.edition_id),
editionOwners: Object.fromEntries(this.db.prepare("SELECT edition_id, COUNT(*) AS owners FROM collection_cards GROUP BY edition_id").all().map((row) => [row.edition_id, row.owners]))
};
}
// Crée une ouverture en attente de révélation avec les éditions tirées ; utilisé par les paquets normaux, achetés et offerts.
// Une carte ou une édition est « nouvelle » si le joueur ne la possédait pas : une carte obtenue n'est jamais perdue.
insertOpening(playerId, collectionId, editionIds) {
const openingId = randomUUID();
this.db.prepare("INSERT INTO openings(id, player_id, collection_id, status, created_at) VALUES (?, ?, ?, 'pending', ?)")
.run(openingId, playerId, collectionId, this.now());
const ownsCard = this.db.prepare("SELECT 1 FROM collection_cards WHERE player_id = ? AND edition_id IN (SELECT value FROM json_each(?)) LIMIT 1");
editionIds.forEach((editionId, position) => {
const edition = this.index.editions.get(editionId);
const quantity = this.quantityOf(playerId, editionId);
const cardEditions = this.catalog.editions.filter((item) => item.cardId === edition.cardId).map((item) => item.id);
const knownCard = ownsCard.get(playerId, JSON.stringify(cardEditions));
this.db.prepare("INSERT INTO opening_cards(opening_id, position, edition_id, was_new_card, was_new_edition, quantity_before) VALUES (?, ?, ?, ?, ?, ?)")
.run(openingId, position, editionId, knownCard ? 0 : 1, quantity ? 0 : 1, quantity);
this.addCard(playerId, editionId);
});
return openingId;
}
// Rejoue une requête déjà traitée (même clé d'idempotence) ou exécute `create` qui renvoie l'identifiant d'ouverture.
idempotentOpening(playerId, scope, requestKey, create) {
if (!requestKey || requestKey.length > 100) fail(400, "IDEMPOTENCY_REQUIRED", "Une clé d'idempotence est requise.");
let openingId;
this.database.transaction(() => {
const previous = this.db.prepare("SELECT response_json FROM idempotency WHERE player_id = ? AND scope = ? AND request_key = ?").get(playerId, scope, requestKey);
if (previous) {
openingId = JSON.parse(previous.response_json).openingId;
return;
}
const pending = this.db.prepare("SELECT id FROM openings WHERE player_id = ? AND status = 'pending'").get(playerId);
if (pending) fail(409, "PENDING_OPENING", "Terminez d'abord l'ouverture en cours.");
openingId = create();
this.db.prepare("INSERT INTO idempotency(player_id, scope, request_key, response_json, created_at) VALUES (?, ?, ?, ?, ?)")
.run(playerId, scope, requestKey, JSON.stringify({ openingId }), this.now());
});
return { opening: this.openingById(openingId, playerId), state: this.getState(playerId) };
}
// `purchased` : consomme une ouverture achetée en boutique au lieu de la réserve rechargeable.
openPack(playerId, collectionId, requestKey, { purchased = false } = {}) {
return this.idempotentOpening(playerId, purchased ? "open-purchased" : "open-pack", requestKey, () => {
if (this.catalog.collections.find((item) => item.id === collectionId)?.packCategory === "shop") fail(409, "SHOP_PACK_ONLY", "Ce paquet ne s’obtient que dans la boutique.");
if (purchased) {
const spent = this.db.prepare("UPDATE players SET purchased_openings = purchased_openings - 1 WHERE id = ? AND purchased_openings > 0").run(playerId);
if (!spent.changes) fail(409, "NO_PURCHASED_OPENING", "Vous n’avez aucune ouverture achetée.");
} else {
const spent = spendOpening(this.refreshRecharge(playerId), this.now(), this.rechargeSetting);
this.db.prepare("UPDATE players SET openings_balance = ?, recharge_anchor = ? WHERE id = ?").run(spent.openingsBalance, spent.rechargeAnchor, playerId);
}
const editionIds = drawPack(this.catalog, collectionId, this.random);
const openingId = this.insertOpening(playerId, collectionId, editionIds);
this.audit(playerId, "pack_opened", openingId, { collectionId, cards: editionIds, ...(purchased ? { purchased: true } : {}) });
return openingId;
});
}
recyclingPlan(collection, editionId = null) {
return planRecycling(collection, { editionId, rarityOf: (id) => this.index.editions.get(id)?.rarity, stardustValues: this.shopSetting.stardustValues });
}
// Recycle tous les doublons disponibles, ou un seul doublon de `editionId` ; un exemplaire de chaque carte reste toujours.
recycleDuplicates(playerId, { editionId = null } = {}) {
if (editionId != null && !this.index.editions.has(editionId)) fail(404, "EDITION_NOT_FOUND", "Édition introuvable.");
let plan;
this.database.transaction(() => {
this.expireTransfers();
if (this.db.prepare("SELECT 1 FROM openings WHERE player_id = ? AND status = 'pending'").get(playerId)) fail(409, "PENDING_OPENING", "Terminez d'abord l'ouverture en cours.");
plan = this.recyclingPlan(this.collectionOf(playerId), editionId);
if (!plan.count) fail(409, "NO_DUPLICATE", editionId ? "Aucun doublon disponible pour cette carte." : "Aucun doublon à recycler.");
for (const item of plan.items) this.removeDuplicates(playerId, item.editionId, item.count);
this.db.prepare("UPDATE players SET stardust = stardust + ? WHERE id = ?").run(plan.stardust, playerId);
this.audit(playerId, "cards_recycled", editionId || "duplicates", { count: plan.count, stardust: plan.stardust, editions: plan.items.map((item) => item.editionId) });
});
return { recycled: { count: plan.count, stardust: plan.stardust }, state: this.getState(playerId) };
}
buyOpening(playerId) {
const { openingPrice } = this.shopSetting;
this.database.transaction(() => {
const bought = this.db.prepare("UPDATE players SET stardust = stardust - ?, purchased_openings = purchased_openings + 1 WHERE id = ? AND stardust >= ?").run(openingPrice, playerId, openingPrice);
if (!bought.changes) fail(409, "NOT_ENOUGH_STARDUST", "Pas assez de poussière d’étoiles.");
this.audit(playerId, "opening_purchased", "shop", { price: openingPrice });
});
return this.getState(playerId);
}
// Le paquet de la Boutique se paie en poussière et s'ouvre aussitôt ; il ne consomme aucune ouverture.
buyShopPack(playerId, requestKey) {
return this.idempotentOpening(playerId, "buy-shop-pack", requestKey, () => {
const collection = this.catalog.collections.find((item) => item.packCategory === "shop" && item.active);
if (!collection) fail(404, "COLLECTION_UNAVAILABLE", "Ce paquet n’est pas disponible.");
const { shopPackPrice, shopPackShare } = this.shopSetting;
// Compte de développement : son solde figé doit être appliqué avant de vérifier le prix.
this.refreshRecharge(playerId);
const paid = this.db.prepare("UPDATE players SET stardust = stardust - ? WHERE id = ? AND stardust >= ?").run(shopPackPrice, playerId, shopPackPrice);
if (!paid.changes) fail(409, "NOT_ENOUGH_STARDUST", "Pas assez de poussière d’étoiles.");
const editionIds = drawShopPack(this.catalog, collection.id, this.random, shopPackShare);
const openingId = this.insertOpening(playerId, collection.id, editionIds);
this.audit(playerId, "pack_opened", openingId, { collectionId: collection.id, cards: editionIds, price: shopPackPrice });
return openingId;
});
}
// Un paquet offert ne consomme pas d'ouverture rechargeable et s'ouvre même si la collection est fermée.
openGiftPack(playerId, giftPackId, requestKey) {
return this.idempotentOpening(playerId, "open-gift", requestKey, () => {
const gift = this.db.prepare("SELECT * FROM gift_packs WHERE id = ? AND player_id = ? AND opening_id IS NULL").get(giftPackId, playerId);
if (!gift) fail(404, "GIFT_PACK_NOT_FOUND", "Ce paquet offert n'est plus disponible.");
const options = JSON.parse(gift.options_json);
const editionIds = drawPack(this.catalog, gift.collection_id, this.random, { weights: options.rarityWeights, guarantee: options.guarantee, requireActive: false });
const openingId = this.insertOpening(playerId, gift.collection_id, editionIds);
this.db.prepare("UPDATE gift_packs SET opening_id = ?, opened_at = ? WHERE id = ?").run(openingId, this.now(), gift.id);
this.audit(playerId, "gift_pack_opened", openingId, { collectionId: gift.collection_id, campaignId: gift.campaign_id, cards: editionIds });
return openingId;
});
}
completeOpening(playerId, openingId) {
const result = this.db.prepare("UPDATE openings SET status = 'completed', completed_at = ? WHERE id = ? AND player_id = ? AND status = 'pending'").run(this.now(), openingId, playerId);
if (!result.changes && !this.openingById(openingId, playerId)) fail(404, "OPENING_NOT_FOUND", "Ouverture introuvable.");
return this.getState(playerId);
}
setFavorite(playerId, editionId, favorite) {
if (!this.index.editions.has(editionId)) fail(404, "EDITION_NOT_FOUND", "Édition introuvable.");
if (favorite) this.db.prepare("INSERT OR IGNORE INTO favorites(player_id, edition_id) VALUES (?, ?)").run(playerId, editionId);
else this.db.prepare("DELETE FROM favorites WHERE player_id = ? AND edition_id = ?").run(playerId, editionId);
return this.getState(playerId);
}
// Joueurs à qui donner ou proposer un échange : seuls leur identité publique et leurs doublons disponibles sont exposés, jamais leur collection.
listTraders(playerId) {
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);
return {
traders: rows.map((row) => ({
id: row.id,
displayName: row.display_name,
avatarUrl: row.avatar_url,
duplicates: this.collectionOf(row.id).filter((entry) => entry.spare > 0).map(({ editionId, spare }) => ({ editionId, spare }))
}))
};
}
// Déplace un doublon d'un joueur à l'autre ; l'exemplaire conservé reste toujours.
moveDuplicate(fromId, toId, editionId) {
this.removeDuplicates(fromId, editionId, 1);
this.addCard(toId, editionId);
}
requireRecipient(playerId, recipientId) {
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.");
}
// Un don arrive immédiatement. Un échange réserve le doublon proposé jusqu'à la réponse, l'annulation ou l'expiration.
createTransfer(playerId, { type, recipientId, editionId, requestedEditionId = null } = {}) {
if (!["trade", "gift"].includes(type)) fail(400, "TRANSFER_TYPE", "Type de transfert invalide.");
const transferId = randomUUID();
this.database.transaction(() => {
this.expireTransfers();
this.requireRecipient(playerId, recipientId);
this.requireSpare(playerId, editionId);
const now = this.now();
const insert = this.db.prepare(`INSERT INTO transfers(id, code, type, initiator_id, recipient_id, offered_edition_id, requested_edition_id, status, created_at, expires_at, completed_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
if (type === "gift") {
insert.run(transferId, token(9).toUpperCase(), type, playerId, recipientId, editionId, null, "completed", now, now, now);
this.moveDuplicate(playerId, recipientId, editionId);
this.audit(playerId, "gift_completed", transferId, { sent: editionId, received: null });
this.audit(recipientId, "gift_completed", transferId, { sent: null, received: editionId });
return;
}
if (requestedEditionId === editionId) fail(400, "TRADE_SAME_CARD", "Choisissez deux cartes différentes.");
if (!this.collectionOf(recipientId).some((entry) => entry.editionId === requestedEditionId && entry.spare > 0)) fail(409, "TRADE_CARD_UNAVAILABLE", "Ce joueur n’a plus ce doublon disponible.");
insert.run(transferId, token(9).toUpperCase(), type, playerId, recipientId, editionId, requestedEditionId, "open", now, now + TRANSFER_TTL_MS, null);
this.audit(playerId, "trade_created", transferId, { sent: editionId, received: requestedEditionId });
this.audit(recipientId, "trade_received", transferId, { sent: requestedEditionId, received: editionId });
});
return { transfer: this.transferView(this.db.prepare("SELECT * FROM transfers WHERE id = ?").get(transferId), playerId), state: this.getState(playerId) };
}
openTrade(transferId) {
const transfer = this.db.prepare("SELECT * FROM transfers WHERE id = ? AND status = 'open'").get(transferId);
if (!transfer) fail(404, "TRANSFER_NOT_FOUND", "Cette proposition n’est plus disponible.");
return transfer;
}
acceptTransfer(playerId, transferId) {
this.database.transaction(() => {
this.expireTransfers();
const transfer = this.openTrade(transferId);
if (transfer.recipient_id !== playerId) fail(404, "TRANSFER_NOT_FOUND", "Cette proposition n’est plus disponible.");
// Le doublon demandé n'est pas réservé tant que la proposition n'est pas acceptée : il a pu partir entre-temps.
this.requireSpare(playerId, transfer.requested_edition_id);
this.moveDuplicate(transfer.initiator_id, playerId, transfer.offered_edition_id);
this.moveDuplicate(playerId, transfer.initiator_id, transfer.requested_edition_id);
this.db.prepare("UPDATE transfers SET status = 'completed', completed_at = ? WHERE id = ?").run(this.now(), transferId);
this.audit(transfer.initiator_id, "trade_completed", transferId, { sent: transfer.offered_edition_id, received: transfer.requested_edition_id });
this.audit(playerId, "trade_completed", transferId, { sent: transfer.requested_edition_id, received: transfer.offered_edition_id });
});
return this.getState(playerId);
}
declineTransfer(playerId, transferId) {
this.database.transaction(() => {
this.expireTransfers();
const transfer = this.openTrade(transferId);
if (transfer.recipient_id !== playerId) fail(404, "TRANSFER_NOT_FOUND", "Cette proposition n’est plus disponible.");
this.db.prepare("UPDATE transfers SET status = 'cancelled', declined = 1 WHERE id = ?").run(transferId);
this.audit(transfer.initiator_id, "trade_declined", transferId, { sent: transfer.offered_edition_id, received: transfer.requested_edition_id });
this.audit(playerId, "trade_declined", transferId, { sent: transfer.requested_edition_id, received: transfer.offered_edition_id });
});
return this.getState(playerId);
}
cancelTransfer(playerId, transferId) {
this.database.transaction(() => {
this.expireTransfers();
const transfer = this.openTrade(transferId);
if (transfer.initiator_id !== playerId) fail(404, "TRANSFER_NOT_FOUND", "Cette proposition n’est plus disponible.");
this.db.prepare("UPDATE transfers SET status = 'cancelled' WHERE id = ?").run(transferId);
this.audit(playerId, "trade_cancelled", transferId, { sent: transfer.offered_edition_id, received: transfer.requested_edition_id });
this.audit(transfer.recipient_id, "trade_cancelled", transferId, { sent: transfer.requested_edition_id, received: transfer.offered_edition_id });
});
return this.getState(playerId);
}
// Toutes les campagnes, ou une seule si `campaignId` est donné.
campaignSummaries(campaignId = null) {
return this.db.prepare(`SELECT c.*, (SELECT COUNT(*) FROM campaign_claims cl WHERE cl.campaign_id = c.id) AS claimed_count
FROM campaigns c WHERE ? IS NULL OR c.id = ? ORDER BY c.created_at DESC`).all(campaignId, campaignId).map((row) => ({
id: row.id,
name: row.name,
code: row.code,
reward: JSON.parse(row.reward_json),
maxClaims: row.max_claims,
claimedCount: row.claimed_count,
createdAt: row.created_at,
expiresAt: row.expires_at,
revokedAt: row.revoked_at
}));
}
// Une campagne = un code lisible, partagé entre les joueurs, chacun ne l'utilisant qu'une fois.
// `maxClaims` null = utilisations illimitées ; `expiresAt` null = sans date d'expiration.
createCampaign(playerId, { name, reward, code: rawCode, maxClaims, expiresAt } = {}) {
this.requireAdmin(playerId);
const normalized = normalizeReward(reward, this.catalog);
if (!name?.trim() || name.trim().length > 80) fail(400, "CAMPAIGN_INVALID", "Donnez un nom de 1 à 80 caractères à la campagne.");
const code = String(rawCode || "").trim().toUpperCase();
if (!/^[A-Z0-9][A-Z0-9-]{3,23}$/.test(code)) fail(400, "CAMPAIGN_INVALID", "Code : 4 à 24 caractères, lettres, chiffres et tirets.");
const limit = maxClaims == null ? null : Number(maxClaims);
if (limit !== null && (!Number.isInteger(limit) || limit < 1 || limit > 100_000)) fail(400, "CAMPAIGN_INVALID", "Entre 1 et 100 000 utilisations, ou illimité.");
const expiry = this.campaignExpiry(expiresAt);
if (this.db.prepare("SELECT 1 FROM campaigns WHERE code = ?").get(code)) fail(409, "CODE_TAKEN", "Ce code est déjà utilisé par une autre campagne.");
const campaignId = randomUUID();
this.database.transaction(() => {
this.db.prepare(`INSERT INTO campaigns(id, name, code, reward_json, max_claims, created_by, created_at, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(campaignId, name.trim(), code, JSON.stringify(normalized), limit, playerId, this.now(), expiry);
this.audit(playerId, "campaign_created", campaignId, { code, reward: normalized, maxClaims: limit });
});
return { campaign: this.campaignSummary(campaignId) };
}
campaignSummary(campaignId) {
const [campaign] = this.campaignSummaries(campaignId);
if (!campaign) fail(404, "CAMPAIGN_NOT_FOUND", "Campagne introuvable.");
return campaign;
}
campaignDetail(playerId, campaignId) {
this.requireAdmin(playerId);
const campaign = this.campaignSummary(campaignId);
const claims = this.db.prepare(`SELECT cl.claimed_at, p.display_name FROM campaign_claims cl JOIN players p ON p.id = cl.player_id
WHERE cl.campaign_id = ? ORDER BY cl.claimed_at, cl.rowid`).all(campaignId).map((row) => ({ playerName: row.display_name, claimedAt: row.claimed_at }));
return { campaign, claims };
}
revokeCampaign(playerId, campaignId) {
this.requireAdmin(playerId);
this.database.transaction(() => {
this.campaignSummary(campaignId);
this.db.prepare("UPDATE campaigns SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL").run(this.now(), campaignId);
this.audit(playerId, "campaign_revoked", campaignId, {});
});
return { campaign: this.campaignSummary(campaignId) };
}
// Date d'expiration d'une campagne : null (sans expiration) ou un instant futur.
campaignExpiry(expiresAt) {
if (expiresAt == null) return null;
const expiry = Number(expiresAt);
if (!Number.isFinite(expiry) || expiry <= this.now()) fail(400, "CAMPAIGN_INVALID", "La date d’expiration doit être dans le futur.");
return expiry;
}
extendCampaign(playerId, campaignId, expiresAt) {
this.requireAdmin(playerId);
const expiry = this.campaignExpiry(expiresAt);
const result = this.db.prepare("UPDATE campaigns SET expires_at = ? WHERE id = ? AND revoked_at IS NULL").run(expiry, campaignId);
if (!result.changes) fail(404, "CAMPAIGN_NOT_FOUND", "Campagne introuvable ou révoquée.");
this.audit(playerId, "campaign_extended", campaignId, { expiresAt: expiry });
return { campaign: this.campaignSummary(campaignId) };
}
claimCampaign(playerId, rawCode) {
const code = String(rawCode || "").trim().toUpperCase();
let reward;
this.database.transaction(() => {
const row = this.db.prepare("SELECT * FROM campaigns WHERE code = ?").get(code);
if (!row || row.revoked_at || (row.expires_at != null && row.expires_at <= this.now())) fail(404, "CODE_INVALID", "Code invalide, expiré ou révoqué.");
if (this.db.prepare("SELECT 1 FROM campaign_claims WHERE campaign_id = ? AND player_id = ?").get(row.id, playerId)) fail(409, "CAMPAIGN_ALREADY_CLAIMED", "Vous avez déjà reçu cette récompense.");
const used = row.max_claims != null && this.db.prepare("SELECT COUNT(*) AS count FROM campaign_claims WHERE campaign_id = ?").get(row.id).count >= row.max_claims;
if (used) fail(409, "CODE_EXHAUSTED", "Ce code a atteint son nombre maximal d’utilisations.");
reward = JSON.parse(row.reward_json);
for (const item of reward.items) {
for (let copy = 0; copy < item.quantity; copy += 1) {
if (item.type === "card") {
const edition = this.index.editions.get(item.editionId);
if (!edition) fail(409, "REWARD_UNAVAILABLE", "Une carte de cette récompense n’existe plus dans le catalogue.");
this.addCard(playerId, edition.id);
} else {
const options = { rarityWeights: item.rarityWeights, guarantee: item.guarantee };
this.db.prepare("INSERT INTO gift_packs(id, player_id, campaign_id, collection_id, options_json, created_at) VALUES (?, ?, ?, ?, ?, ?)")
.run(randomUUID(), playerId, row.id, item.collectionId, JSON.stringify(options), this.now());
}
}
}
this.db.prepare("INSERT INTO campaign_claims(id, campaign_id, player_id, claimed_at) VALUES (?, ?, ?, ?)").run(randomUUID(), row.id, playerId, this.now());
this.audit(playerId, "campaign_claimed", row.id, { campaignName: row.name, reward });
});
return { reward, state: this.getState(playerId) };
}
audit(playerId, eventType, entityId, details) {
this.db.prepare("INSERT INTO audit_log(player_id, event_type, entity_id, details_json, created_at) VALUES (?, ?, ?, ?, ?)")
.run(playerId, eventType, entityId, JSON.stringify(details), this.now());
}
}

View file

@ -0,0 +1,35 @@
// Rôle : règles pures de la poussière d'étoiles (recyclage des doublons, barème de la boutique).
// Le serveur s'en sert aussi pour l'aperçu envoyé au client, qui correspond donc exactement au recyclage appliqué.
export const MAX_STARDUST_VALUE = 100_000;
export const MAX_OPENING_PRICE = 100_000;
// Doublons disponibles d'une carte : la quantité possédée moins l'exemplaire toujours conservé et les doublons réservés par un
// transfert en cours. Seuls ces doublons s'échangent, se donnent ou se recyclent.
export const spareQuantity = ({ quantity, reserved = 0 }) => Math.max(0, quantity - 1 - reserved);
// `collection` : [{ editionId, quantity, reserved }] ; `rarityOf(editionId)` renvoie la rareté de la carte.
// Sans `editionId`, prépare le recyclage de tous les doublons disponibles ; avec, d'un seul doublon de cette carte.
export function planRecycling(collection, { rarityOf, stardustValues, editionId = null }) {
const items = collection
.filter((entry) => !editionId || entry.editionId === editionId)
.map((entry) => {
const count = editionId ? Math.min(1, spareQuantity(entry)) : spareQuantity(entry);
return { editionId: entry.editionId, count, stardust: count * (stardustValues[rarityOf(entry.editionId)] ?? 0) };
})
.filter((item) => item.count > 0);
return { items, count: items.reduce((total, item) => total + item.count, 0), stardust: items.reduce((total, item) => total + item.stardust, 0) };
}
export function validateShopSetting({ stardustValues, openingPrice, shopPackPrice, shopPackShare } = {}, rarityIds) {
const valid = (value, max) => Number.isInteger(value) && value >= 0 && value <= max;
if (!stardustValues || typeof stardustValues !== "object" || Array.isArray(stardustValues)) return "Barème de poussière invalide.";
for (const rarityId of rarityIds) {
if (!valid(stardustValues[rarityId], MAX_STARDUST_VALUE)) return `Valeur invalide pour la rareté ${rarityId} : un entier entre 0 et ${MAX_STARDUST_VALUE.toLocaleString("fr-FR")}.`;
}
if (Object.keys(stardustValues).some((rarityId) => !rarityIds.includes(rarityId))) return "Rareté inconnue dans le barème.";
if (!valid(openingPrice, MAX_OPENING_PRICE) || openingPrice < 1) return `Prix d’une ouverture invalide : un entier entre 1 et ${MAX_OPENING_PRICE.toLocaleString("fr-FR")}.`;
if (!valid(shopPackPrice, MAX_OPENING_PRICE) || shopPackPrice < 1) return `Prix du paquet de la boutique invalide : un entier entre 1 et ${MAX_OPENING_PRICE.toLocaleString("fr-FR")}.`;
if (!valid(shopPackShare, 100)) return "Part des cartes de la boutique invalide : un entier entre 0 et 100.";
return null;
}