Repository Public
1/**2 * Backup, restore and export of the studio's state.3 *4 * A backup is a directory:5 * atlas.db a consistent snapshot of the database, taken with VACUUM INTO while the site runs6 * resources/** every downloadable file (all versions)7 * media/** the small, irreplaceable files next to the videos: captions, transcripts, chapters8 * (and everything else under media/ with `withMedia`)9 * masters/** the original videos, only with `withMasters` — they are large; copy them with rsync otherwise10 * media-manifest.json every file under media/ and masters/ with its size (and SHA-256 when known), so a11 * restore can tell exactly which large files still have to be brought back12 * backup.json what the backup contains, with the SHA-256 of every file in it13 *14 * Restore verifies every checksum before touching the target, never overwrites an existing database without15 * `force` (and then keeps the old one aside), and replays migrations forward.16 */17import { createHash } from "node:crypto";18import { createReadStream, existsSync } from "node:fs";19import { copyFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";20import { dirname, join, relative, resolve, sep } from "node:path";21import { DatabaseSync } from "node:sqlite";22import { gzipSync } from "node:zlib";23import { Figures } from "../modules/content-schema/schema";24import { TAR_END, tarEntry } from "./archive";25import { getBlob, getBlobText, getJson } from "./audit";26import { listEditors } from "./auth";27import { getCourseRow, isBootstrapped, listCapsules, listResources, listSections, listSessions, workingManifest } from "./content";28import { MIGRATIONS, all, db, dbPath, openDb } from "./db";29import { COURSE_TARGET, history, publicManifest, sessionStatus } from "./publish";30import { paths } from "./storage";31import { readSidecar } from "./uploads";3233export interface BackupFile { path: string; bytes: number; sha256: string }34export interface BackupManifest {35 format: 1; createdAt: string; app: string; schema: { version: number; migrations: string[] };36 includes: { resources: true; sidecars: true; media: boolean; masters: boolean };37 files: BackupFile[];38 counts: { sessions: number; publications: number; audit: number; resources: number; mediaFiles: number; masters: number };39}40export interface MediaManifest { createdAt: string; files: { root: "media" | "masters"; path: string; bytes: number; sha256: string | null; inBackup: boolean }[] }4142const hashFile = (file: string) => new Promise<string>((res, rej) => { const h = createHash("sha256"); createReadStream(file).on("data", (d) => h.update(d)).on("end", () => res(h.digest("hex"))).on("error", rej); });43async function walk(dir: string, base = dir): Promise<string[]> {44 const out: string[] = [];45 for (const e of await readdir(dir, { withFileTypes: true }).catch(() => [])) {46 if (e.isDirectory()) out.push(...(await walk(join(dir, e.name), base)));47 else if (e.isFile()) out.push(relative(base, join(dir, e.name)).split(sep).join("/"));48 }49 return out.sort();50}51const SIDECAR = /\.(vtt|json)$/;52const stamp = (d = new Date()) => d.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");53const appVersion = async () => { try { return (JSON.parse(await readFile(resolve("package.json"), "utf8")) as { version: string }).version; } catch { return "inconnue"; } };5455export async function createBackup(o: { outDir?: string; withMedia?: boolean; withMasters?: boolean } = {}): Promise<{ dir: string; manifest: BackupManifest }> {56 const dir = resolve(/* turbopackIgnore: true */ o.outDir ?? join(/* turbopackIgnore: true */ paths.backups, stamp()));57 if (existsSync(/* turbopackIgnore: true */ dir) && (await readdir(/* turbopackIgnore: true */ dir)).length) throw new Error(`Le dossier de sauvegarde existe déjà et n'est pas vide : ${dir}`);58 await mkdir(dir, { recursive: true, mode: 0o700 });59 const files: BackupFile[] = [];60 const add = async (rel: string) => { const f = join(/* turbopackIgnore: true */ dir, rel); files.push({ path: rel, bytes: (await stat(/* turbopackIgnore: true */ f)).size, sha256: await hashFile(f) }); };61 const copy = async (from: string, rel: string) => { await mkdir(dirname(join(/* turbopackIgnore: true */ dir, rel)), { recursive: true }); await copyFile(/* turbopackIgnore: true */ from, join(/* turbopackIgnore: true */ dir, rel)); await add(rel); };6263 // A transactionally consistent copy, taken without stopping the site or the worker.64 const target = join(dir, "atlas.db");65 if (target.includes("'")) throw new Error("Chemin de sauvegarde invalide.");66 db().exec(`VACUUM INTO '${target}'`);67 await add("atlas.db");6869 for (const rel of await walk(paths.resources)) await copy(join(paths.resources, rel), `resources/${rel}`);70 const media: MediaManifest = { createdAt: new Date().toISOString(), files: [] };71 for (const rel of await walk(paths.media)) {72 const keep = o.withMedia || SIDECAR.test(rel), size = (await stat(join(paths.media, rel))).size;73 if (keep) await copy(join(paths.media, rel), `media/${rel}`);74 media.files.push({ root: "media", path: rel, bytes: size, sha256: keep ? files[files.length - 1]!.sha256 : null, inBackup: Boolean(keep) });75 }76 for (const rel of await walk(paths.masters)) {77 if (o.withMasters) await copy(join(paths.masters, rel), `masters/${rel}`);78 // A master is stored under its own SHA-256: the name is the checksum.79 media.files.push({ root: "masters", path: rel, bytes: (await stat(join(paths.masters, rel))).size, sha256: /^([a-f0-9]{64})\./.exec(rel)?.[1] ?? null, inBackup: Boolean(o.withMasters) });80 }81 await writeFile(join(dir, "media-manifest.json"), `${JSON.stringify(media, null, 2)}\n`);82 await add("media-manifest.json");8384 const count = (sql: string) => (db().prepare(sql).get() as { n: number }).n;85 const manifest: BackupManifest = {86 format: 1, createdAt: new Date().toISOString(), app: await appVersion(),87 schema: { version: MIGRATIONS.length, migrations: MIGRATIONS.map((m) => m.name) },88 includes: { resources: true, sidecars: true, media: Boolean(o.withMedia), masters: Boolean(o.withMasters) },89 files,90 counts: {91 sessions: count("SELECT count(*) AS n FROM course_sessions"), publications: count("SELECT count(*) AS n FROM publications"), audit: count("SELECT count(*) AS n FROM audit"),92 resources: count("SELECT count(*) AS n FROM resource_versions"), mediaFiles: media.files.filter((f) => f.root === "media").length, masters: media.files.filter((f) => f.root === "masters").length,93 },94 };95 await writeFile(join(dir, "backup.json"), `${JSON.stringify(manifest, null, 2)}\n`);96 return { dir, manifest };97}9899/** Lists the backups of a directory, newest first. */100export async function listBackups(root = paths.backups): Promise<{ dir: string; manifest: BackupManifest; bytes: number }[]> {101 const out: { dir: string; manifest: BackupManifest; bytes: number }[] = [];102 for (const e of await readdir(root, { withFileTypes: true }).catch(() => [])) {103 if (!e.isDirectory()) continue;104 try { const manifest = JSON.parse(await readFile(join(root, e.name, "backup.json"), "utf8")) as BackupManifest; out.push({ dir: join(root, e.name), manifest, bytes: manifest.files.reduce((a, f) => a + f.bytes, 0) }); } catch { /* not a backup */ }105 }106 return out.sort((a, b) => b.manifest.createdAt.localeCompare(a.manifest.createdAt));107}108109/** Retention: keeps the `keep` most recent backups of the directory and deletes the others. */110export async function pruneBackups(keep: number, root = paths.backups): Promise<string[]> {111 const old = (await listBackups(root)).slice(Math.max(1, keep)), removed: string[] = [];112 for (const b of old) { await rm(b.dir, { recursive: true, force: true }); removed.push(b.dir); }113 return removed;114}115116/** Checks that every file listed in backup.json is present and intact. */117export async function verifyBackup(dir: string): Promise<{ manifest: BackupManifest; problems: string[] }> {118 const manifest = JSON.parse(await readFile(join(dir, "backup.json"), "utf8")) as BackupManifest, problems: string[] = [];119 if (manifest.format !== 1) problems.push(`format de sauvegarde inconnu : ${String(manifest.format)}`);120 for (const f of manifest.files) {121 if (f.path.split("/").includes("..") || f.path.startsWith("/")) { problems.push(`chemin dangereux dans la sauvegarde : ${f.path}`); continue; }122 const s = await stat(join(dir, f.path)).catch(() => null);123 if (!s) problems.push(`fichier manquant : ${f.path}`);124 else if (s.size !== f.bytes || (await hashFile(join(dir, f.path))) !== f.sha256) problems.push(`fichier altéré : ${f.path}`);125 }126 return { manifest, problems };127}128129export interface RestoreReport { dataDir: string; restoredFiles: number; replacedDatabase: string | null; migrationsApplied: string[]; integrity: string; missingMedia: { root: string; path: string; bytes: number }[] }130131/**132 * Restores a backup into a data directory. Stop the web server and the worker first: they hold the database133 * open. Refuses a damaged backup, and an existing database unless `force` (the old one is then kept aside).134 */135export async function restoreBackup(backupDir: string, dataDir: string, o: { force?: boolean } = {}): Promise<RestoreReport> {136 const src = resolve(backupDir), dest = resolve(dataDir);137 const { manifest, problems } = await verifyBackup(src);138 if (problems.length) throw new Error(`Sauvegarde refusée : ${problems.slice(0, 5).join(" ; ")}${problems.length > 5 ? ` (et ${problems.length - 5} autres)` : ""}`);139 if (manifest.schema.version > MIGRATIONS.length) throw new Error("Cette sauvegarde vient d'une version plus récente de l'application : mettez l'application à jour avant de restaurer.");140 await mkdir(dest, { recursive: true, mode: 0o700 });141 let replaced: string | null = null;142 const target = dbPath(dest);143 if (existsSync(target)) {144 if (!o.force) throw new Error(`Une base existe déjà dans ${dest}. Relancez avec --force pour la remplacer (elle sera conservée à côté).`);145 replaced = `${target}.remplacee-${stamp()}`;146 await rename(target, replaced);147 for (const ext of ["-wal", "-shm"]) await rm(`${target}${ext}`, { force: true }); // the snapshot is self-contained; a stale journal must not be replayed onto it148 }149 for (const f of manifest.files) {150 if (f.path === "media-manifest.json") continue;151 const to = join(dest, f.path);152 if (!resolve(to).startsWith(dest + sep)) throw new Error(`Chemin dangereux dans la sauvegarde : ${f.path}`);153 await mkdir(dirname(to), { recursive: true });154 await copyFile(join(src, f.path), to);155 }156 // Open once to bring the schema forward and check the file; closed again at once.157 const before = (() => { const d = new DatabaseSync(target); try { return (d.prepare("SELECT count(*) AS n FROM schema_migrations").get() as { n: number }).n; } finally { d.close(); } })();158 const restored = openDb(target);159 let integrity: string;160 try { integrity = (restored.prepare("PRAGMA integrity_check").get() as { integrity_check: string }).integrity_check; } finally { restored.close(); }161 const media = JSON.parse(await readFile(join(src, "media-manifest.json"), "utf8")) as MediaManifest, missing: RestoreReport["missingMedia"] = [];162 for (const f of media.files) { const s = await stat(join(dest, f.root, f.path)).catch(() => null); if (!s || s.size !== f.bytes) missing.push({ root: f.root, path: f.path, bytes: f.bytes }); }163 return { dataDir: dest, restoredFiles: manifest.files.length - 1, replacedDatabase: replaced, migrationsApplied: MIGRATIONS.slice(before).map((m) => m.name), integrity, missingMedia: missing };164}165166/* ---- Export of all course content and metadata ---- */167168export interface ExportFile { path: string; data: Buffer }169170/**171 * Everything the studio knows about the course, as plain files: the working copy and the public manifest,172 * every section body, figures, capsule metadata with captions, transcripts and chapters, the resource index,173 * the publication history with its snapshots, and the audit log. No credential, session or token is exported.174 */175export async function exportCourse(o: { withResources?: boolean } = {}): Promise<ExportFile[]> {176 if (!isBootstrapped()) throw new Error("Le studio ne contient pas encore de cours.");177 const files: ExportFile[] = [], json = (v: unknown) => Buffer.from(`${JSON.stringify(v, null, 2)}\n`);178 const put = (path: string, data: Buffer | string | null) => { if (data !== null) files.push({ path, data: typeof data === "string" ? Buffer.from(data) : data }); };179 put("LISEZ-MOI.txt", ["ATLAS IA — exportation du studio", `Créée le ${new Date().toISOString()}`, "",180 "manifeste-de-travail.json la copie de travail complète (états, visibilités), au format du manifeste",181 "manifeste-public.json ce que le site public montre en ce moment",182 "cours.json identité, parties, licence, schémas, redirections",183 "seances/<id>/seance.json plan, état et publication de la séance",184 "seances/<id>/<section> quiz.json, glossary.json, bibliography.json, figures.json, lab.md, script.md",185 "seances/<id>/capsules/ métadonnées, sous-titres, transcriptions et chapitres (les vidéos ne sont pas exportées)",186 "seances/<id>/ressources.json index des ressources et de leurs versions (SHA-256)",187 "publications.json historique complet des publications, avec leurs instantanés",188 "journal.jsonl journal d'audit", "editeurs.json noms et rôles (aucune clé, aucun jeton)", ""].join("\n"));189 put("manifeste-de-travail.json", json(workingManifest()));190 put("manifeste-public.json", json(publicManifest()));191 put("cours.json", json(getCourseRow().data));192 const pubs: unknown[] = history(COURSE_TARGET).map((e) => ({ ...e, payload: getJson(e.payloadSha) }));193 for (const s of listSessions()) {194 const base = `seances/${s.id}`;195 put(`${base}/seance.json`, json({ id: s.id, state: s.state, inSource: s.inSource, ...s.data, status: sessionStatus(s), updatedAt: s.updatedAt, updatedBy: s.updatedBy }));196 for (const sec of listSections(s.id)) {197 const text = getBlobText(sec.sha256);198 put(`${base}/${sec.key}.${sec.key === "lab" || sec.key === "script" ? "md" : "json"}`, text);199 if (sec.key === "figures" && text) { const f = Figures.safeParse(JSON.parse(text)); for (const fig of f.success ? f.data.figures : []) put(`${base}/${fig.file}`, getBlob(fig.sha256)); }200 }201 for (const c of listCapsules(s.id)) {202 put(`${base}/capsules/${c.id}/capsule.json`, json({ id: c.id, position: c.position, status: c.status, masterSha256: c.masterSha, ...c.data }));203 for (const key of [c.data.media.transcript, c.data.media.chapters, ...c.data.media.captions.map((t) => t.path)]) if (key) put(`${base}/capsules/${c.id}/${key.split("/").pop()!}`, await readSidecar(key));204 }205 const resources = listResources(s.id);206 if (resources.length) put(`${base}/ressources.json`, json(resources));207 if (o.withResources) for (const r of resources) for (const v of r.versions) { const b = await readFile(join(paths.resources, v.path)).catch(() => null); put(`${base}/ressources/${r.id}/v${v.version}/${v.filename}`, b); }208 pubs.push(...history(s.id).map((e) => ({ ...e, payload: getJson(e.payloadSha) })));209 }210 put("publications.json", json(pubs));211 const rows = all<Record<string, unknown>>("SELECT * FROM audit ORDER BY id");212 put("journal.jsonl", rows.map((r) => JSON.stringify(r)).join("\n") + (rows.length ? "\n" : ""));213 put("editeurs.json", json(listEditors().map((e) => ({ id: e.id, name: e.name, role: e.role, createdAt: e.created_at, disabledAt: e.disabled_at }))));214 return files;215}216217export async function exportTarGz(o: { withResources?: boolean } = {}): Promise<Buffer> {218 const root = `atlas-ia-export-${stamp()}`, at = new Date();219 return gzipSync(Buffer.concat([...(await exportCourse(o)).map((f) => tarEntry(`${root}/${f.path}`, f.data, at)), TAR_END]));220}221222export async function exportToDir(dir: string, o: { withResources?: boolean } = {}): Promise<number> {223 const files = await exportCourse(o);224 for (const f of files) { const to = join(resolve(dir), f.path); await mkdir(dirname(to), { recursive: true }); await writeFile(to, f.data); }225 return files.length;226}227