Repository Public
1import { existsSync, readFileSync, readdirSync } from "node:fs";2import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";3import { tmpdir } from "node:os";4import { join } from "node:path";5import { DatabaseSync } from "node:sqlite";6import { gunzipSync } from "node:zlib";7import { afterAll, beforeEach, describe, expect, it } from "vitest";8import { getCourse, getQuiz } from "@/lib/content";9import { buildView } from "@/modules/content-schema";10import { listAudit } from "@/server/audit";11import { createEditor, issueEnrollToken, issueSession } from "@/server/auth";12import { createBackup, exportCourse, exportTarGz, exportToDir, listBackups, pruneBackups, restoreBackup, verifyBackup } from "@/server/backup";13import { addResourceVersion, createCapsule, getCapsule, getSessionRow, listSessions, putSection, setSessionState, updateSession, writeCapsule } from "@/server/content";14import { closeDb, db, run } from "@/server/db";15import { beat } from "@/server/jobs";16import { checkLinks, healthDetails, validateAllCaptions } from "@/server/ops";17import { history, publicManifest, publishSession } from "@/server/publish";18import { storageUsage } from "@/server/storage";19import { cleanup, freshDataDir, freshStudio } from "./studio-helpers";2021let dir: string;22const put = async (rel: string, body: string | Buffer) => { await mkdir(join(dir, rel, ".."), { recursive: true }); await writeFile(join(dir, rel), body); };2324/** A studio with a published session, a capsule with sidecar files, a resource, a master and an editor with a session. */25async function populated() {26 dir = await freshStudio();27 const owner = createEditor("Propriétaire", "owner", "cli");28 const { raw } = issueEnrollToken(owner.id, "setup", "cli"), { token } = issueSession(owner.id);29 createCapsule("S01", { title: "Capsule", id: "capsule" }, owner.id);30 const rel = "S01/capsule/r1";31 await put(`media/${rel}/master.m3u8`, "#EXTM3U"); await put(`media/${rel}/fallback.mp4`, "mp4"); await put(`media/${rel}/poster.jpg`, "jpg"); await put(`media/${rel}/v360/seg_00000.ts`, "x".repeat(5000));32 await put("media/S01/capsule/captions.fr-CA.aaaaaaaaaa.vtt", "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nRéplique sauvegardée.\n");33 await put("media/S01/capsule/transcript.bbbbbbbbbb.json", JSON.stringify({ lang: "fr-CA", segments: [{ start: 0, end: 2, text: "Réplique sauvegardée." }] }));34 await put(`masters/${"c".repeat(64)}.mp4`, "fichier maître volumineux");35 const cur = getCapsule("S01", "capsule");36 writeCapsule({ ...cur, status: "ready", data: { ...cur.data, visibility: "public", durationSeconds: 10, media: { hls: `${rel}/master.m3u8`, mp4: `${rel}/fallback.mp4`, poster: `${rel}/poster.jpg`, captions: [{ lang: "fr-CA", label: "Français", path: "S01/capsule/captions.fr-CA.aaaaaaaaaa.vtt" }], transcript: "S01/capsule/transcript.bbbbbbbbbb.json" } } }, owner.id);37 await put("resources/S01/abc/diapos.pdf", "%PDF-1.4 contenu");38 addResourceVersion("S01", { meta: { kind: "slides", title: "Diapositives", visibility: "public", download: true, license: "CC BY 4.0" }, file: { path: "S01/abc/diapos.pdf", bytes: 16, sha256: "d".repeat(64), mime: "application/pdf", filename: "diapos.pdf" } }, owner.id);39 putSection("S01", "quiz", { visibility: "public" }, owner.id); setSessionState("S01", "preview", owner.id);40 updateSession("S01", { title: "Titre avant la sauvegarde" }, getSessionRow("S01").rev, owner.id);41 publishSession("S01", { confirm: "S01" }, owner.id);42 return { owner, raw, token };43}4445beforeEach(() => { delete process.env.ATLAS_FFMPEG; });46afterAll(cleanup);4748describe("backup → restore drill", () => {49 it("restores database, resources and caption files into an empty directory, and the site is the same", async () => {50 await populated();51 const before = { view: JSON.stringify(buildView(publicManifest()!, "production")), audit: listAudit({ limit: 500 }).length, history: history("S01").length, sessions: listSessions().length };52 const { dir: backup, manifest } = await createBackup();53 expect(backup.startsWith(join(dir, "backups"))).toBe(true);54 expect(manifest).toMatchObject({ format: 1, includes: { resources: true, sidecars: true, media: false, masters: false }, counts: { sessions: 24, masters: 1 } });55 const paths = manifest.files.map((f) => f.path);56 expect(paths).toEqual(expect.arrayContaining(["atlas.db", "media-manifest.json", "resources/S01/abc/diapos.pdf", "media/S01/capsule/captions.fr-CA.aaaaaaaaaa.vtt", "media/S01/capsule/transcript.bbbbbbbbbb.json"]));57 expect(paths.some((p) => p.endsWith(".ts") || p.endsWith(".mp4") || p.startsWith("masters/"))).toBe(false); // large, regenerable or copied apart58 const media = JSON.parse(await readFile(join(backup, "media-manifest.json"), "utf8")) as { files: { root: string; path: string; bytes: number; inBackup: boolean; sha256: string | null }[] };59 expect(media.files.find((f) => f.root === "masters")).toMatchObject({ bytes: 26, inBackup: false, sha256: "c".repeat(64) });60 expect(media.files.find((f) => f.path.endsWith("seg_00000.ts"))).toMatchObject({ bytes: 5000, inBackup: false });61 expect((await verifyBackup(backup)).problems).toEqual([]);6263 // The snapshot is consistent and self-contained: it opens alone, without the live database's journal.64 const snap = new DatabaseSync(join(backup, "atlas.db"), { readOnly: true });65 expect((snap.prepare("PRAGMA integrity_check").get() as { integrity_check: string }).integrity_check).toBe("ok");66 snap.close();6768 // Disaster: a new, empty data directory.69 const target = await freshDataDir();70 const report = await restoreBackup(backup, target);71 expect(report).toMatchObject({ integrity: "ok", replacedDatabase: null, migrationsApplied: [] });72 expect(report.missingMedia.map((m) => `${m.root}/${m.path}`).sort()).toEqual([`masters/${"c".repeat(64)}.mp4`, "media/S01/capsule/r1/fallback.mp4", "media/S01/capsule/r1/master.m3u8", "media/S01/capsule/r1/poster.jpg", "media/S01/capsule/r1/v360/seg_00000.ts"]); // exactly what still has to be brought back73 expect(JSON.stringify(buildView(publicManifest()!, "production"))).toBe(before.view);74 expect(listAudit({ limit: 500 }).length).toBe(before.audit);75 expect(history("S01")).toHaveLength(before.history);76 expect(listSessions()).toHaveLength(before.sessions);77 const s = (await getCourse()).sessions.find((x) => x.id === "S01")!;78 expect(s.title).toBe("Titre avant la sauvegarde");79 expect((await getQuiz(s))!.questions.length).toBeGreaterThan(0); // section bodies came back with the database80 expect(readFileSync(join(target, "resources/S01/abc/diapos.pdf"), "utf8")).toBe("%PDF-1.4 contenu");81 expect(readFileSync(join(target, "media/S01/capsule/captions.fr-CA.aaaaaaaaaa.vtt"), "utf8")).toContain("Réplique sauvegardée");82 expect((await validateAllCaptions()).tracks[0]).toMatchObject({ ok: true, cues: 1 });83 // The link checker of the restored studio names what is missing on disk for what is online.84 expect((await checkLinks()).findings.filter((f) => f.level === "error").map((f) => f.message).join(" ")).toMatch(/capsule publiée .* manque/);85 });8687 it("includes videos and masters on request: then nothing is missing after the restore", async () => {88 await populated();89 const { dir: backup, manifest } = await createBackup({ outDir: join(await mkdtemp(join(tmpdir(), "atlas-bk-")), "complet"), withMedia: true, withMasters: true });90 expect(manifest.includes).toMatchObject({ media: true, masters: true });91 const target = await freshDataDir();92 const report = await restoreBackup(backup, target);93 expect(report.missingMedia).toEqual([]);94 expect((await checkLinks({ deep: false })).findings.filter((f) => f.level === "error" && /manque|absent/.test(f.message))).toEqual([]);95 await rm(join(backup, ".."), { recursive: true, force: true });96 });9798 it("refuses a damaged or tampered backup before touching anything", async () => {99 await populated();100 const { dir: backup } = await createBackup();101 await writeFile(join(backup, "resources/S01/abc/diapos.pdf"), "%PDF-1.4 falsifié");102 expect((await verifyBackup(backup)).problems).toEqual(["fichier altéré : resources/S01/abc/diapos.pdf"]);103 const target = await freshDataDir();104 await expect(restoreBackup(backup, target)).rejects.toThrow(/Sauvegarde refusée : fichier altéré/);105 expect(readdirSync(target)).toEqual([]);106 const m = JSON.parse(await readFile(join(backup, "backup.json"), "utf8")) as { files: { path: string }[] };107 m.files.push({ path: "../../evasion.txt" } as never);108 await writeFile(join(backup, "backup.json"), JSON.stringify(m));109 expect((await verifyBackup(backup)).problems.join(" ")).toMatch(/chemin dangereux/);110 });111112 it("never overwrites an existing database silently; with --force the old one is kept aside", async () => {113 await populated();114 const { dir: backup } = await createBackup();115 updateSession("S01", { title: "Titre après la sauvegarde" }, getSessionRow("S01").rev, "ed");116 closeDb(); // restore runs with the server and the worker stopped117 await expect(restoreBackup(backup, dir)).rejects.toThrow(/Une base existe déjà/);118 const report = await restoreBackup(backup, dir, { force: true });119 expect(report.replacedDatabase).toMatch(/atlas\.db\.remplacee-/);120 expect(existsSync(report.replacedDatabase!)).toBe(true);121 expect(getSessionRow("S01").data.title).toBe("Titre avant la sauvegarde");122 });123124 it("brings an older backup forward through the migrations, and refuses one from a newer application", async () => {125 await populated();126 const { dir: backup } = await createBackup();127 const m = JSON.parse(await readFile(join(backup, "backup.json"), "utf8")) as { schema: { version: number } };128 m.schema.version = 99;129 await writeFile(join(backup, "backup.json"), JSON.stringify(m));130 await expect(restoreBackup(backup, await freshDataDir())).rejects.toThrow(/plus récente/);131 });132133 it("applies the retention rule: the N most recent backups are kept", async () => {134 await populated();135 const root = join(dir, "backups");136 for (const name of ["a", "b", "c", "d"]) { await createBackup({ outDir: join(root, name) }); await new Promise((r) => setTimeout(r, 5)); }137 expect((await listBackups()).map((b) => b.dir.split("/").pop())).toEqual(["d", "c", "b", "a"]);138 expect((await pruneBackups(2)).map((d) => d.split("/").pop()).sort()).toEqual(["a", "b"]);139 expect(readdirSync(root).sort()).toEqual(["c", "d"]);140 await expect(createBackup({ outDir: join(root, "d") })).rejects.toThrow(/existe déjà/); // a backup is never written over another141 });142});143144describe("export of all course content and metadata", () => {145 it("contains the working copy, the public manifest, every section, sidecars, history and the journal — and no credential", async () => {146 const { raw, token } = await populated();147 const files = await exportCourse(), byPath = new Map(files.map((f) => [f.path, f.data.toString("utf8")]));148 for (const p of ["LISEZ-MOI.txt", "manifeste-de-travail.json", "manifeste-public.json", "cours.json", "publications.json", "journal.jsonl", "editeurs.json", "seances/S01/seance.json", "seances/S01/quiz.json", "seances/S01/lab.md", "seances/S01/figures.json", "seances/S01/capsules/capsule/capsule.json", "seances/S01/capsules/capsule/captions.fr-CA.aaaaaaaaaa.vtt", "seances/S01/capsules/capsule/transcript.bbbbbbbbbb.json", "seances/S01/ressources.json", "seances/S24/seance.json"]) expect(byPath.has(p), p).toBe(true);149 expect(files.some((f) => /^seances\/S01\/figures\/.+\.svg$/.test(f.path))).toBe(true);150 expect(JSON.parse(byPath.get("manifeste-de-travail.json")!).sessions).toHaveLength(24);151 expect(JSON.parse(byPath.get("publications.json")!).some((p: { target: string; payload: unknown }) => p.target === "S01" && p.payload)).toBe(true);152 expect(byPath.get("journal.jsonl")!.trim().split("\n").length).toBe(listAudit({ limit: 500 }).length);153 const all = files.map((f) => f.data.toString("utf8")).join("\n");154 for (const secret of [raw, token, "token_hash", "public_key"]) expect(all, secret).not.toContain(secret);155 expect(files.some((f) => f.path.endsWith(".pdf") || f.path.endsWith(".mp4"))).toBe(false);156 expect((await exportCourse({ withResources: true })).some((f) => f.path === "seances/S01/ressources/diapositives/v1/diapos.pdf")).toBe(true);157 const tar = gunzipSync(await exportTarGz());158 expect(tar.subarray(257, 262).toString()).toBe("ustar");159 const out = await mkdtemp(join(tmpdir(), "atlas-export-"));160 expect(await exportToDir(out)).toBe(files.length);161 expect(readFileSync(join(out, "seances/S01/lab.md"), "utf8").length).toBeGreaterThan(100);162 await rm(out, { recursive: true, force: true });163 });164});165166describe("health and integrity", () => {167 it("reports each component, and degrades without failing when the worker or ffmpeg is missing", async () => {168 await freshDataDir();169 const none = await healthDetails();170 expect(none.checks.database).toMatchObject({ ok: true, schema: 0 }); // no database yet: the site serves the snapshot171 expect(none.checks.content.source).toBe("snapshot");172 expect(existsSync(join(process.env.ATLAS_DATA_DIR!, "atlas.db"))).toBe(false); // asking for health creates nothing173 await populated();174 process.env.ATLAS_FFMPEG = "/chemin/inexistant/ffmpeg";175 const h = await healthDetails();176 expect(h.status).toBe("degraded");177 expect(h.checks.database).toMatchObject({ ok: true, integrity: "ok" });178 expect(h.checks.content).toMatchObject({ ok: true, source: "studio", sessions: 24, published: 1 });179 expect(h.checks.worker).toMatchObject({ ok: false, state: "absent" });180 expect(h.checks.ffmpeg.ok).toBe(false);181 expect(h.checks.ffmpeg.message).toMatch(/ffmpeg est introuvable/);182 beat("w1");183 expect((await healthDetails()).checks.worker).toMatchObject({ ok: true, state: "ok" });184 run("DELETE FROM publications WHERE target = 'course'");185 expect((await healthDetails()).status).toBe("error"); // no public plan: the site has nothing valid to show186 });187188 it("measures storage and warns against the budget", async () => {189 await populated();190 const u = await storageUsage(true);191 expect(u.parts.media.files).toBe(6); expect(u.parts.masters.bytes).toBe(26); expect(u.parts.resources.files).toBe(1); expect(u.parts.database.bytes).toBeGreaterThan(10_000);192 expect(u.usedBytes).toBe(Object.values(u.parts).reduce((a, p) => a + p.bytes, 0));193 process.env.ATLAS_QUOTA_GB = "1"; await put("masters/gros.bin", Buffer.alloc(1)); 194 expect((await storageUsage(true)).quotaBytes).toBe(1e9);195 delete process.env.ATLAS_QUOTA_GB;196 });197198 it("finds broken things: missing files, altered resources, bad links, invalid sections", async () => {199 await populated();200 const clean = await checkLinks({ deep: false });201 expect(clean.findings.filter((f) => f.level === "error").map((f) => f.message)).toEqual([]);202 expect(clean.stats).toMatchObject({ sessions: 24, published: 1, resourceFiles: 1 });203 expect((await checkLinks({ deep: true })).findings.map((f) => f.message).join(" ")).toMatch(/somme de contrôle SHA-256 différente/); // the recorded checksum of the fixture is not the file's204 await rm(join(dir, "resources/S01/abc/diapos.pdf"));205 await rm(join(dir, "media/S01/capsule/r1/fallback.mp4"));206 putSection("S01", "lab", { body: "Voir [la séance 2](/seances/02-inexistante), [le programme](/programme), [ailleurs](https://example.org/x) et [piège](javascript:alert(1))." }, "ed");207 db().prepare("UPDATE blobs SET body = ? WHERE sha256 = (SELECT sha256 FROM sections WHERE session_id = 'S02' AND key = 'quiz')").run(Buffer.from('{"pas": "un quiz"}'));208 const r = await checkLinks();209 const errors = r.findings.filter((f) => f.level === "error").map((f) => `${f.where} — ${f.message}`).join("\n");210 expect(errors).toMatch(/ressource « Diapositives » — fichier absent/);211 expect(errors).toMatch(/fichier absent du stockage : MP4/);212 expect(errors).toMatch(/EN LIGNE — un fichier de la capsule publiée/);213 expect(errors).toMatch(/lien interne vers une page qui n'existe pas : \/seances\/02-inexistante/);214 expect(errors).toMatch(/lien de schéma interdit/);215 expect(errors).toMatch(/S02 .* quiz — contenu qui ne respecte plus son schéma/);216 expect(errors).not.toMatch(/\/programme/);217 expect(r.findings.find((f) => f.level === "info")!.message).toMatch(/lien\(s\) vers d'autres sites .* ne contacte aucune adresse/);218 });219});220