Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : UQO Éval — Le Grand Défi Immobilier8 * File : apps/api/src/server.ts9 * Module : api10 * 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/** UQO ÉVAL — Le Grand Défi Immobilier · serveur HTTP (API + interface). */44import fs from "node:fs";45import path from "node:path";46import compress from "@fastify/compress";47import cookie from "@fastify/cookie";48import rateLimit from "@fastify/rate-limit";49import fastifyStatic from "@fastify/static";50import Fastify, { type FastifyRequest } from "fastify";51import { ZodError, z } from "zod";52import { CATEGORIES, CATEGORY_LABELS, PRICE_DISCLAIMER, REGIONS, TITLES } from "@jeux/engine";53import { registerAdmin } from "./admin.ts";54import { getOrCreateDaily, todayInMontreal } from "./bank.ts";55import { config } from "./config.ts";56import { migrate, sql } from "./db.ts";57import { TRAINING_SIZES, currentState, findSessionByToken, flagQuestion, openNextQuestion, resumeByCode, startSession, submitAnswer, type SessionRow } from "./game.ts";58import { IMAGE_WIDTHS, imageFile, type ImageWidth } from "./images.ts";59import { subscribe } from "./live.ts";60import { analyticsFor, leaderboard, resultsFor, reviewFor } from "./results.ts";61import { HttpError, hmac } from "./util.ts";6263const VERSION = "1.0.0";64const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;6566const cookieName = (sessionId: string): string => `gdi_${sessionId.slice(0, 8)}`;6768export async function buildServer() {69 const app = Fastify({70 logger: {71 level: config.logLevel,72 redact: ["req.headers.cookie", "req.headers['x-admin-key']"],73 // Ni les paramètres d'URL (clé d'administration, code de compétition) ni l'adresse IP ne sont journalisés.74 serializers: { req: (request) => ({ method: request.method, url: request.url.split("?")[0] }) },75 },76 // Seuls la passerelle (réseau privé) et la boucle locale peuvent déclarer l'adresse du client.77 trustProxy: (process.env.TRUSTED_PROXIES ?? "127.0.0.1,::1,10.67.0.0/16").split(",").map((s) => s.trim()).filter(Boolean),78 bodyLimit: 64 * 1024,79 });8081 await app.register(cookie);82 await app.register(compress, { threshold: 1024 });83 await app.register(rateLimit, {84 max: Number(process.env.RATE_LIMIT_MAX ?? 6000),85 timeWindow: "1 minute",86 errorResponseBuilder: () => ({ statusCode: 429, error: { code: "rate_limited", message: "Trop de requêtes. Patientez un instant." } }),87 });8889 app.addHook("onSend", async (request, reply) => {90 reply.header("x-content-type-options", "nosniff");91 reply.header("referrer-policy", "same-origin");92 reply.header("x-frame-options", "DENY");93 reply.header("permissions-policy", "camera=(), microphone=(), geolocation=()");94 if (config.isProduction) reply.header("strict-transport-security", "max-age=31536000; includeSubDomains");95 reply.header(96 "content-security-policy",97 "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https://tiles.openfreemap.org; " +98 "connect-src 'self' https://tiles.openfreemap.org; font-src 'self' data:; worker-src 'self' blob:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'",99 );100 if (request.url.startsWith("/api/")) reply.header("cache-control", "no-store");101 });102103 app.setErrorHandler((error: unknown, request, reply) => {104 if (error instanceof HttpError) {105 return reply.status(error.status).send({ error: { code: error.code, message: error.message } });106 }107 if (error instanceof ZodError) {108 const first = error.issues[0];109 return reply.status(400).send({ error: { code: "invalid_request", message: first?.message && !/^(Required|Invalid|Expected)/.test(first.message) ? first.message : "Requête invalide." } });110 }111 const e = error as { statusCode?: number; code?: string; message?: string; error?: unknown };112 if (e.statusCode === 429) return reply.status(429).send({ error: e.error ?? { code: "rate_limited", message: "Trop de requêtes. Patientez un instant." } });113 if (e.statusCode && e.statusCode < 500) {114 return reply.status(e.statusCode).send({ error: { code: "bad_request", message: "Requête invalide." } });115 }116 if (e.code === "22P02") return reply.status(400).send({ error: { code: "invalid_request", message: "Identifiant invalide." } });117 request.log.error({ err: error }, "erreur interne");118 return reply.status(500).send({ error: { code: "internal", message: "Une erreur est survenue. Réessayez dans un instant." } });119 });120121 /** Partie authentifiée par le témoin HttpOnly associé à l'identifiant transmis dans `x-game`. */122 async function requireSession(request: FastifyRequest): Promise<SessionRow> {123 const id = request.headers["x-game"];124 if (typeof id !== "string" || !UUID.test(id)) throw new HttpError(401, "no_session", "Aucune partie en cours sur cet appareil.");125 const token = request.cookies[cookieName(id)];126 const session = token ? await findSessionByToken(id, token) : null;127 if (!session) throw new HttpError(401, "no_session", "Partie introuvable sur cet appareil. Utilisez votre code de reprise.");128 return session;129 }130131 /** Les requêtes de modification exigent l'en-tête `x-requested-with: gdi`, qu'un site tiers ne peut pas envoyer : protection CSRF. */132 function requireCustomHeader(request: FastifyRequest): void {133 if (request.headers["x-requested-with"] !== "gdi") throw new HttpError(403, "csrf", "Requête refusée.");134 }135136 const cookieOptions = { path: "/", httpOnly: true, sameSite: "lax" as const, secure: config.isProduction, maxAge: 60 * 60 * 24 * 120 };137138 app.get("/api/v1/health", async (_request, reply) => {139 try {140 await sql`select 1`;141 return { status: "ok", version: VERSION, database: "ok", uptime: Math.round(process.uptime()) };142 } catch {143 return reply.status(503).send({ status: "degraded", version: VERSION, database: "down" });144 }145 });146147 async function publicCompetitions() {148 const rows = await sql<{149 id: string; name: string; status: string; size: number; starts_at: Date | null; ends_at: Date | null; access_code: string | null;150 courses: string[]; allow_external: boolean; participants: number; finished: number; prizes: { amounts: number[]; label: string } | null;151 }[]>`152 select c.id, c.name, c.status, c.size, c.starts_at, c.ends_at, c.access_code, c.courses, c.allow_external, c.config->'prizes' as prizes,153 (select count(*)::int from game_sessions s where s.competition_id = c.id and s.status in ('in_progress', 'completed')) as participants,154 (select count(*)::int from game_sessions s where s.competition_id = c.id and s.status = 'completed') as finished155 from competitions c where c.mode = 'official' and c.status in ('published', 'closed')156 order by (c.status = 'published') desc, coalesce(c.published_at, c.created_at) desc limit 30`;157 const now = Date.now();158 return rows.map((c) => ({159 id: c.id, name: c.name, size: c.size, startsAt: c.starts_at, endsAt: c.ends_at, needsCode: Boolean(c.access_code),160 courses: c.courses, allowExternal: c.allow_external, participants: c.participants, finished: c.finished, prizes: c.prizes ?? null,161 state:162 c.status === "closed" || (c.ends_at && now > c.ends_at.getTime()) ? ("terminee" as const)163 : c.starts_at && now < c.starts_at.getTime() ? ("a-venir" as const) : ("ouverte" as const),164 }));165 }166167 app.get("/api/v1/competitions", async () => publicCompetitions());168169 app.get<{ Params: { id: string } }>("/api/v1/competitions/:id", async (request) => {170 const found = (await publicCompetitions()).find((c) => c.id === request.params.id);171 if (!found) throw new HttpError(404, "competition_not_found", "Compétition introuvable.");172 return found;173 });174175 app.get("/api/v1/home", async () => {176 const competitions = await publicCompetitions();177 const open = competitions.find((c) => c.state === "ouverte") ?? null;178 const showcase = open179 ? await sql<{ id: string }[]>`180 select i.id from question_images i join questions q on q.id = i.question_id181 where q.competition_id = ${open.id} and i.position = 0 and i.status = 'ok' and i.width >= 1200 and i.width > i.height order by md5(i.id::text || ${todayInMontreal()}) limit 9`182 : await sql<{ id: string }[]>`183 select i.id from question_images i where i.position = 0 and i.status = 'ok' and i.width >= 1200 and i.width > i.height order by i.checked_at desc nulls last limit 9`;184 const today = todayInMontreal();185 const [daily] = await sql<{ id: string; players: number }[]>`186 select c.id, (select count(*)::int from game_sessions s where s.competition_id = c.id and s.status = 'completed') as players187 from competitions c where c.daily_date = ${today}`;188 const [pool] = await sql<{ n: number }[]>`select count(*)::int as n from properties where eligible and active`;189 return {190 competitions,191 featured: open,192 daily: { date: today, competitionId: daily?.id ?? null, players: daily?.players ?? 0 },193 showcase: showcase.map((s) => s.id),194 poolSize: pool!.n,195 trainingSizes: TRAINING_SIZES,196 freeTrialSize: 30,197 hasRoster: (await sql<{ n: number }[]>`select count(*)::int as n from roster_entries`)[0]!.n > 0,198 categories: CATEGORIES.map((key) => ({ key, label: CATEGORY_LABELS[key] })),199 regions: Object.entries(REGIONS).map(([code, name]) => ({ code, name })),200 titles: TITLES,201 disclaimer: PRICE_DISCLAIMER,202 noticeVersion: config.noticeVersion,203 leaderboardEnabled: config.publicLeaderboard,204 };205 });206207 /**208 * Liste de classe d'une compétition : noms à choisir dans le menu. Si la compétition209 * est protégée par un code d'accès, la liste n'est remise qu'avec ce code.210 */211 app.get<{ Params: { id: string }; Querystring: { code?: string } }>("/api/v1/competitions/:id/roster", { config: { rateLimit: { max: 600, timeWindow: "1 minute" } } }, async (request) => {212 if (!UUID.test(request.params.id)) throw new HttpError(400, "invalid_request", "Identifiant invalide.");213 const [competition] = await sql<{ id: string; courses: string[]; access_code: string | null; mode: string; status: string }[]>`214 select id, courses, access_code, mode, status from competitions where id = ${request.params.id}`;215 if (!competition || competition.mode !== "official" || competition.status !== "published") {216 throw new HttpError(404, "competition_not_found", "Compétition introuvable.");217 }218 if (competition.access_code && competition.access_code.trim().toUpperCase() !== (request.query.code ?? "").trim().toUpperCase()) {219 return { locked: true, groups: [] };220 }221 const rows = await sql<{ id: string; course: string; display_name: string; taken: boolean; hors_concours: boolean }[]>`222 select r.id, r.course, r.display_name, not r.prize_eligible as hors_concours,223 exists (select 1 from game_sessions s where s.competition_id = ${competition.id} and s.name_key = r.name_key224 and s.status in ('in_progress', 'completed', 'excluded')) as taken225 from roster_entries r where r.course = any(${[...competition.courses, "ENSEIGNANT"]}) order by r.course, r.display_name`;226 return {227 locked: false,228 groups: [...competition.courses, "ENSEIGNANT"]229 .map((course) => ({ course, students: rows.filter((r) => r.course === course).map((r) => ({ id: r.id, name: r.display_name, taken: r.taken, horsConcours: r.hors_concours })) }))230 .filter((g) => g.students.length > 0),231 };232 });233234 const startSchema = z.object({235 displayName: z.string().max(80).default(""),236 rosterId: z.string().uuid().optional(),237 course: z.enum(["IMM1003", "IMM1033"]).nullable().default(null),238 mode: z.enum(["official", "training", "daily"]),239 competitionId: z.string().uuid().optional(),240 size: z.number().int().optional(),241 accessCode: z.string().max(40).optional(),242 training: z.object({243 categories: z.array(z.enum(CATEGORIES)).max(8).optional(),244 regionCodes: z.array(z.string().regex(/^\d{2}$/)).max(17).optional(),245 fixedDifficulty: z.enum(["initiation", "intermediaire", "avance", "expert"]).optional(),246 }).optional(),247 consent: z.boolean(),248 });249250 app.post("/api/v1/sessions", { config: { rateLimit: { max: Number(process.env.RATE_LIMIT_SESSIONS ?? 300), timeWindow: "10 minutes" } } }, async (request, reply) => {251 requireCustomHeader(request);252 const body = startSchema.parse(request.body);253 const result = await startSession({ ...body, ipHash: hmac(`ip:${request.ip}`).slice(0, 16) });254 reply.setCookie(cookieName(result.session.id), result.token, cookieOptions);255 return { session: result.session, resumeCode: result.resumeCode };256 });257258 app.post("/api/v1/sessions/resume", { config: { rateLimit: { max: Number(process.env.RATE_LIMIT_RESUME ?? 60), timeWindow: "10 minutes" } } }, async (request, reply) => {259 requireCustomHeader(request);260 const { resumeCode } = z.object({ resumeCode: z.string().min(8).max(40) }).parse(request.body);261 const result = await resumeByCode(resumeCode);262 reply.setCookie(cookieName(result.session.id), result.token, cookieOptions);263 return { session: result.session };264 });265266 app.get("/api/v1/game/current", async (request) => currentState(await requireSession(request)));267268 /** Ouvre la propriété suivante et démarre son chrono. */269 app.post("/api/v1/game/next", {270 config: { rateLimit: { max: Number(process.env.RATE_LIMIT_ANSWERS ?? 90), timeWindow: "1 minute", keyGenerator: (request: FastifyRequest) => `n:${String(request.headers["x-game"] ?? request.ip)}` } },271 }, async (request) => {272 const session = await requireSession(request);273 return openNextQuestion(session.id);274 });275276 // `choiceId: null` déclare l'expiration du délai (refusée tant que le temps n'est pas écoulé).277 const answerSchema = z.object({ questionId: z.string().uuid(), choiceId: z.string().uuid().nullable(), idempotencyKey: z.string().min(8).max(80) });278279 app.post("/api/v1/game/answer", {280 // Limite par partie (et non par adresse IP) : toute une classe peut partager la même adresse publique.281 config: { rateLimit: { max: Number(process.env.RATE_LIMIT_ANSWERS ?? 90), timeWindow: "1 minute", keyGenerator: (request: FastifyRequest) => String(request.headers["x-game"] ?? request.ip) } },282 }, async (request) => {283 const session = await requireSession(request);284 return submitAnswer(session.id, answerSchema.parse(request.body));285 });286287 app.post("/api/v1/game/flag", async (request) => {288 const session = await requireSession(request);289 const body = z.object({ questionId: z.string().uuid(), reason: z.string().min(3).max(300) }).parse(request.body);290 await flagQuestion(session, body.questionId, body.reason);291 return { ok: true };292 });293294 app.get("/api/v1/results/me", async (request) => resultsFor(await requireSession(request)));295 app.get("/api/v1/results/me/analytics", async (request) => analyticsFor(await requireSession(request)));296 app.get<{ Querystring: { erreurs?: string } }>("/api/v1/results/me/review", async (request) =>297 reviewFor(await requireSession(request), request.query.erreurs === "1"),298 );299300 const leaderboardGuard = (): void => {301 if (!config.publicLeaderboard) throw new HttpError(403, "leaderboard_disabled", "Le classement public est désactivé.");302 };303304 app.get("/api/v1/leaderboard", async () => {305 leaderboardGuard();306 const daily = await getOrCreateDaily(todayInMontreal()).catch(() => null);307 return { competitions: await publicCompetitions(), daily: daily ? { id: daily.id, name: daily.name } : null };308 });309310 app.get<{ Params: { competitionId: string }; Querystring: Record<string, string> }>("/api/v1/leaderboard/:competitionId", async (request) => {311 leaderboardGuard();312 const query = z.object({313 cours: z.enum(["IMM1003", "IMM1033"]).optional(), q: z.string().max(40).default(""),314 page: z.coerce.number().int().min(1).max(10_000).default(1),315 }).parse(request.query);316 const me = typeof request.headers["x-game"] === "string" && UUID.test(request.headers["x-game"]) ? request.headers["x-game"] : null;317 return leaderboard(request.params.competitionId, { course: query.cours ?? null, search: query.q, page: query.page, pageSize: 25, me });318 });319320 app.get<{ Params: { competitionId: string } }>("/api/v1/leaderboard/:competitionId/stream", async (request, reply) => {321 leaderboardGuard();322 if (!UUID.test(request.params.competitionId)) throw new HttpError(400, "invalid_request", "Identifiant invalide.");323 reply.hijack();324 reply.raw.writeHead(200, {325 "content-type": "text/event-stream; charset=utf-8",326 "cache-control": "no-store, no-transform",327 connection: "keep-alive",328 "x-accel-buffering": "no",329 });330 reply.raw.write("retry: 4000\n\n");331 subscribe(request.params.competitionId, reply.raw);332 });333334 app.get<{ Params: { id: string; width: string } }>("/img/:id/:width", { config: { rateLimit: { max: 20_000, timeWindow: "1 minute" } } }, async (request, reply) => {335 const width = Number(request.params.width) as ImageWidth;336 if (!UUID.test(request.params.id) || !IMAGE_WIDTHS.includes(width)) throw new HttpError(404, "image_not_found", "Image introuvable.");337 const file = await imageFile(request.params.id, width);338 if (!file) return reply.status(404).header("cache-control", "public, max-age=300").send({ error: { code: "image_unavailable", message: "Photographie indisponible." } });339 return reply.header("cache-control", "public, max-age=31536000, immutable").type("image/webp").send(fs.createReadStream(file));340 });341342 await registerAdmin(app);343344 if (fs.existsSync(path.join(config.webDist, "index.html"))) {345 await app.register(fastifyStatic, {346 root: config.webDist,347 setHeaders: (res, file) => {348 res.setHeader("cache-control", file.includes(`${path.sep}assets${path.sep}`) ? "public, max-age=31536000, immutable" : "no-cache");349 },350 });351 // Relu à chaque requête : un nouveau build est servi sans redémarrer le serveur.352 const indexFile = path.join(config.webDist, "index.html");353 app.setNotFoundHandler((request, reply) => {354 if (request.method !== "GET" || request.url.startsWith("/api/") || request.url.startsWith("/img/") || /\.[a-z0-9]{2,5}$/i.test(request.url.split("?")[0]!)) {355 return reply.status(404).send({ error: { code: "not_found", message: "Ressource introuvable." } });356 }357 return reply.type("text/html; charset=utf-8").header("cache-control", "no-cache").send(fs.readFileSync(indexFile, "utf8"));358 });359 } else {360 app.setNotFoundHandler((_request, reply) => reply.status(404).send({ error: { code: "not_found", message: "Ressource introuvable." } }));361 }362363 return app;364}365366/** Entretien périodique : purge des parties d'entraînement anciennes et application de la durée de conservation. */367async function maintenance(log: (message: string) => void): Promise<void> {368 const training = await sql`369 delete from competitions c where c.mode = 'training' and c.created_at < now() - interval '30 days'`;370 let purged = 0;371 if (config.retentionDays > 0) {372 const result = await sql`delete from participants where created_at < now() - make_interval(days => ${config.retentionDays})`;373 purged = result.count;374 }375 await sql`delete from participants p where not exists (select 1 from game_sessions s where s.participant_id = p.id) and p.created_at < now() - interval '1 day'`;376 await sql`delete from audit_logs where at < now() - interval '3 years'`;377 if (training.count || purged) log(`entretien : ${training.count} entraînements et ${purged} participants purgés`);378}379380if (import.meta.main) {381 await migrate((message) => console.log(message));382 const app = await buildServer();383 await app.listen({ host: config.host, port: config.port });384 const tick = (): void => void maintenance((m) => app.log.info(m)).catch((error) => app.log.error({ err: error }, "entretien échoué"));385 setTimeout(tick, 60_000).unref();386 setInterval(tick, 6 * 60 * 60 * 1000).unref();387 for (const signal of ["SIGTERM", "SIGINT"] as const) {388 process.on(signal, () => {389 void app.close().then(() => sql.end({ timeout: 5 })).finally(() => process.exit(0));390 });391 }392}393