SPB Git

Repository Public

leak-check.ts 13.2 KB 154 lines typescript

1/**2 * pnpm leak-check — proves that unpublished material is absent from the production build.3 *4 * Sentinels are distinctive phrases taken from every imported section (quiz explanations, glossary5 * definitions, figure descriptions, lab instructions, narration scripts, references), from the preview6 * overlay (synthetic capsule, demonstration exercises) and from the learning paths' private notes.7 * Every file of .next (static HTML, RSC payloads, server and client chunks, prerender manifests) is8 * searched. As a positive control, the same sentinels must be found in the preview build when it exists:9 * a detector that finds nothing anywhere proves nothing.10 */11import { spawn } from "node:child_process";12import { existsSync } from "node:fs";13import { readFile, readdir } from "node:fs/promises";14import { join } from "node:path";15import { Manifest, buildView } from "../src/modules/content-schema";1617const manifest = Manifest.parse(JSON.parse(await readFile("content/course.manifest.json", "utf8")));18const view = buildView(manifest, "production");19const visible = new Set(view.sessions.flatMap((s) => Object.values(s.sections).map((r) => r!.path)));2021/** Long runs of plain letters: they survive HTML, JSON and JS string escaping unchanged. */22const phrases = (text: string, min = 28) => (text.match(/[A-Za-zàâçéèêëîïôûùüÿœ]+(?: [A-Za-zàâçéèêëîïôûùüÿœ]+){3,}/g) ?? []).filter((p) => p.length >= min);2324const sentinels = new Map<string, string>(); // phrase → origin25const add = (origin: string, text: string, max = 6) => { for (const p of phrases(text).slice(0, max)) if (!sentinels.has(p)) sentinels.set(p, origin); };26const strings = (value: unknown, out: string[] = []): string[] => { if (typeof value === "string") out.push(value); else if (value && typeof value === "object") for (const v of Object.values(value)) strings(v, out); return out; };2728for (const s of manifest.sessions) for (const [key, ref] of Object.entries(s.sections)) {29  if (visible.has(ref!.path)) continue; // genuinely published material is allowed in the build30  const body = await readFile(join("content/import", ref!.path), "utf8");31  if (ref!.path.endsWith(".json")) {32    // Skip fields that are public by design (titles of sessions never appear in these files).33    for (const text of strings(JSON.parse(body))) add(`${s.id}.${key}`, text, 2);34  } else for (const line of body.split("\n").filter((l) => l.length > 60).slice(0, 40)) add(`${s.id}.${key}`, line, 1);35}36const overlay = JSON.parse(await readFile("content/preview/overlay.json", "utf8"));37for (const text of strings(overlay)) add("preview/overlay.json", text, 2);3839// Public plan text (titles, outcomes, tags) is legitimately in the build: never use it as a sentinel.40const publicText = [...view.sessions.flatMap((s) => [s.title, s.short, ...s.outcomes, ...s.tags]), ...view.parts.flatMap((p) => [p.title, p.short]), view.course.title, view.course.subtitle, view.course.tagline, view.course.endorsementNotice].join("\n");41// Neither is the site's own interface copy (src/), which may share a generic phrase with the course by coincidence.42const sourceFiles = async (d: string): Promise<string[]> => (await Promise.all((await readdir(d, { withFileTypes: true })).map(async (e) => (e.isDirectory() ? sourceFiles(join(d, e.name)) : [await readFile(join(d, e.name), "utf8")])))).flat();43const ownText = [publicText, view.author.institution, view.author.department, ...(await sourceFiles("src")), await readFile("content/paths.json", "utf8")].join("\n");44for (const p of [...sentinels.keys()]) if (ownText.includes(p)) sentinels.delete(p);4546async function scan(dir: string): Promise<Map<string, string[]>> {47  const found = new Map<string, string[]>();48  const walk = async (d: string) => {49    for (const e of await readdir(d, { withFileTypes: true })) {50      const path = join(d, e.name);51      if (e.isSymbolicLink()) continue; // links to external packages: third-party code, not course content52      if (e.isDirectory()) { if (!["cache", "dev", "trace"].includes(e.name)) await walk(path); continue; }53      if (/\.(png|jpg|ico|woff2?|map)$/.test(e.name)) continue;54      const text = await readFile(path, "utf8");55      for (const phrase of sentinels.keys()) if (text.includes(phrase)) found.set(phrase, [...(found.get(phrase) ?? []), path]);56    }57  };58  await walk(dir);59  return found;60}6162/**63 * Since Phase 4 pages are rendered on demand: the build holds no course content at all, so the build scan64 * alone would prove little. Each build is therefore also started for real and crawled — every route, the65 * sitemap, the search index, every session page — and the answers are searched for the same sentinels.66 */67async function crawl(distEnv: Record<string, string>, port: number): Promise<{ found: Map<string, string[]>; pages: number }> {68  const base = `http://127.0.0.1:${port}`;69  const child = spawn("node_modules/.bin/next", ["start", "-p", String(port), "-H", "127.0.0.1"], { env: { ...process.env, NODE_ENV: "production", ATLAS_CONTENT_SOURCE: "seed", ATLAS_LOG_LEVEL: "silent", ...distEnv } as NodeJS.ProcessEnv, stdio: "ignore" });70  try {71    for (let i = 0; ; i++) { try { if ((await fetch(`${base}/api/health`)).ok) break; } catch { /* not up yet */ } if (i > 100) throw new Error(`le serveur du port ${port} n'a pas démarré`); await new Promise((r) => setTimeout(r, 200)); }72    const urls = new Set(["/", "/programme", "/parcours", "/laboratoires", "/ressources", "/glossaire", "/recherche", "/a-propos", "/accessibilite", "/confidentialite", "/conditions", "/schemas", "/apercu", "/recherche/index.json", "/sitemap.xml", "/robots.txt", "/api/health", "/admin", "/admin/connexion", "/admin/api/sessions", "/admin/api/sessions/S01/sections/quiz"]);73    for (const s of manifest.sessions) { for (const slug of [s.slug, ...s.aliases]) { urls.add(`/seances/${slug}`); urls.add(`/seances/${slug}/regarder`); } for (const ref of Object.values(s.sections)) urls.add(`/contenu/${ref!.path.replace(/^sessions\//, "")}`); urls.add(`/admin/apercu/seances/${s.slug}`); }74    for (const id of Object.keys(manifest.diagrams)) urls.add(`/schemas/${id}`);75    const found = new Map<string, string[]>();76    for (const url of urls) {77      const text = await (await fetch(base + url)).text();78      for (const phrase of sentinels.keys()) if (text.includes(phrase)) found.set(phrase, [...(found.get(phrase) ?? []), url]);79    }80    return { found, pages: urls.size };81  } finally { if (child.pid) process.kill(child.pid, "SIGTERM"); }82}8384if (!existsSync(".next/BUILD_ID")) { console.error("Aucune compilation de production : lancer pnpm build."); process.exit(2); }85console.log(`${sentinels.size} phrases témoins tirées du contenu non publié.`);86let failed = false;87const report = (label: string, leaks: Map<string, string[]>) => {88  if (!leaks.size) { console.log(`✓ Aucune phrase témoin ${label}.`); return; }89  failed = true;90  console.error(`✗ ${leaks.size} phrase(s) non publiée(s) trouvée(s) ${label} :`);91  for (const [phrase, where] of [...leaks].slice(0, 20)) console.error(`  « ${phrase} » (${sentinels.get(phrase)}) → ${where.slice(0, 3).join(", ")}`);92};93report("dans .next (fichiers de la compilation de production)", await scan(".next"));94const prod = await crawl({}, 8851);95report(`dans les ${prod.pages} réponses du serveur de production`, prod.found);9697if (existsSync(".next-preview/BUILD_ID")) {98  // Positive control: the same detector must find the preview material where it is meant to be shown.99  const control = (await crawl({ ATLAS_PREVIEW: "1" }, 8852)).found;100  const origins = new Set([...control.keys()].map((p) => sentinels.get(p)!));101  console.log(`Contrôle positif : ${control.size} phrases témoins retrouvées sur le serveur d'aperçu (origines : ${[...origins].sort().join(", ")}).`);102  if (!origins.has("S01.quiz") || !origins.has("preview/overlay.json")) { failed = true; console.error("✗ Le contrôle positif a échoué : le détecteur ne retrouve pas le contenu d'aperçu là où il doit être."); }103  // Boilerplate shared by every session also lives in the sessions legitimately shown in preview: a draft leaks only if a phrase found is absent from all of those.104  const previewView = buildView(manifest, "preview");105  const shown = (await Promise.all(previewView.sessions.flatMap((s) => Object.values(s.sections).map((r) => readFile(join("content/import", r!.path), "utf8"))))).join("\n");106  const shownIds = new Set(previewView.sessions.filter((s) => s.access === "open").map((s) => s.id));107  const drafts = [...new Set([...control.keys()].filter((p) => !shown.includes(p)).map((p) => sentinels.get(p)!))].filter((o) => /^S\d+\./.test(o) && !shownIds.has(o.split(".")[0]!));108  if (drafts.length) { failed = true; console.error(`✗ Du contenu de séances en brouillon est servi par l'aperçu : ${drafts.join(", ")}`); }109  else console.log("✓ Aucun contenu de séance en brouillon servi par l'aperçu.");110  report("dans .next-preview (fichiers de la compilation d'aperçu)", await scan(".next-preview"));111} else console.log("(Contrôle positif non effectué : pas de compilation d'aperçu.)");112113// The instructor's speaker notes must be nowhere: not in a build, not in the committed snapshot, not in a slide114// deck of the data directory. Checked when the course repository is on this machine (ATLAS_COURSE_REPO).115const courseRepo = process.env.ATLAS_COURSE_REPO;116if (courseRepo && existsSync(join(courseRepo, "sessions"))) {117  const notes = new Set<string>();118  let shared = 0;119  for (const dir of await readdir(join(courseRepo, "sessions"))) {120    const text = await readFile(join(courseRepo, "sessions", dir, "slides", "speaker-notes.md"), "utf8").catch(() => "");121    // The narration script (video/script.md) is a separate file that the importer has always brought in, as a private122    // section; where the instructor wrote the same sentence in both, the sentence is not a note leaking.123    const script = await readFile(join(courseRepo, "sessions", dir, "video", "script.md"), "utf8").catch(() => "");124    for (const p of phrases(text, 45).slice(0, 60)) { if (script.includes(p)) shared++; else if (!ownText.includes(p)) notes.add(p); }125  }126  const haystacks: [string, string][] = [];127  const collect = async (d: string, keep: (name: string) => boolean) => { for (const e of await readdir(d, { withFileTypes: true }).catch(() => [])) { const path = join(d, e.name); if (e.isSymbolicLink()) continue; if (e.isDirectory()) { if (!["cache", "node_modules"].includes(e.name)) await collect(path, keep); } else if (keep(e.name)) haystacks.push([path, await readFile(path, "utf8")]); } };128  await collect(".next", (n) => !/\.(png|jpg|ico|woff2?|map)$/.test(n));129  // The committed snapshot is reported apart, without failing: its sections (narration scripts, quiz explanations — all130  // private or preview-only, imported in Phases 1–3 from other files) share whole sentences with the notes, written by the same hand.131  const snapshot: [string, string][] = [];132  { const keep = haystacks.length; await collect("content", (n) => /\.(json|md)$/.test(n)); snapshot.push(...haystacks.splice(keep)); }133  await collect(join(process.env.ATLAS_DATA_DIR ?? "data", "slides"), (n) => n === "deck.json");134  // A sentence the instructor also put on a slide is public by his own hand: only phrases absent from every slide text count.135  const slideText = haystacks.filter(([p]) => p.endsWith("deck.json")).map(([, t]) => (JSON.parse(t) as { slides: { text: string }[] }).slides.map((x) => x.text.replace(/\s+/g, " ")).join(" ")).join(" ");136  const hits = [...notes].filter((n) => !slideText.includes(n)).flatMap((n) => haystacks.filter(([, t]) => t.includes(n)).map(([p]) => `« ${n.slice(0, 50)}… » dans ${p}`));137  const echoed = [...notes].filter((n) => snapshot.some(([, t]) => t.includes(n))).length;138  if (echoed) console.log(`(À savoir : ${echoed} phrase(s) des notes figurent aussi, mot pour mot, dans des sections non publiques de l'instantané — scénarios, explications de quiz. Elles ne sont servies à personne.)`);139  if (hits.length) { failed = true; console.error(`✗ Notes de l'enseignant retrouvées : ${hits.slice(0, 5).join(" ; ")}`); }140  else console.log(`✓ Aucune des ${notes.size} phrases tirées des notes de l'enseignant dans ${haystacks.length} fichiers (compilations et paquets de diapositives) ; ${shared} phrase(s) écartée(s) car aussi présente(s) dans le scénario de narration du dépôt.`);141} else console.log("(Notes de l'enseignant non vérifiées ici : dépôt du cours absent — ATLAS_COURSE_REPO.)");142143// No server-side secret or database code in what is sent to browsers.144const client = await scanClient(".next/static");145if (client.length) { failed = true; console.error(`✗ Code ou identifiants réservés au serveur dans le lot client : ${client.slice(0, 5).join(" ; ")}`); } else console.log("✓ Aucun code serveur ni secret dans .next/static.");146process.exit(failed ? 1 : 0);147148async function scanClient(dir: string): Promise<string[]> {149  const hits: string[] = [], markers = ["node:sqlite", "token_hash", "ATLAS_HEALTH_TOKEN", "enroll_tokens", "auth_sessions", "BEGIN IMMEDIATE"];150  const walk = async (d: string) => { for (const e of await readdir(d, { withFileTypes: true })) { const path = join(d, e.name); if (e.isDirectory()) await walk(path); else if (/\.(js|css|json)$/.test(e.name)) { const text = await readFile(path, "utf8"); for (const m of markers) if (text.includes(m)) hits.push(`${m} dans ${path}`); } } };151  await walk(dir);152  return hits;153}154
Files main
Menu

Theme