sokko-g/services/cards/api.js
Shinuwa 498e171bc3 Show a full reserve count on the Sokko TCG menu icon and remaining openings while opening a pack
A gold count now sits on the Sokko TCG menu icon while the opening reserve is
full, so players notice it from any page. A light reserve route keeps it up to
date outside the game, and the game page updates it with every state it gets.
The opening stage also lists the remaining openings, apart for the automatic
recharge and for openings bought one at a time, since the sidebar reserve is
hidden there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 23:16:47 +01:00

439 lines
22 KiB
JavaScript

// 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;
const MAINTENANCE_INTERVAL_MS = 24 * 60 * 60 * 1000;
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
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();
}
// Un cookie d'une autre application du domaine peut être mal encodé : il ne doit pas bloquer l'API.
function decodeCookiePart(value) {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
function parseCookies(req) {
return Object.fromEntries(String(req.headers.cookie || "").split(";").map((entry) => entry.trim()).filter(Boolean).map((entry) => {
const separator = entry.indexOf("=");
return [decodeCookiePart(entry.slice(0, separator)), decodeCookiePart(entry.slice(separator + 1))];
}));
}
// Avec __Host-, le navigateur refuse qu'une autre application du domaine pose ces cookies. Ce préfixe exige Secure et Path=/ :
// sans HTTPS, en développement, le nom reste donc nu.
function cookieName(name, secure) {
return secure ? `__Host-${name}` : name;
}
function cookie(name, value, secure, maxAge) {
return `${cookieName(name, secure)}=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? "; Secure" : ""}`;
}
function sessionCookie(value, secure, maxAge = 30 * 24 * 60 * 60) {
return cookie("sokkog_cards_session", value, secure, maxAge);
}
function stateCookie(value, secure, maxAge = 600) {
return cookie("sokkog_cards_oauth_state", value, secure, maxAge);
}
function oauthReturnCookie(value, secure, maxAge = 600) {
return cookie("sokkog_cards_oauth_return", value, secure, maxAge);
}
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);
if (!match) return null;
try {
return match.slice(1).map(decodeURIComponent);
} catch {
throw Object.assign(new Error("Adresse de requête invalide."), { status: 400, code: "INVALID_PATH" });
}
}
// Les compteurs ne valent que pour la minute en cours : ils sont tous oubliés à la suivante pour que la mémoire reste bornée.
export function createRateLimiter(now) {
const buckets = new Map();
let currentMinute = null;
const limiter = (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);
if (minute !== currentMinute) {
buckets.clear();
currentMinute = minute;
}
const count = (buckets.get(key) || 0) + 1;
buckets.set(key, count);
if (count > limit) throw Object.assign(new Error("Trop de tentatives. Réessayez dans quelques instants."), { status: 429, code: "RATE_LIMITED" });
};
limiter.bucketCount = () => buckets.size;
return limiter;
}
export function createCardsApiHandler({
projectRoot = resolve("."),
env = process.env,
// Un oubli de NODE_ENV ne doit jamais ouvrir le jeu ni la connexion factice : les deux se demandent explicitement.
enabled = bool(env.CARDS_ENABLED),
devAuth: requestedDevAuth = bool(env.CARDS_DEV_AUTH),
// Réservé au serveur E2E : cette option n'est pas lisible depuis l'environnement, une erreur de configuration ne peut donc pas l'activer.
allowProductionDevAuth = false,
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
} = {}) {
// Cette connexion accorde les droits administrateur à n'importe quel visiteur.
const devAuth = requestedDevAuth && (env.NODE_ENV !== "production" || allowProductionDevAuth);
if (requestedDevAuth && !devAuth) console.error("CARDS_DEV_AUTH is ignored in production.");
const configuredContact = String(env.CARDS_PRIVACY_CONTACT || "").trim();
const privacyContact = EMAIL_PATTERN.test(configuredContact) ? configuredContact : null;
const privacyController = String(env.CARDS_PRIVACY_CONTROLLER || "").trim() || null;
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.");
// La notice de confidentialité doit indiquer à qui s'adresser avant d'ouvrir le jeu à de vrais comptes.
if (env.NODE_ENV === "production" && !privacyContact) throw new TypeError("CARDS_PRIVACY_CONTACT must be a valid e-mail address when Sokko TCG is enabled in production.");
if (env.NODE_ENV === "production" && !privacyController) throw new TypeError("CARDS_PRIVACY_CONTROLLER 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" || String(env.CARDS_PUBLIC_ORIGIN || "").startsWith("https://");
const adminIds = new Set(String(env.CARDS_ADMIN_DISCORD_IDS || "").split(",").map((item) => item.trim()).filter(Boolean));
service?.syncAdmins(adminIds, { keepDevAdmin: devAuth });
service?.runMaintenance();
const maintenanceTimer = service && setInterval(() => {
try {
service.runMaintenance();
} catch (error) {
console.error(error);
}
}, MAINTENANCE_INTERVAL_MS);
maintenanceTimer?.unref();
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) {
// Seuls le chemin et les paramètres servent ici : ils ne doivent pas dépendre des en-têtes envoyés par le client.
let url;
try {
url = new URL(req.url || "/", "http://localhost");
} catch {
return false;
}
if (!url.pathname.startsWith("/api/cards")) return false;
try {
if (req.method === "GET" && url.pathname === "/api/cards/config") {
// Compteur séparé : chaque visite du site lit cette route, mais elle renvoie tout le catalogue.
rateLimit(req, "config", apiRateLimit * 2);
json(res, 200, {
enabled,
devAuth: enabled && devAuth,
discordConfigured: enabled && Boolean(env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET),
catalog: enabled ? publicCatalog(service.catalog) : null,
privacyContact: enabled ? privacyContact : null,
privacyController: enabled ? privacyController : 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[cookieName("sokkog_cards_session", secureCookies)]);
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[cookieName("sokkog_cards_oauth_return", secureCookies)]);
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[cookieName("sokkog_cards_oauth_state", secureCookies)]) {
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;
}
// Lue par le menu sur toutes les pages : un visiteur sans compte reçoit une réserve vide plutôt qu'une erreur.
if (req.method === "GET" && url.pathname === "/api/cards/reserve") {
json(res, 200, { recharge: session ? service.getReserve(session.player.id) : null });
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[cookieName("sokkog_cards_session", secureCookies)]);
res.setHeader("Set-Cookie", sessionCookie("", secureCookies, 0));
json(res, 200, { ok: true });
return true;
}
if (req.method === "DELETE" && url.pathname === "/api/cards/account") {
service.deleteAccount(session.player.id);
res.setHeader("Set-Cookie", sessionCookie("", secureCookies, 0));
json(res, 200, { ok: true });
return true;
}
if (req.method === "GET" && url.pathname === "/api/cards/state") {
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 = () => {
clearInterval(maintenanceTimer);
database?.close();
};
handler.service = service;
return handler;
}