Repository Public
1import { mkdir, mkdtemp, readFile, readdir, rm, symlink, writeFile } from "node:fs/promises";2import { tmpdir } from "node:os";3import { join } from "node:path";4import { afterAll, beforeAll, describe, expect, it } from "vitest";5import { importCourse } from "../scripts/lib/importer";6import { checkSvg, convertQuiz, parseBibtex, parseGlossary } from "@/modules/content-schema/adapter";7import { Manifest, buildView } from "@/modules/content-schema";89const SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 50"><rect width="100" height="50"/></svg>';10const COURSE = `11course: {id: test, title: "Cours test", short_title: "Test", tagline: "t", subtitle: "s", language: fr-CA, version: 0.1.0, endorsement_notice: "Avis."}12author: {name: "Prof", role: "Professeur", institution: "Université", institution_short: "U", department: "Département"}13parts: [{id: I, short: "Un", title: "Partie un"}]14sessions:15 - {id: S01, slug: first, part: I, level: débutant, title: "Première", short: "Première séance", depends_on: [], tags: [a], outcomes: ["Faire A."]}16 - {id: S02, slug: second, part: I, level: avancé, title: "Deuxième", short: "Deuxième séance", depends_on: [S01], tags: [], outcomes: ["Faire B."]}17 - {id: S03, slug: third, part: I, level: avancé, title: "Troisième", short: "Troisième séance", depends_on: [S01], tags: [], outcomes: ["Faire C."]}18 - {id: S04, slug: fourth, part: I, level: avancé, title: "Quatrième", short: "Quatrième séance", depends_on: [], tags: [], outcomes: ["Faire D."]}19`;20const QUIZ = `21session: S0122title: Quiz23passing_score: 124questions:25- {id: Q1, type: choix-unique, prompt: "P ?", options: [{id: A, text: "a"}, {id: B, text: "b"}], answer: B, explanation: "Parce que.", distractors: {A: "Non."}}26- {id: Q2, type: vrai-faux, prompt: "V ?", options: [{id: A, text: Vrai}, {id: B, text: Faux}], answer: B, explanation: "Faux."}27- {id: Q3, type: type-inconnu, prompt: "?", explanation: "x"}28- {id: Q4, type: choix-unique, prompt: "P ?", options: [{id: A, text: "a"}], answer: Z, explanation: "x"}29`;30const README = "# S01\n\n## Glossaire de la séance\n\n| Terme français | Terme anglais | Définition courte |\n|---|---|---|\n| jeton | *token* | unité de texte |\n| **fenêtre de contexte** | *context window* | texte lu par le modèle |\n\n## Suite\n\n| a | b | c |\n";3132let repo: string, out: string, outside: string;3334beforeAll(async () => {35 repo = await mkdtemp(join(tmpdir(), "atlas-repo-")); out = await mkdtemp(join(tmpdir(), "atlas-out-")); outside = await mkdtemp(join(tmpdir(), "atlas-outside-"));36 await writeFile(join(outside, "secret.svg"), SVG.replace("<rect", "<!-- SECRET-HORS-DEPOT --><rect"));37 await writeFile(join(outside, "secret.md"), "SECRET-HORS-DEPOT");38 await writeFile(join(repo, "course.yaml"), COURSE);39 const s1 = join(repo, "sessions/S01-first");40 for (const d of ["quizzes", "figures/rendered", "labs/solution", "video", "slides"]) await mkdir(join(s1, d), { recursive: true });41 await writeFile(join(s1, "metadata.yaml"), "id: S01\nstatus: implemented\nlast_reviewed: '2026-11-22'\neffort_minutes: {lab: [45, 60]}\ndeliverables: {video_recorded: false}\n");42 await writeFile(join(s1, "README.md"), README);43 await writeFile(join(s1, "quizzes/questions.yaml"), QUIZ);44 await writeFile(join(s1, "labs/instructions.md"), "# Labo\n\nConsignes.");45 await writeFile(join(s1, "labs/solution/corrige.py"), "CORRIGE-SECRET = 42");46 await writeFile(join(s1, "video/script.md"), "# Scénario");47 await writeFile(join(s1, "slides/references.bib"), "@book{k1,\n author = {Doe, Jane and Roe, Rick},\n title = {A {Good} Book},\n year = {2020},\n publisher = {Press},\n url = {https://example.org/x},\n}\n@misc{k2, title = {No url}, year = 2021, url = {javascript:alert(1)}}");48 await writeFile(join(s1, "figures/rendered/ok.svg"), SVG);49 await writeFile(join(s1, "figures/rendered/script.svg"), SVG.replace("<rect", "<script>alert(1)</script><rect"));50 await writeFile(join(s1, "figures/rendered/handler.svg"), SVG.replace("<rect", '<rect onload="x()"'));51 await writeFile(join(s1, "figures/rendered/remote.svg"), SVG.replace("<rect", '<image href="https://evil.example/x.png"/><rect'));52 await symlink(join(outside, "secret.svg"), join(s1, "figures/rendered/link.svg"));53 await writeFile(join(s1, "figures/manifest.yaml"), `figures:54 - {id: F-OK, rendered: [rendered/ok.pdf, rendered/ok.svg], caption: "Légende", alt: "Description."}55 - {id: F-SCRIPT, rendered: [rendered/script.svg], caption: "c", alt: "a"}56 - {id: F-HANDLER, rendered: [rendered/handler.svg], caption: "c", alt: "a"}57 - {id: F-REMOTE, rendered: [rendered/remote.svg], caption: "c", alt: "a"}58 - {id: F-TRAVERSAL, rendered: [../../../../outside/secret.svg], caption: "c", alt: "a"}59 - {id: F-SYMLINK, rendered: [rendered/link.svg], caption: "c", alt: "a"}60 - {id: F-NOALT, rendered: [rendered/ok.svg], caption: "c", alt: ""}61 - {id: F-PDF, rendered: [rendered/only.pdf], caption: "c", alt: "a"}62`);63 // S02: a draft being written by someone else — full of material that must not be read.64 const s2 = join(repo, "sessions/S02-second");65 await mkdir(join(s2, "quizzes"), { recursive: true });66 await writeFile(join(s2, "metadata.yaml"), "id: S02\nstatus: draft\n");67 await writeFile(join(s2, "quizzes/questions.yaml"), QUIZ.replace("S01", "S02"));68 // S03: half-written metadata (invalid YAML). S04: no directory at all.69 await mkdir(join(repo, "sessions/S03-third"), { recursive: true });70 await writeFile(join(repo, "sessions/S03-third/metadata.yaml"), "id: S03\nstatus: [implemen");71 // A symlinked lab pointing outside the repository.72 await symlink(join(outside, "secret.md"), join(repo, "sessions/S03-third/README.md"));73});74afterAll(async () => { for (const d of [repo, out, outside]) await rm(d, { recursive: true, force: true }); });7576const walk = async (d: string): Promise<string[]> => (await Promise.all((await readdir(d, { withFileTypes: true })).map(async (e) => (e.isDirectory() ? walk(join(d, e.name)) : [join(d, e.name)])))).flat();7778describe("course importer", () => {79 it("imports only what the session's own metadata declares complete, and never publishes", async () => {80 const { manifest, report } = await importCourse({ repo, out, publication: {} });81 expect(Manifest.safeParse(manifest).success).toBe(true);82 const [s1, s2, s3, s4] = manifest.sessions;83 expect(Object.keys(s1!.sections).sort()).toEqual(["bibliography", "figures", "glossary", "lab", "quiz", "script"]);84 expect(s1!.publication).toBe("draft"); // material exists, yet nothing is opened by the import85 for (const ref of Object.values(s1!.sections)) expect(ref!.visibility).toBe("private");86 expect(s2!.sections).toEqual({}); expect(s2!.publication).toBe("planned"); expect(s2!.source.status).toBe("draft");87 expect(s3!.sections).toEqual({}); expect(s3!.source.status).toBe("unknown");88 expect(s4!.source.status).toBe("unknown");89 expect(report.sessions[2]!.warnings.join()).toContain("YAML");90 expect(report.sessions[3]!.warnings).toContain("metadata.yaml absent");91 // Nothing is visible to anyone, in any mode, without an editorial decision.92 for (const mode of ["production", "preview"] as const) expect(buildView(manifest, mode).counts.open).toBe(0);93 });9495 it("derives French slugs and keeps the repository slug as a redirect alias", async () => {96 const { manifest } = await importCourse({ repo, out, publication: {} });97 expect(manifest.sessions[0]).toMatchObject({ slug: "01-premiere-seance", aliases: ["first", "s01"] });98 });99100 it("is idempotent: a second run writes nothing, and outputs are byte-identical", async () => {101 await importCourse({ repo, out, publication: {} });102 const before = await Promise.all((await walk(out)).sort().map(async (f) => [f, (await readFile(f)).toString("base64")]));103 const second = await importCourse({ repo, out, publication: {} });104 expect(second.written).toEqual([]); expect(second.removed).toEqual([]);105 const after = await Promise.all((await walk(out)).sort().map(async (f) => [f, (await readFile(f)).toString("base64")]));106 expect(after).toEqual(before);107 });108109 it("records a content hash that changes when a source file changes", async () => {110 const a = await importCourse({ repo, out, publication: {}, dryRun: true });111 await writeFile(join(repo, "sessions/S01-first/video/script.md"), "# Scénario modifié");112 const b = await importCourse({ repo, out, publication: {}, dryRun: true });113 expect(b.report.sourceHash).not.toBe(a.report.sourceHash);114 expect(b.manifest.sessions[0]!.source.hash).not.toBe(a.manifest.sessions[0]!.source.hash);115 expect(b.manifest.sessions[1]!.source.hash).toBe(a.manifest.sessions[1]!.source.hash);116 expect(b.written.some((f) => f.endsWith("script.md"))).toBe(true); // dry run reports, does not write117 await writeFile(join(repo, "sessions/S01-first/video/script.md"), "# Scénario");118 });119120 it("refuses path traversal, symlink escapes and active SVG content", async () => {121 const { report } = await importCourse({ repo, out, publication: {} });122 const figures = JSON.parse(await readFile(join(out, "import/sessions/S01/figures.json"), "utf8")).figures as { id: string }[];123 expect(figures.map((f) => f.id)).toEqual(["F-OK"]);124 const w = report.sessions[0]!.warnings.join("\n");125 for (const id of ["F-SCRIPT", "F-HANDLER", "F-REMOTE", "F-TRAVERSAL", "F-NOALT"]) expect(w, id).toContain(id);126 expect(w).toContain("link.svg");127 const everything = (await Promise.all((await walk(out)).map((f) => readFile(f, "utf8")))).join("\n");128 expect(everything).not.toContain("SECRET-HORS-DEPOT");129 });130131 it("never reads the solution directory", async () => {132 await importCourse({ repo, out, publication: {} });133 const everything = (await Promise.all((await walk(out)).map((f) => readFile(f, "utf8")))).join("\n");134 expect(everything).not.toContain("CORRIGE-SECRET");135 expect((await walk(out)).some((f) => /solution|corrige/i.test(f))).toBe(false);136 });137138 it("applies the editorial layer, and only that layer raises visibility", async () => {139 const publication = { sessions: { S01: { publication: "preview", sections: { quiz: "preview" } }, S02: { publication: "published", sections: { quiz: "public" } } } };140 const { manifest, report } = await importCourse({ repo, out, publication });141 const preview = buildView(manifest, "preview"), production = buildView(manifest, "production");142 expect(Object.keys(preview.sessions[0]!.sections)).toEqual(["quiz"]); // the other sections stay private143 expect(production.sessions[0]!.access).toBe("upcoming");144 // S02 was marked published by hand but has no imported material: it opens empty, and the report says so.145 expect(production.sessions[1]!.sections).toEqual({});146 expect(report.warnings.join()).toMatch(/S02.*sans aucun contenu|S02\.quiz/);147 });148149 it("removes stale outputs of a previous import, inside the import directory only", async () => {150 await importCourse({ repo, out, publication: {} });151 await mkdir(join(out, "import/sessions/S09"), { recursive: true });152 await writeFile(join(out, "import/sessions/S09/quiz.json"), "{}");153 await writeFile(join(out, "publication.json"), "{}");154 const { removed } = await importCourse({ repo, out, publication: {} });155 expect(removed.map((f) => f.replace(out, ""))).toEqual(["/import/sessions/S09/quiz.json"]);156 expect(await readFile(join(out, "publication.json"), "utf8")).toBe("{}");157 });158159 it("fails loudly when course.yaml is missing or invalid", async () => {160 const empty = await mkdtemp(join(tmpdir(), "atlas-empty-"));161 await expect(importCourse({ repo: empty, out, publication: {}, dryRun: true })).rejects.toThrow(/course\.yaml/);162 await writeFile(join(empty, "course.yaml"), "course: {id: x}");163 await expect(importCourse({ repo: empty, out, publication: {}, dryRun: true })).rejects.toThrow();164 await rm(empty, { recursive: true, force: true });165 });166});167168describe("format adapters", () => {169 it("converts the course quiz format and skips what it does not understand", async () => {170 const { parse } = await import("yaml");171 const { value, warnings } = convertQuiz(parse(QUIZ));172 expect(value!.questions.map((q) => q.type)).toEqual(["single", "true-false"]);173 expect(value!.questions[0]).toMatchObject({ answer: "B", options: [{ id: "A", text: "a", feedback: "Non." }, { id: "B", text: "b" }] });174 expect(value!.questions[1]).toMatchObject({ answer: false });175 expect(value!.passingScore).toBe(1);176 expect(warnings.join("\n")).toMatch(/Q3.*type-inconnu/); expect(warnings.join("\n")).toMatch(/Q4/);177 expect(convertQuiz({ nope: true }).value).toBeNull();178 });179 it("reads the glossary table of a README", () => {180 const { value } = parseGlossary(README, "S01");181 expect(value!.terms).toEqual([182 { id: "jeton", term: "jeton", english: "token", definition: "unité de texte", session: "S01" },183 { id: "fenetre-de-contexte", term: "fenêtre de contexte", english: "context window", definition: "texte lu par le modèle", session: "S01" },184 ]);185 expect(parseGlossary("# rien", "S01").value).toBeNull();186 });187 it("reads BibTeX and keeps only http(s) links", () => {188 const { entries } = parseBibtex("@book{k1,\n author = {Doe, Jane and Roe, Rick},\n title = {A {Good} Book},\n year = {2020},\n publisher = {Press},\n url = {https://example.org/x},\n}\n@misc{k2, title = {No url}, year = 2021, url = {javascript:alert(1)}}");189 expect(entries[0]).toEqual({ key: "k1", type: "book", authors: "Jane Doe, Rick Roe", title: "A Good Book", year: "2020", venue: "Press", url: "https://example.org/x" });190 expect(entries[1]).toMatchObject({ key: "k2", url: null });191 });192 it("accepts inert SVG and reports its size", () => {193 expect(checkSvg(SVG)).toEqual({ ok: true, width: 100, height: 50 });194 expect(checkSvg('<svg><use href="#a"/></svg>').ok).toBe(true);195 for (const bad of ["<html/>", "<svg><script/></svg>", "<svg><foreignObject/></svg>", '<svg onclick="x"/>', '<svg><a href="javascript:x"/></svg>', '<!DOCTYPE svg [<!ENTITY x "y">]><svg/>']) expect(checkSvg(bad).ok, bad).toBe(false);196 });197});198199describe("the committed snapshot", () => {200 it("matches its recorded hashes (no hand edit of imported files)", async () => {201 const { createHash } = await import("node:crypto");202 const manifest = Manifest.parse(JSON.parse(await readFile("content/course.manifest.json", "utf8")));203 for (const s of manifest.sessions) for (const ref of Object.values(s.sections)) {204 const body = await readFile(join("content/import", ref!.path));205 expect(createHash("sha256").update(body).digest("hex"), ref!.path).toBe(ref!.sha256);206 }207 });208});209