Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : UQO Éval — Le Grand Défi Immobilier8 * File : tests/security/fuites.test.ts9 * Module : tests10 * Repository : https://git.spboucher.ai/uqo-eval-jeux11 * Project Website : https://jeux.uqo-eval.app12 * Created : 2026-11-2513 * Last Modified : 2026-11-2514 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/**44 * Aucune fuite de la bonne réponse avant la soumission.45 *46 * On inspecte le JSON brut de toutes les réponses qu'un participant peut obtenir avant de répondre :47 * POST /sessions, GET /game/current (les 100 propriétés d'une partie), le champ `next` de chaque réponse,48 * /home, /competitions, /leaderboard et la reprise par code.49 */50import { afterAll, beforeAll, describe, expect, it } from "vitest";51import { createRng, hashSeed } from "../../packages/engine/src/index.ts";52import { Player, XRW, allKeys, closeDatabase, makeCompetition, openServer, oracle, resetGameData, sql, type App, type QuestionJson } from "../helpers/api.ts";5354let app: App;55let competitionId = "";56let player: Player;57let startBody = "";58/** Les 100 fiches reçues AVANT de répondre (la première par /game/current, les suivantes par `next`). */59const seen: { question: QuestionJson; raw: string; via: "current" | "next" }[] = [];60/** Ce que renvoie /game/current AVANT l'ouverture de chaque propriété, et la réponse à chaque /game/answer. */61const beforeOpen: string[] = [];62const answerBodies: { questionId: string; raw: string }[] = [];63const secrets = new Map<string, { sourceRef: string; correctPrice: number; correctId: string; imageUrls: string[]; snapshot: Record<string, unknown> }>();6465const FORBIDDEN_KEY = /^(is_?correct|correct|is_?right|right|answer|solution|correct_?(price|choice|choice_?id|rank|index|id)|price_?rank|rank|source_?(ref|uid|url|id)|source|url|href|mls|uid|external_?id|property_?id|assessment|price_?history|municipal_?taxes|annual_?revenue|lat_?exact|snapshot|context)$/i;6667function distanceM(lat1: number, lng1: number, lat2: number, lng2: number): number {68 const rad = Math.PI / 180;69 const a = Math.sin(((lat2 - lat1) * rad) / 2) ** 2 + Math.cos(lat1 * rad) * Math.cos(lat2 * rad) * Math.sin(((lng2 - lng1) * rad) / 2) ** 2;70 return 2 * 6_371_000 * Math.asin(Math.sqrt(a));71}7273beforeAll(async () => {74 await resetGameData();75 app = await openServer();76 competitionId = (await makeCompetition({ name: "Étanchéité", size: 100, seed: "etancheite" })).id;77 const rows = await sql<{ id: string; source_ref: string; correct_price: number; snapshot: Record<string, unknown>; correct_id: string; urls: string[] }[]>`78 select q.id, q.source_ref, q.correct_price, q.snapshot,79 (select c.id from question_choices c where c.question_id = q.id and c.is_correct) as correct_id,80 (select array_agg(i.source_url) from question_images i where i.question_id = q.id) as urls81 from questions q where q.competition_id = ${competitionId}`;82 for (const r of rows) secrets.set(r.id, { sourceRef: r.source_ref, correctPrice: r.correct_price, correctId: r.correct_id, imageUrls: r.urls, snapshot: r.snapshot });8384 player = new Player(app);85 const started = await player.rawStart({ displayName: "Curieuse Inspectrice", course: "IMM1033", competitionId });86 startBody = started.body;87 // On joue toute la partie en gardant, pour chaque propriété, le JSON reçu avant d'y répondre :88 // la réponse à POST /game/next (ouverture), relue une fois sur deux par GET /game/current.89 for (let i = 0; i < 100; i++) {90 beforeOpen.push((await player.current()).body);91 const opened = await player.next();92 const read = i % 2 ? await player.current() : opened;93 seen.push({ question: read.json().question, raw: read.body, via: i % 2 ? "current" : "next" });94 const q = seen[i]!.question;95 const truth = await oracle(q.id);96 const res = await player.answer(q.id, (i % 2 ? truth.correct : truth.wrong[i % 3]!).id);97 answerBodies.push({ questionId: q.id, raw: res.body });98 }99});100101afterAll(async () => {102 await app.close();103 await closeDatabase();104});105106describe("GET /game/current et champ `next` — structure", () => {107 it("a bien inspecté les 100 propriétés de la partie, chacune avant la réponse", () => {108 expect(seen).toHaveLength(100);109 expect(new Set(seen.map((s) => s.question.id)).size).toBe(100);110 expect(seen.filter((s) => s.via === "next")).toHaveLength(50);111 expect(seen.filter((s) => s.via === "current")).toHaveLength(50);112 expect(answerBodies).toHaveLength(100);113 });114115 it("avant l'ouverture, /game/current ne livre rien de la propriété à venir (ni fiche, ni choix, ni identifiant)", () => {116 expect(beforeOpen).toHaveLength(100);117 beforeOpen.forEach((raw, i) => {118 const body = JSON.parse(raw) as { question: unknown; timing: { deadline: string | null } };119 expect(body.question, `avant la propriété ${i + 1}`).toBeNull();120 expect(body.timing.deadline).toBeNull();121 expect(raw).not.toMatch(/"choices"|"card"|"images"|"price"/);122 const upcoming = seen[i]!.question;123 expect(raw.includes(upcoming.id)).toBe(false);124 for (const choice of upcoming.choices) expect(raw.includes(choice.id)).toBe(false);125 });126 });127128 it("la réponse à /game/answer ne contient plus la propriété suivante : ni `next`, ni `preload`, ni aucun identifiant à venir", () => {129 answerBodies.forEach(({ questionId, raw }, i) => {130 const body = JSON.parse(raw) as Record<string, unknown>;131 expect(Object.keys(body).sort()).toEqual(["chosenChoiceId", "completed", "correctChoiceId", "crowd", "feedback", "isCorrect", "replayed", "session", "timedOut"]);132 expect(questionId).toBe(seen[i]!.question.id);133 // aucune des propriétés restant à jouer n'y figure : identifiant, choix, photos134 for (const later of seen.slice(i + 1)) {135 expect(raw.includes(later.question.id), `réponse ${i + 1}`).toBe(false);136 for (const choice of later.question.choices) expect(raw.includes(choice.id)).toBe(false);137 for (const image of later.question.images as { id: string }[]) expect(raw.includes(image.id)).toBe(false);138 }139 });140 });141142 it("chaque choix n'a que `id` et `price` — aucun champ ne distingue le bon choix", () => {143 for (const { question } of seen) {144 expect(question.choices).toHaveLength(4);145 for (const choice of question.choices) {146 expect(Object.keys(choice).sort()).toEqual(["id", "price"]);147 expect(choice.id).toMatch(/^[0-9a-f-]{36}$/);148 expect(Number.isInteger(choice.price)).toBe(true);149 }150 }151 });152153 it("la question ne porte que les champs publics attendus", () => {154 for (const { question } of seen) {155 expect(Object.keys(question).sort()).toEqual(["card", "choices", "difficultyLabel", "id", "images", "number", "phase", "phaseName", "total"]);156 const card = question.card as Record<string, unknown>;157 expect(Object.keys(card).sort()).toEqual(["categoryLabel", "description", "details", "facts", "location", "municipality", "regionName", "sector", "subtype"]);158 for (const image of question.images as Record<string, unknown>[]) expect(Object.keys(image).sort()).toEqual(["alt", "id"]);159 for (const fact of [...(card.facts as Record<string, unknown>[]), ...(card.details as Record<string, unknown>[])]) expect(Object.keys(fact).sort()).toEqual(["key", "label", "value"]);160 if (card.location) expect(Object.keys(card.location as object).sort()).toEqual(["lat", "lng", "radiusM"]);161 }162 });163164 it("aucune clé interdite, à aucune profondeur (is_correct, isCorrect, correct, correctPrice, source_ref, price_rank…)", () => {165 for (const { question } of seen) {166 for (const key of allKeys(question)) expect(FORBIDDEN_KEY.test(key), `clé « ${key} »`).toBe(false);167 }168 });169170 it("le JSON brut de /game/current ne contient ni is_correct, ni isCorrect, ni correctPrice, ni source_ref", async () => {171 const fresh = await Player.start(app, { displayName: "Seconde Inspectrice", competitionId });172 const res = await fresh.current();173 expect(res.statusCode).toBe(200);174 expect(res.body).not.toMatch(/is_?correct|correct_?price|correct_?choice|source_?ref|source_?url|price_?rank|sourceUid|imageUrls|dedupeKeys/i);175 const body = res.json();176 expect(Object.keys(body).sort()).toEqual(["lapsed", "question", "session", "timing"]);177 expect(body.question).toBeNull();178 expect(Object.keys(body.timing).sort()).toEqual(["deadline", "limitSeconds", "serverNow"]);179 const opened = await fresh.next();180 expect(opened.body).not.toMatch(/is_?correct|correct_?price|correct_?choice|source_?ref|source_?url|price_?rank|sourceUid|imageUrls|dedupeKeys|served_?at|timed_?out/i);181 expect(opened.body.match(/correct/gi)).toHaveLength(1);182 expect(Object.keys(opened.json()).sort()).toEqual(["lapsed", "question", "session", "timing"]);183 // Seule occurrence de « correct » : le compteur de bonnes réponses de la session, connu du joueur (0 avant toute réponse).184 expect(Object.keys(body.session).sort()).toEqual(["answered", "bestStreak", "competitionId", "competitionName", "correct", "course", "displayName", "endsAt", "id", "mape", "mode", "status", "streak", "total"]);185 expect(body.session.correct).toBe(0);186 expect(res.body.match(/correct/gi)).toHaveLength(1);187 });188});189190describe("GET /game/current et champ `next` — contenu", () => {191 it("le prix réel n'apparaît qu'une fois : comme l'un des quatre choix, sans marque", () => {192 const UUID_LIKE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;193 /** Parcourt le JSON et relève chaque valeur — nombre ou texte — qui porte le montant `price` comme nombre isolé. */194 const occurrences = (value: unknown, price: number, path: string, out: string[]): string[] => {195 if (typeof value === "number") {196 if (value === price) out.push(path);197 } else if (typeof value === "string") {198 // Un identifiant opaque (UUID hexadécimal) n'est pas un montant : « 449000 » peut y figurer par pur hasard.199 if (!UUID_LIKE.test(value)) {200 const compact = value.replace(/[\s\u00a0\u202f]/g, "");201 if (new RegExp(`(^|[^0-9])${price}([^0-9]|$)`).test(compact)) out.push(`${path} = ${JSON.stringify(value.slice(0, 80))}`);202 }203 } else if (Array.isArray(value)) value.forEach((item, i) => occurrences(item, price, `${path}[${i}]`, out));204 else if (value && typeof value === "object") for (const [key, inner] of Object.entries(value)) occurrences(inner, price, `${path}.${key}`, out);205 return out;206 };207 for (const { question, raw } of seen) {208 const secret = secrets.get(question.id)!;209 expect(question.choices.filter((c) => c.price === secret.correctPrice)).toHaveLength(1);210 const found = occurrences(JSON.parse(raw), secret.correctPrice, "$", []);211 // une seule occurrence, et c'est le prix d'un des quatre choix212 expect(found, `question ${question.number}, prix ${secret.correctPrice} : ${found.join(" ; ")}`).toHaveLength(1);213 expect(found[0]).toMatch(/^\$\.question\.choices\[\d\]\.price$/);214 }215 });216217 it("ne contient jamais l'identifiant source de la propriété, ni celui d'aucune autre propriété de la banque", () => {218 const allRefs = [...secrets.values()].map((s) => s.sourceRef);219 for (const { question, raw } of seen) {220 expect(raw.includes(secrets.get(question.id)!.sourceRef)).toBe(false);221 }222 const everything = seen.map((s) => s.raw).join("\n");223 for (const ref of allRefs) expect(everything.includes(ref), ref).toBe(false);224 });225226 it("ne contient jamais l'URL d'origine d'une photographie, ni son domaine", () => {227 const hosts = new Set<string>();228 for (const { question, raw } of seen) {229 expect(raw).not.toMatch(/https?:\/\//);230 for (const url of secrets.get(question.id)!.imageUrls) {231 expect(raw.includes(url)).toBe(false);232 hosts.add(new URL(url).hostname);233 }234 }235 const everything = seen.map((s) => s.raw).join("\n");236 expect(hosts.size).toBeGreaterThan(0);237 for (const host of hosts) expect(everything.includes(host), host).toBe(false);238 });239240 it("ne contient ni l'évaluation municipale, ni les taxes, ni l'historique de prix, ni les revenus", () => {241 let checked = 0;242 for (const { question, raw } of seen) {243 const s = secrets.get(question.id)!.snapshot as { assessment: { total: number; land: number | null; building: number | null } | null; municipalTaxes: number | null; annualRevenue: number | null; priceHistory: { price: number }[] };244 const compact = raw.replace(/[\s ]/g, "");245 const values = [s.assessment?.total, s.assessment?.land, s.assessment?.building, s.annualRevenue, ...s.priceHistory.map((h) => h.price)]246 .filter((v): v is number => typeof v === "number" && v >= 10_000 && v !== secrets.get(question.id)!.correctPrice);247 for (const v of values) {248 // un montant ne peut apparaître que s'il coïncide avec l'un des trois prix fictifs249 if (question.choices.some((c) => c.price === v)) continue;250 // recherche du nombre entier isolé (« 89500 » ne doit pas être confondu avec « 689500 »)251 expect(new RegExp(`(^|\\D)${v}(\\D|$)`).test(compact), `question ${question.number} : ${v}`).toBe(false);252 checked += 1;253 }254 }255 expect(checked).toBeGreaterThan(100);256 });257258 it("ne contient jamais les coordonnées exactes de la propriété", () => {259 let located = 0;260 for (const { question, raw } of seen) {261 const s = secrets.get(question.id)!.snapshot as { lat: number | null; lng: number | null };262 const location = (question.card as { location: { lat: number; lng: number } | null }).location;263 if (s.lat === null || s.lng === null) {264 expect(location).toBeNull();265 continue;266 }267 located += 1;268 expect(location!.lat === s.lat && location!.lng === s.lng).toBe(false);269 // coordonnées précises (5 décimales ou plus) : leur écriture ne figure nulle part dans le JSON270 if ((String(s.lat).split(".")[1] ?? "").length >= 5) expect(raw.includes(String(s.lat))).toBe(false);271 if ((String(s.lng).split(".")[1] ?? "").length >= 5) expect(raw.includes(String(s.lng))).toBe(false);272 const d = distanceM(s.lat, s.lng, location!.lat, location!.lng);273 expect(d).toBeGreaterThanOrEqual(110);274 expect(d).toBeLessThanOrEqual(330);275 }276 expect(located).toBeGreaterThan(50);277 });278279 // Corrigé : le décalage est dérivé d'une graine secrète du serveur (hmac("emplacement:" + id), game.ts ligne 133).280 // Avant le correctif, le calcul ci-dessous (graine publique `loc:<id de la question>`) retrouvait 98 points sur 98 à moins de 25 m.281 it("le point affiché ne permet plus de retrouver l'emplacement exact à partir des seules données reçues", () => {282 let recovered = 0;283 let located = 0;284 const misses: number[] = [];285 for (const { question } of seen) {286 const location = (question.card as { location: { lat: number; lng: number } | null }).location;287 const truth = secrets.get(question.id)!.snapshot as { lat: number | null; lng: number | null };288 if (!location || truth.lat === null || truth.lng === null) continue;289 located += 1;290 // Tout ce qui suit n'utilise que des données publiques : question.id et question.card.location.291 for (const seed of [`loc:${question.id}`, question.id, `emplacement:${question.id}`]) {292 const rng = createRng(seed === question.id ? seed : hashSeed(seed));293 const angle = rng.range(0, 2 * Math.PI);294 const distance = rng.range(120, 320);295 const guessLat = location.lat - (distance * Math.cos(angle)) / 111_320;296 const guessLng = location.lng - (distance * Math.sin(angle)) / (111_320 * Math.cos((guessLat * Math.PI) / 180));297 const miss = distanceM(truth.lat, truth.lng, guessLat, guessLng);298 misses.push(miss);299 if (miss < 25) recovered += 1;300 }301 }302 expect(located).toBeGreaterThan(50);303 // Un décalage deviné au hasard tombe à moins de 25 m du vrai point moins d'une fois sur cent : on tolère 5 % de coïncidences.304 expect(recovered).toBeLessThanOrEqual(Math.ceil(located * 3 * 0.05));305 // … et en moyenne la « reconstitution » manque le vrai point de plus de 150 m (deux décalages indépendants).306 expect(misses.reduce((x, y) => x + y, 0) / misses.length).toBeGreaterThan(150);307 });308309 it("le décalage reste stable d'un appel à l'autre pour une même propriété (pas de triangulation par moyenne)", async () => {310 const other = await Player.start(app, { displayName: "Triangulatrice Patiente", competitionId });311 const mine = (await other.question()) as QuestionJson;312 const first = seen.find((s) => s.question.id === mine.id)!;313 expect((mine.card as { location: unknown }).location).toEqual((first.question.card as { location: unknown }).location);314 const again = await other.question();315 expect((again.card as { location: unknown }).location).toEqual((mine.card as { location: unknown }).location);316 });317318 it("le texte alternatif des photos et les libellés ne trahissent ni prix ni source", () => {319 for (const { question } of seen) {320 for (const image of question.images as { id: string; alt: string }[]) {321 expect(image.id).toMatch(/^[0-9a-f-]{36}$/);322 expect(image.alt).not.toMatch(/\$|https?:|centris|duproprio|remax|royal ?lepage|sutton/i);323 }324 }325 });326327 it("l'identifiant du bon choix n'est pas reconnaissable à son rang parmi les quatre identifiants (χ², 3 ddl, α = 0,001)", async () => {328 const counts = [0, 0, 0, 0];329 for (const [questionId, secret] of secrets) {330 const truth = await oracle(questionId);331 const sorted = truth.choices.map((c) => c.id).sort();332 counts[sorted.indexOf(secret.correctId)]! += 1;333 }334 const chi2 = counts.reduce((acc, c) => acc + (c - 25) ** 2 / 25, 0);335 expect(counts.reduce((a, b) => a + b, 0)).toBe(100);336 expect(chi2).toBeLessThan(16.266);337 });338339 it("la position affichée du bon choix varie d'une propriété à l'autre (aucune position ne dépasse 45 %)", () => {340 const counts = [0, 0, 0, 0];341 for (const { question } of seen) counts[question.choices.findIndex((c) => c.id === secrets.get(question.id)!.correctId)]! += 1;342 expect(Math.max(...counts)).toBeLessThanOrEqual(45);343 expect(Math.min(...counts)).toBeGreaterThanOrEqual(10);344 });345});346347describe("POST /sessions, reprise, /home, /competitions, /leaderboard", () => {348 const SECRET_WORDS = /is_?correct|correct_?price|correct_?choice|source_?ref|source_?url|price_?rank|sourceUid|imageUrls|dedupeKeys|snapshot|token_hash|resume_code_hash|order_seed|ip_hash|access_code|accessCode/i;349350 function expectNoBankSecret(raw: string): void {351 expect(raw).not.toMatch(SECRET_WORDS);352 expect(raw).not.toMatch(/https?:\/\/(?!tiles\.openfreemap\.org)/);353 for (const secret of secrets.values()) {354 expect(raw.includes(secret.sourceRef)).toBe(false);355 expect(raw.includes(secret.correctId)).toBe(false);356 }357 }358359 it("la réponse à POST /sessions ne contient que la session et le code de reprise", () => {360 const body = JSON.parse(startBody) as Record<string, unknown>;361 expect(Object.keys(body).sort()).toEqual(["resumeCode", "session"]);362 expect(Object.keys(body.session as object).sort()).toEqual(["answered", "bestStreak", "competitionId", "competitionName", "correct", "course", "displayName", "endsAt", "id", "mape", "mode", "status", "streak", "total"]);363 expect((body.session as { correct: number }).correct).toBe(0);364 expectNoBankSecret(startBody);365 // aucune question, aucun choix, aucun jeton dans le corps : le jeton ne voyage que dans le témoin HttpOnly366 expect(startBody).not.toMatch(/"choices"|"question"|"token"/);367 expect(startBody).not.toContain(player.cookie.split("=")[1]!);368 });369370 it("la reprise par code ne renvoie que la session", async () => {371 const other = await Player.start(app, { displayName: "Reprise Discrète", competitionId });372 const res = await app.inject({ method: "POST", url: "/api/v1/sessions/resume", headers: XRW, payload: { resumeCode: other.resumeCode } });373 expect(res.statusCode).toBe(200);374 expect(Object.keys(res.json())).toEqual(["session"]);375 expectNoBankSecret(res.body);376 expect(res.body).not.toContain(other.resumeCode);377 });378379 it.each(["/api/v1/home", "/api/v1/competitions", "/api/v1/leaderboard"])("GET %s ne contient aucune clé ni valeur sensible", async (url) => {380 const res = await app.inject({ method: "GET", url });381 expect(res.statusCode).toBe(200);382 expectNoBankSecret(res.body);383 for (const key of allKeys(res.json())) expect(/^(is_?correct|correct|correct_?price|source_?ref|price_?rank|price|prices|choices|snapshot)$/i.test(key), `clé « ${key} »`).toBe(false);384 for (const secret of secrets.values()) expect(res.body.includes(String(secret.correctPrice)), `prix ${secret.correctPrice}`).toBe(false);385 });386387 it("GET /competitions/:id et GET /leaderboard/:id ne contiennent aucune donnée de la banque", async () => {388 for (const url of [`/api/v1/competitions/${competitionId}`, `/api/v1/leaderboard/${competitionId}`]) {389 const res = await app.inject({ method: "GET", url });390 expect(res.statusCode).toBe(200);391 expectNoBankSecret(res.body);392 for (const key of allKeys(res.json())) expect(/^(is_?correct|correct_?price|source_?ref|price_?rank|price|prices|choices|snapshot|questions)$/i.test(key), `clé « ${key} »`).toBe(false);393 }394 });395396 it("/home n'expose que des identifiants opaques de photos, jamais de propriété ni d'URL", async () => {397 const home = (await app.inject({ method: "GET", url: "/api/v1/home" })).json();398 expect(Array.isArray(home.showcase)).toBe(true);399 for (const id of home.showcase) expect(id).toMatch(/^[0-9a-f-]{36}$/);400 expect(home.poolSize).toBeGreaterThan(1_000);401 expect(JSON.stringify(home.competitions)).not.toMatch(/seed|config|accessCode|notes/);402 });403});404405describe("Aucune fuite par les erreurs ou les routes annexes", () => {406 let fresh: Player;407 let current: QuestionJson;408409 beforeAll(async () => {410 fresh = await Player.start(app, { displayName: "Fouineuse Obstinée", competitionId });411 current = await fresh.question();412 });413414 it("une soumission refusée (mauvaise question, choix invalide, corps invalide) ne révèle rien", async () => {415 const [later] = await sql<{ question_id: string }[]>`select question_id from game_session_questions where session_id = ${fresh.sessionId} and idx = 40`;416 const laterTruth = await oracle(later!.question_id);417 const attempts = [418 await fresh.answer(later!.question_id, laterTruth.wrong[0]!.id),419 await fresh.answer(current.id, laterTruth.correct.id),420 await fresh.answer(current.id, "00000000-0000-4000-8000-000000000000"),421 await app.inject({ method: "POST", url: "/api/v1/game/answer", headers: fresh.headers, payload: { questionId: current.id } }),422 ];423 expect(attempts.map((r) => r.statusCode)).toEqual([409, 400, 400, 400]);424 const truth = await oracle(current.id);425 for (const res of attempts) {426 expect(Object.keys(res.json())).toEqual(["error"]);427 expect(res.body).not.toMatch(/correct|feedback|price/i);428 expect(res.body.includes(truth.correct.id)).toBe(false);429 expect(res.body.includes(laterTruth.correct.id)).toBe(false);430 }431 const [row] = await sql<{ answered: number }[]>`select answered from game_sessions where id = ${fresh.sessionId}`;432 expect(row!.answered).toBe(0);433 });434435 it("résultats, rapport, révision et signalement sont fermés avant la réponse", async () => {436 for (const url of ["/api/v1/results/me", "/api/v1/results/me/analytics", "/api/v1/results/me/review", "/api/v1/results/me/review?erreurs=1"]) {437 const res = await fresh.get(url);438 expect(res.statusCode, url).toBe(409);439 expect(res.body).not.toMatch(/isCorrect|correctPrice|choices/);440 }441 const flag = await app.inject({ method: "POST", url: "/api/v1/game/flag", headers: fresh.headers, payload: { questionId: current.id, reason: "Je veux voir la réponse" } });442 expect(flag.statusCode).toBe(403);443 });444445 it("le service de photos ne révèle pas l'URL d'origine et refuse les identifiants ou largeurs invalides", async () => {446 const imageId = (current.images as { id: string }[])[0]!.id;447 for (const url of [`/img/${imageId}/123`, `/img/${imageId}/original`, "/img/pas-un-uuid/960", "/img/00000000-0000-4000-8000-000000000000/960", `/img/${imageId}/960/source`]) {448 const res = await app.inject({ method: "GET", url });449 expect(res.statusCode, url).toBe(404);450 expect(res.body).not.toMatch(/https?:\/\//);451 expect(res.headers.location).toBeUndefined();452 }453 });454455 it("aucune route publique ne liste les questions, les choix ou les réponses d'une compétition", async () => {456 for (const url of [457 `/api/v1/competitions/${competitionId}/questions`, `/api/v1/questions/${current.id}`, `/api/v1/questions/${current.id}/choices`,458 `/api/v1/game/answer`, `/api/v1/game/answers`, `/api/v1/competitions/${competitionId}/bank`, `/api/v1/sessions/${fresh.sessionId}`,459 ]) {460 const res = await app.inject({ method: "GET", url, headers: fresh.headers });461 expect(res.statusCode, url).toBe(404);462 }463 });464465 it("après la réponse seulement, le serveur révèle le bon choix", async () => {466 const truth = await oracle(current.id);467 const res = await fresh.answer(current.id, truth.wrong[0]!.id);468 expect(res.statusCode).toBe(200);469 expect(res.json().correctChoiceId).toBe(truth.correct.id);470 expect(res.json().feedback.correctPrice).toBe(truth.correctPrice);471 // … et rien sur la propriété suivante : elle n'apparaît qu'à son ouverture, sans marque472 expect(res.json()).not.toHaveProperty("next");473 const [upcoming] = await sql<{ question_id: string }[]>`select question_id from game_session_questions where session_id = ${fresh.sessionId} and idx = 1`;474 expect(res.body.includes(upcoming!.question_id)).toBe(false);475 const next = await fresh.question();476 expect(next.id).toBe(upcoming!.question_id);477 for (const key of allKeys(next)) expect(FORBIDDEN_KEY.test(key), key).toBe(false);478 });479});480481describe("Limites connues (choix du propriétaire : pas d'authentification des participants)", () => {482 // LIMITE CONNUE, NON CORRIGÉE PAR CHOIX. L'unique verrou d'une compétition ouverte aux externes est le nom : une483 // première partie sous un nom d'emprunt recueille le `correctChoiceId` de chaque propriété (identifiants communs à484 // tous), puis la vraie partie se joue sans faute. Ce test décrit le comportement actuel ; il échouera le jour où une485 // parade sera ajoutée (identifiants de choix propres à chaque partie, par exemple) et devra alors être inversé.486 it("une partie jouée sous un autre nom donne aujourd'hui toutes les réponses de sa propre partie (8 sur 8)", async () => {487 const small = await makeCompetition({ name: "Seconde identité", size: 8, seed: "seconde-identite" });488 const scout = await Player.start(app, { displayName: "Nom d'emprunt", competitionId: small.id });489 const learned = new Map<string, string>();490 for (let i = 0; i < 8; i++) {491 const q = await scout.question();492 const body: { correctChoiceId: string } = (await scout.answer(q.id, q.choices[0]!.id)).json();493 learned.set(q.id, body.correctChoiceId);494 }495 expect(learned.size).toBe(8);496 const real = await Player.start(app, { displayName: "Vraie Identité", competitionId: small.id });497 let last: { session: { correct: number; status: string } } | null = null;498 for (let i = 0; i < 8; i++) {499 const current = await real.question();500 last = (await real.answer(current.id, learned.get(current.id)!)).json() as { session: { correct: number; status: string } };501 }502 expect(last!.session).toMatchObject({ correct: 8, status: "completed" });503 const board = (await app.inject({ method: "GET", url: `/api/v1/leaderboard/${small.id}` })).json();504 expect(board.rows[0]).toMatchObject({ displayName: "Vraie Identité", rank: 1, correct: 8 });505 });506507 // LIMITE CONNUE. Le classement public porte l'identifiant de partie de chaque participant. Seul, il n'ouvre rien508 // (voir tests/security/acces-et-injections.test.ts) : c'est la moitié publique du couple identifiant + témoin.509 it("le classement public expose l'identifiant de partie de chaque participant, qui ne donne aucun accès à lui seul", async () => {510 const board = (await app.inject({ method: "GET", url: `/api/v1/leaderboard/${competitionId}` })).json();511 expect(board.rows.length).toBeGreaterThan(0);512 for (const row of board.rows as { sessionId: string }[]) {513 expect(row.sessionId).toMatch(/^[0-9a-f-]{36}$/);514 expect((await app.inject({ method: "GET", url: "/api/v1/results/me", headers: { "x-game": row.sessionId } })).statusCode).toBe(401);515 }516 });517});518