Players kept finishing third or fourth: opponents were played better than their owners would (always the best runner, half of them with perfect boosts and no reaction time), and the Watchers recruited knowing the day's circuit, which players never see. - A player who already ran today now comes back as a ghost with their real race; other teams play like an attentive player (best runner, each teammate given in a zone of its best stat after a reaction delay). The Watchers recruit blind; only the strong one plays attentively. The administration counts the ghosts. - The rule that a boost keeps the value of the zone where it was given is now stated before and during the race. - A boosting teammate is greyed at once with "Élan donné", a 1.5 s bar and its locked value; the others dim while the player has to wait. - The result shows the place as a medal, the finish as lanes (with a gold silhouette at the best boosts), the three times, each boost placed on the circuit (dashed in the teammate's best stat when it was worth more elsewhere), a sentence per boost to place better and, when clearly faster, another runner. The best boosts are searched in the browser. - A development-only "Recourir (dev)" button erases the race and keeps the team. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
708 lines
38 KiB
JavaScript
708 lines
38 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 { createDailyImageRenderer } from "./daily-image.js";
|
|
import { createMirrorImageRenderer } from "./mirror-image.js";
|
|
import { DEFAULT_DESTINATIONS_PATH, loadExpeditionDestinations } from "./expedition-content.js";
|
|
import { createDiscordAlertSender, dispatchAlerts } from "./discord-alerts.js";
|
|
import { CardsService, DEV_DISCORD_ID } from "./service.js";
|
|
import { bool, createRateLimiter, json } from "../http.js";
|
|
|
|
export { createRateLimiter };
|
|
|
|
const JSON_LIMIT = 64 * 1024;
|
|
const DISCORD_TIMEOUT_MS = 10_000;
|
|
const MAINTENANCE_INTERVAL_MS = 24 * 60 * 60 * 1000;
|
|
// Les alertes Discord partent par lots : retours d'expédition et groupes ouverts arrivent au plus une demi-minute plus tard.
|
|
const ALERTS_INTERVAL_MS = 30_000;
|
|
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
|
|
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);
|
|
}
|
|
|
|
// Retour après la connexion Discord : une section du jeu, ou le lien direct d'une expédition (#/cards/expeditions/<id>).
|
|
function cardsReturnPath(value) {
|
|
return /^\/cards(?:\/admin(?:\/[a-z0-9-]{1,40}){0,2}|\/expeditions\/[a-z0-9-]{1,40}|\/[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" });
|
|
}
|
|
}
|
|
|
|
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"),
|
|
destinationsPath = DEFAULT_DESTINATIONS_PATH,
|
|
now = Date.now,
|
|
random,
|
|
fetchImpl = fetch,
|
|
devPerks = false,
|
|
apiRateLimit = 60,
|
|
// Connexions de développement par minute et par adresse ; les parcours E2E en enchaînent davantage.
|
|
devAuthRateLimit = 10,
|
|
// Envoi des alertes Discord ; par défaut, la route palico-bot de CARDS_DISCORD_ALERTS_URL avec la clé CARDS_DISCORD_ALERTS_KEY.
|
|
sendAlert = null
|
|
} = {}) {
|
|
// 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;
|
|
const alertsUrl = String(env.CARDS_DISCORD_ALERTS_URL || "").trim();
|
|
const alertsKey = String(env.CARDS_DISCORD_ALERTS_KEY || "").trim();
|
|
const alertSender = sendAlert || (alertsUrl && alertsKey ? createDiscordAlertSender({ url: alertsUrl, key: alertsKey, fetchImpl }) : 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);
|
|
const destinations = loadExpeditionDestinations(destinationsPath, catalog);
|
|
service = new CardsService({ database, catalog, now, random, devPerks, destinations, alerts: { available: Boolean(alertSender), publicOrigin: env.CARDS_PUBLIC_ORIGIN || null } });
|
|
}
|
|
const renderDailyImage = createDailyImageRenderer(join(projectRoot, "website", "public"));
|
|
const renderMirrorImage = createMirrorImageRenderer(join(projectRoot, "website", "public"));
|
|
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();
|
|
// Un seul passage à la fois : un envoi lent ne doit pas en lancer un second sur les mêmes messages.
|
|
let dispatching = false;
|
|
const runAlerts = async () => {
|
|
if (dispatching) return;
|
|
dispatching = true;
|
|
try {
|
|
await dispatchAlerts(service.expeditions, alertSender);
|
|
} catch (error) {
|
|
console.error(error);
|
|
} finally {
|
|
dispatching = false;
|
|
}
|
|
};
|
|
const alertsTimer = service && alertSender && setInterval(runAlerts, ALERTS_INTERVAL_MS);
|
|
alertsTimer?.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;
|
|
}
|
|
// Lue par le menu sur toutes les pages : compteur séparé, pour ne pas épuiser celui du jeu ;
|
|
// un visiteur sans compte reçoit une réserve vide plutôt qu'une erreur.
|
|
if (req.method === "GET" && url.pathname === "/api/cards/reserve") {
|
|
rateLimit(req, "reserve", apiRateLimit * 2);
|
|
const session = enabled ? service.getSession(parseCookies(req)[cookieName("sokkog_cards_session", secureCookies)]) : null;
|
|
json(res, 200, { recharge: session ? service.getReserve(session.player.id) : 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", devAuthRateLimit);
|
|
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[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/daily") {
|
|
json(res, 200, service.getDaily(session.player.id));
|
|
return true;
|
|
}
|
|
// L'illustration du jour passe par cette adresse fixe : ni son nom de fichier ni une redirection ne révèlent la carte,
|
|
// et seule la zone visible au zoom courant est envoyée tant que la partie dure.
|
|
if (req.method === "GET" && url.pathname === "/api/cards/daily/image") {
|
|
const image = await renderDailyImage(service.dailyImage(session.player.id));
|
|
res.writeHead(200, { "Content-Type": "image/webp", "Content-Length": image.length, "Cache-Control": "private, no-store", "X-Content-Type-Options": "nosniff" });
|
|
res.end(image);
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/daily/guesses") {
|
|
rateLimit(req, "daily-guess", 30);
|
|
const body = await readBody(req);
|
|
json(res, 200, service.guessDaily(session.player.id, { day: body.day, cardId: body.cardId }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/daily/reward") {
|
|
rateLimit(req, "daily-reward", 30);
|
|
const body = await readBody(req);
|
|
json(res, 200, service.chooseDailyReward(session.player.id, { day: body.day, choice: body.choice }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/daily/hints") {
|
|
rateLimit(req, "daily-hint", 30);
|
|
const body = await readBody(req);
|
|
json(res, 200, { daily: service.useDailyHint(session.player.id, { day: body.day, hint: body.hint }) });
|
|
return true;
|
|
}
|
|
if (req.method === "GET" && url.pathname === "/api/cards/team") {
|
|
json(res, 200, { team: service.team.view(session.player.id) });
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/team/recruit") {
|
|
rateLimit(req, "team-recruit", 30);
|
|
json(res, 200, service.team.startRecruitment(session.player.id, { day: (await readBody(req)).day }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/team/race/reset") {
|
|
json(res, 200, service.team.resetRaceForTests(session.player.id));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/team/reset") {
|
|
json(res, 200, service.team.resetForTests(session.player.id));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/team/reroll") {
|
|
rateLimit(req, "team-reroll", 60);
|
|
json(res, 200, service.team.rerollOffer(session.player.id, { offer: (await readBody(req)).offer }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/team/choose") {
|
|
rateLimit(req, "team-choose", 60);
|
|
json(res, 200, service.team.chooseCharacter(session.player.id, { cardId: (await readBody(req)).cardId }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/team/stars") {
|
|
rateLimit(req, "team-stars", 120);
|
|
json(res, 200, service.team.revealStar(session.player.id, { index: (await readBody(req)).index }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/team/heal") {
|
|
rateLimit(req, "team-heal", 60);
|
|
json(res, 200, service.team.healCompanion(session.player.id, { cardId: (await readBody(req)).cardId }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/team/keep") {
|
|
rateLimit(req, "team-keep", 60);
|
|
json(res, 200, service.team.keepCompanion(session.player.id, { cardId: (await readBody(req)).cardId }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/team/race") {
|
|
rateLimit(req, "race-start", 30);
|
|
const body = await readBody(req);
|
|
json(res, 200, service.team.startRace(session.player.id, { day: body.day, cardId: body.cardId }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/team/race/boosts") {
|
|
rateLimit(req, "race-boosts", 120);
|
|
json(res, 200, service.team.recordBoosts(session.player.id, { boosts: (await readBody(req)).boosts }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/team/race/finish") {
|
|
rateLimit(req, "race-finish", 60);
|
|
json(res, 200, service.team.finishRace(session.player.id, { boosts: (await readBody(req)).boosts }));
|
|
return true;
|
|
}
|
|
if (req.method === "PUT" && url.pathname === "/api/cards/admin/team/settings") {
|
|
json(res, 200, service.team.updateSettings(session.player.id, (await readBody(req)).settings));
|
|
return true;
|
|
}
|
|
if (req.method === "GET" && url.pathname === "/api/cards/mirror") {
|
|
json(res, 200, { mirror: service.mirror.view(session.player.id) });
|
|
return true;
|
|
}
|
|
// Image mélangée de la partie, dans l'état où elle est (ou en ordre avec `model=1`) ; `v` (nombre de coups) évite seulement de relire une ancienne image.
|
|
if (req.method === "GET" && url.pathname === "/api/cards/mirror/image") {
|
|
rateLimit(req, "mirror-image", 60);
|
|
const image = await renderMirrorImage(service.mirror.image(session.player.id, url.searchParams.get("mode"), { model: url.searchParams.get("model") === "1" }));
|
|
res.writeHead(200, { "Content-Type": "image/webp", "Content-Length": image.length, "Cache-Control": "private, no-store", "X-Content-Type-Options": "nosniff" });
|
|
res.end(image);
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/mirror/start") {
|
|
rateLimit(req, "mirror-start", 30);
|
|
const body = await readBody(req);
|
|
json(res, 200, service.mirror.start(session.player.id, { day: body.day, mode: body.mode }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/mirror/swap") {
|
|
rateLimit(req, "mirror-swap", 240);
|
|
const body = await readBody(req);
|
|
json(res, 200, service.mirror.swap(session.player.id, { day: body.day, mode: body.mode, from: body.from, to: body.to, moves: body.moves }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/mirror/help") {
|
|
rateLimit(req, "mirror-help", 60);
|
|
const body = await readBody(req);
|
|
json(res, 200, service.mirror.useHelp(session.player.id, { day: body.day, mode: body.mode, cardId: body.cardId, help: body.help, moves: body.moves, cell: body.cell }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/mirror/reset") {
|
|
json(res, 200, service.mirror.resetForTests(session.player.id));
|
|
return true;
|
|
}
|
|
if (req.method === "PUT" && url.pathname === "/api/cards/admin/mirror/settings") {
|
|
json(res, 200, service.mirror.updateSettings(session.player.id, (await readBody(req)).settings));
|
|
return true;
|
|
}
|
|
if (req.method === "GET" && url.pathname === "/api/cards/expeditions") {
|
|
json(res, 200, service.expeditions.getExpeditions(session.player.id));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/expeditions/preview") {
|
|
rateLimit(req, "expedition-preview", 120);
|
|
json(res, 200, service.expeditions.preview(session.player.id, await readBody(req)));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/expeditions") {
|
|
rateLimit(req, "expedition-start", 30);
|
|
const body = await readBody(req);
|
|
const requestKey = String(req.headers["idempotency-key"] || "");
|
|
json(res, 201, service.expeditions.createGroup(session.player.id, body, requestKey));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/progress/upgrade") {
|
|
const body = await readBody(req);
|
|
json(res, 200, service.expeditions.upgradeCard(session.player.id, { editionId: body.editionId, method: body.method, editionIds: body.editionIds ?? null }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/expeditions/atelier") {
|
|
json(res, 200, service.expeditions.craft(session.player.id, { editionIds: (await readBody(req)).editionIds }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/expeditions/bonus") {
|
|
json(res, 200, service.expeditions.addBonusDestination(session.player.id, { item: (await readBody(req)).item }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/equipment/engrave") {
|
|
const body = await readBody(req);
|
|
json(res, 200, service.expeditions.engrave(session.player.id, { editionId: body.editionId, tag: body.tag }));
|
|
return true;
|
|
}
|
|
if (req.method === "PUT" && url.pathname === "/api/cards/alerts") {
|
|
const body = await readBody(req);
|
|
json(res, 200, service.expeditions.setAlertPreferences(session.player.id, { groupOpened: body.groupOpened, expeditionReturned: body.expeditionReturned }));
|
|
return true;
|
|
}
|
|
if (req.method === "PUT" && url.pathname === "/api/cards/equipment") {
|
|
const body = await readBody(req);
|
|
json(res, 200, service.expeditions.equip(session.player.id, { editionId: body.editionId, slot: body.slot, equipmentEditionId: body.equipmentEditionId ?? null }));
|
|
return true;
|
|
}
|
|
if (req.method === "PUT" && url.pathname === "/api/cards/progress/plan") {
|
|
const body = await readBody(req);
|
|
json(res, 200, service.expeditions.setCardPlan(session.player.id, { editionId: body.editionId, plan: body.plan, allocation: body.allocation ?? null }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/shop/items") {
|
|
const body = await readBody(req);
|
|
json(res, 200, service.expeditions.buyShopItem(session.player.id, { item: body.item, count: body.count }));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/expeditions/starter-seen") {
|
|
json(res, 200, service.expeditions.markStarterSeen(session.player.id));
|
|
return true;
|
|
}
|
|
// Serveur Vite local : un joueur de test ouvre une expédition à rejoindre.
|
|
if (req.method === "POST" && url.pathname === "/api/cards/expeditions/test-group") {
|
|
json(res, 200, service.expeditions.openTestGroup(session.player.id));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/expeditions/reroll") {
|
|
json(res, 200, service.expeditions.rerollDestinations(session.player.id));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/eclats/convert") {
|
|
json(res, 200, service.expeditions.convertStardust(session.player.id, { eclats: (await readBody(req)).eclats }));
|
|
return true;
|
|
}
|
|
const expeditionGroup = routeMatch(url.pathname, /^\/api\/cards\/expeditions\/([^/]+)\/(join|join-preview|leave|depart|test-player)$/);
|
|
if (req.method === "POST" && expeditionGroup) {
|
|
const [expeditionId, action] = expeditionGroup;
|
|
if (action === "join") {
|
|
rateLimit(req, "expedition-join", 30);
|
|
const body = await readBody(req);
|
|
json(res, 200, service.expeditions.joinGroup(session.player.id, expeditionId, { editionId: body.editionId, ready: body.ready === true }));
|
|
} else if (action === "join-preview") {
|
|
rateLimit(req, "expedition-preview", 120);
|
|
const body = await readBody(req);
|
|
json(res, 200, service.expeditions.previewJoin(session.player.id, expeditionId, { editionId: body.editionId }));
|
|
} else if (action === "test-player") {
|
|
json(res, 200, service.expeditions.addTestPlayer(session.player.id, expeditionId));
|
|
} else {
|
|
json(res, 200, action === "leave" ? service.expeditions.leaveGroup(session.player.id, expeditionId) : service.expeditions.departGroup(session.player.id, expeditionId));
|
|
}
|
|
return true;
|
|
}
|
|
// Joueur inscrit à un groupe : sa carte, ou « Prêt ».
|
|
const expeditionMember = routeMatch(url.pathname, /^\/api\/cards\/expeditions\/([^/]+)\/member$/);
|
|
if (req.method === "PUT" && expeditionMember) {
|
|
const body = await readBody(req);
|
|
json(res, 200, service.expeditions.updateGroupMember(session.player.id, expeditionMember[0], { editionId: body.editionId ?? null, ready: body.ready ?? null }));
|
|
return true;
|
|
}
|
|
const expeditionRecall = routeMatch(url.pathname, /^\/api\/cards\/expeditions\/([^/]+)\/recall$/);
|
|
if (req.method === "POST" && expeditionRecall) {
|
|
json(res, 200, service.expeditions.recallExpedition(session.player.id, expeditionRecall[0]));
|
|
return true;
|
|
}
|
|
const expeditionClaim = routeMatch(url.pathname, /^\/api\/cards\/expeditions\/([^/]+)\/claim$/);
|
|
if (req.method === "POST" && expeditionClaim) {
|
|
json(res, 200, service.expeditions.claim(session.player.id, expeditionClaim[0]));
|
|
return true;
|
|
}
|
|
if (req.method === "PUT" && url.pathname === "/api/cards/admin/expeditions/settings") {
|
|
json(res, 200, service.expeditions.updateSettings(session.player.id, (await readBody(req)).settings));
|
|
return true;
|
|
}
|
|
const expeditionCancel = routeMatch(url.pathname, /^\/api\/cards\/admin\/expeditions\/([^/]+)\/cancel$/);
|
|
if (req.method === "POST" && expeditionCancel) {
|
|
json(res, 200, service.expeditions.cancel(session.player.id, expeditionCancel[0]));
|
|
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;
|
|
}
|
|
const mythicTuning = routeMatch(url.pathname, /^\/api\/cards\/admin\/catalog\/mythics\/([^/]+)\/tuning$/);
|
|
if (req.method === "PUT" && mythicTuning) {
|
|
const body = await readBody(req);
|
|
json(res, 200, service.setMythicTuning(session.player.id, mythicTuning[0], { intensity: body.intensity, level: body.level }));
|
|
return true;
|
|
}
|
|
const mythicFlare = routeMatch(url.pathname, /^\/api\/cards\/admin\/catalog\/mythics\/([^/]+)\/flare$/);
|
|
if (req.method === "PUT" && mythicFlare) {
|
|
const body = await readBody(req);
|
|
json(res, 200, service.setMythicFlare(session.player.id, mythicFlare[0], { id: body.id ?? null, motifId: body.motifId ?? null, paletteId: body.paletteId ?? null, scope: body.scope ?? null, intensity: body.intensity, level: body.level, count: body.count }));
|
|
return true;
|
|
}
|
|
const mythicFinish = routeMatch(url.pathname, /^\/api\/cards\/admin\/catalog\/mythics\/([^/]+)\/finish$/);
|
|
if (req.method === "PUT" && mythicFinish) {
|
|
json(res, 200, service.setMythicFinish(session.player.id, mythicFinish[0], (await readBody(req)).finishId));
|
|
return true;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/api/cards/recycle") {
|
|
const body = await readBody(req);
|
|
json(res, 200, service.recycleDuplicates(session.player.id, { editionId: body.editionId ?? null, maxRarity: body.maxRarity ?? "legendary" }));
|
|
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, { count: (await readBody(req)).count ?? 1 }));
|
|
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, dailyReward: body.dailyReward }));
|
|
return true;
|
|
}
|
|
if (req.method === "PUT" && url.pathname === "/api/cards/admin/recharge") {
|
|
const body = await readBody(req);
|
|
json(res, 200, service.updateRechargeSetting(session.player.id, { intervalMs: body.intervalMs, maxOpenings: body.maxOpenings }));
|
|
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);
|
|
clearInterval(alertsTimer);
|
|
database?.close();
|
|
};
|
|
handler.service = service;
|
|
handler.runAlerts = runAlerts;
|
|
return handler;
|
|
}
|