SPB Git

Repository Public

studio.spec.ts 56.9 KB 783 lines typescript

1import { readFileSync } from "node:fs";2import { resolve } from "node:path";3import AxeBuilder from "@axe-core/playwright";4import { expect, test, type APIRequestContext, type Browser, type BrowserContext, type Page } from "@playwright/test";5import { STUDIO } from "../playwright.config";6import { WORDS } from "./studio-fixtures";78/**9 * The studio journey, end to end, on a throw-away database with a real media worker:10 * enrol with a one-time link → sign in with a passkey → import the course snapshot → edit a session →11 * upload a small synthetic video → wait for the worker → captions → private preview → publish → check as an12 * anonymous visitor → edit → publish again → roll back → withdraw → check that it is gone.13 * The passkey is held by a virtual authenticator (Chromium DevTools Protocol): no real device is involved.14 */15test.describe.configure({ mode: "serial" });1617const BASE = STUDIO.base, FIX = resolve("e2e/.tmp/studio/fixtures"), S01 = "S01", SLUG = "01-ia-ia-generative-et-llm";18const state = () => JSON.parse(readFileSync("e2e/.tmp/studio/state.json", "utf8")) as { enrol: string };19const fixture = (name: string) => resolve(FIX, name);2021let ctx: BrowserContext, page: Page;2223async function withAuthenticator(context: BrowserContext, p: Page) {24  const cdp = await context.newCDPSession(p);25  await cdp.send("WebAuthn.enable");26  await cdp.send("WebAuthn.addVirtualAuthenticator", { options: { protocol: "ctap2", transport: "internal", hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true } });27}28/** A visitor who has never been to the studio: new context, no cookie, no storage. */29async function anonymous(browser: Browser, fn: (p: Page, c: BrowserContext) => Promise<void>) {30  const c = await browser.newContext({ baseURL: BASE, locale: "fr-CA" }), p = await c.newPage();31  try { await fn(p, c); expect(await c.cookies(), "aucun témoin pour un visiteur anonyme").toEqual([]); } finally { await c.close(); }32}33/** Forces the theme before first paint, whatever this browser profile stored earlier (the studio pages share one profile). */34async function setTheme(p: Page, theme: "light" | "dark") {35  await p.addInitScript((t) => {36    try { const s = JSON.parse(localStorage.getItem("atlas.v1") || "null") ?? { v: 1, updatedAt: new Date(0).toISOString(), prefs: {}, capsules: {}, bookmarks: {}, notes: {}, quizzes: {}, done: {} }; s.prefs = { ...s.prefs, theme: t }; localStorage.setItem("atlas.v1", JSON.stringify(s)); } catch { /* storage unavailable */ }37  }, theme);38}39const csrf = (p: Page) => p.locator('meta[name="atlas-csrf"]').getAttribute("content");40/** Calls the studio API with the signed-in browser's cookie and CSRF token. */41async function call(p: Page, method: string, path: string, data?: unknown, headers: Record<string, string> = {}) {42  return p.request.fetch(`${BASE}/admin/api/${path}`, { method, data: data === undefined ? undefined : JSON.stringify(data), headers: { "content-type": "application/json", origin: BASE, "x-csrf-token": (await csrf(p)) ?? "", ...headers } });43}44const openTab = async (name: RegExp) => { await page.getByRole("tab", { name }).click(); };45const editor = async (id = S01, tab?: RegExp) => { await page.goto(`/admin/seances/${id}`); await expect(page.getByTestId("session-editor")).toBeVisible(); if (tab) await openTab(tab); };4647test.beforeAll(async ({ browser }) => {48  ctx = await browser.newContext({ baseURL: BASE, locale: "fr-CA", viewport: { width: 1440, height: 900 } });49  page = await ctx.newPage();50  await withAuthenticator(ctx, page);51});52test.afterAll(async () => { await ctx.close(); });5354/* ------------------------------------------------------------------ authentication */5556test("le studio est fermé sans session, et rien ne l’indexe", async ({ request }) => {57  await page.goto("/admin");58  await expect(page).toHaveURL(/\/admin\/connexion$/);59  await expect(page.getByTestId("no-passkey")).toBeVisible(); // nothing enrolled yet: no button to try60  await expect(page.getByTestId("passkey-login")).toHaveCount(0);61  await expect(page.locator('meta[name="robots"]')).toHaveAttribute("content", /noindex/);62  for (const path of ["/admin/seances", "/admin/seances/S01", "/admin/cours", "/admin/importation", "/admin/traitements", "/admin/outils", "/admin/journal", "/admin/acces", `/admin/apercu/seances/${SLUG}`]) {63    const r = await request.get(BASE + path, { maxRedirects: 0 });64    expect(r.status(), path).toBe(307);65    expect(r.headers().location).toBe("/admin/connexion");66    expect(r.headers()["x-robots-tag"]).toContain("noindex");67    expect(r.headers()["cache-control"]).toContain("no-store");68  }69  const sitemap = await (await request.get(`${BASE}/sitemap.xml`)).text(), robots = await (await request.get(`${BASE}/robots.txt`)).text();70  expect(sitemap).not.toContain("/admin");71  expect(robots).toContain("Disallow: /admin");72  expect(await ctx.cookies()).toEqual([]); // visiting the sign-in page sets nothing73});7475test("un lien d’enrôlement invalide est refusé", async () => {76  await page.goto("/admin/enrolement?jeton=ceci-n-est-pas-un-vrai-jeton-0123456789");77  await expect(page.getByTestId("enrol-invalid")).toBeVisible();78  await expect(page.getByTestId("passkey-enrol")).toHaveCount(0);79  const r = await page.request.post(`${BASE}/admin/api/auth/register/options`, { data: { token: "ceci-n-est-pas-un-vrai-jeton-0123456789" }, headers: { origin: BASE } });80  expect(r.status()).toBe(403);81});8283test("l’enrôlement à usage unique crée une clé d’accès et ouvre une session", async ({ browser }) => {84  await page.goto(state().enrol);85  await expect(page.locator("main")).toContainText("Enseignant d’essai");86  await page.getByTestId("passkey-enrol").click();87  await expect(page.getByTestId("studio-dashboard")).toBeVisible();88  await expect(page.getByTestId("editor-name")).toHaveText("Enseignant d’essai");89  const cookies = await ctx.cookies();90  const session = cookies.find((c) => c.name === "atlas_studio")!;91  expect(session).toMatchObject({ httpOnly: true, sameSite: "Strict", path: "/admin" });92  expect(cookies.every((c) => c.path.startsWith("/admin")), "aucun témoin hors de /admin").toBe(true);93  // The public pages do not even receive the editor's cookie.94  const seen: string[] = [];95  page.on("request", (r) => { const u = new URL(r.url()); if (!u.pathname.startsWith("/admin") && r.headers().cookie) seen.push(u.pathname); });96  await page.goto("/programme"); await page.goto("/admin");97  expect(seen).toEqual([]);98  // The link is dead after one use.99  const other = await browser.newContext({ baseURL: BASE }); const p = await other.newPage();100  await p.goto(state().enrol);101  await expect(p.getByTestId("enrol-invalid")).toBeVisible();102  await other.close();103});104105test("fermer la session, puis rouvrir avec la clé d’accès ; un autre navigateur est refusé", async ({ browser }) => {106  const before = (await ctx.cookies()).find((c) => c.name === "atlas_studio")!.value, token = await csrf(page);107  await page.getByTestId("logout").click();108  await expect(page).toHaveURL(/\/admin\/connexion$/);109  // The closed session is dead on the server: replaying its cookie and its CSRF token gets nothing.110  const replay = await browser.newContext({ baseURL: BASE });111  await replay.addCookies([{ name: "atlas_studio", value: before, domain: "localhost", path: "/admin" }]);112  expect((await replay.request.get(`${BASE}/admin/api/dashboard`)).status()).toBe(401);113  expect((await replay.request.post(`${BASE}/admin/api/sessions`, { data: { title: "x", short: "x", part: "I", level: "débutant" }, headers: { origin: BASE, "x-csrf-token": token ?? "" } })).status()).toBe(401);114  await replay.close();115116  await page.goto("/admin"); await expect(page).toHaveURL(/\/admin\/connexion$/);117  await page.getByTestId("passkey-login").click();118  await expect(page.getByTestId("studio-dashboard")).toBeVisible();119  expect((await ctx.cookies()).find((c) => c.name === "atlas_studio")!.value).not.toBe(before); // a new session identifier at every sign-in120121  const other = await browser.newContext({ baseURL: BASE }); const p = await other.newPage();122  await withAuthenticator(other, p); // an authenticator, but not the enrolled key123  await p.goto("/admin/connexion");124  await p.getByTestId("passkey-login").click();125  await expect(p.getByTestId("passkey-error")).toBeVisible({ timeout: 20_000 });126  await p.goto("/admin"); await expect(p).toHaveURL(/\/admin\/connexion$/);127  await other.close();128});129130test("tableau de bord : état réel du système", async () => {131  await page.goto("/admin");132  const health = page.getByTestId("health-panel");133  for (const check of ["database", "content", "storage", "ffmpeg", "worker"]) await expect(health.locator(`[data-check="${check}"]`), check).toHaveAttribute("data-ok", "true", { timeout: 20_000 });134  await expect(page.getByTestId("ffmpeg-missing")).toHaveCount(0);135  await expect(page.getByTestId("worker-absent")).toHaveCount(0);136  await expect(page.getByTestId("stat-Publiées")).toContainText("0");137  await expect(page.getByTestId("stat-Publiées")).toContainText("sur 24");138});139140/* ------------------------------------------------------------------ import from the course repository */141142test("importation : différences, conflit jamais écrasé en silence, brouillons seulement", async ({ browser }) => {143  // The instructor edits S05's title in the studio first; nothing of this will be touched by the import.144  await editor("S05");145  await page.getByTestId("field-title").fill("Titre retouché dans le studio");146  await page.getByTestId("save-meta").click();147  await expect(page.locator("main")).toContainText("Fiche enregistrée");148  // …and S01's title too: the repository also changed that one → a conflict.149  await editor(S01);150  await page.getByTestId("field-title").fill("Titre de S01 choisi dans le studio");151  await page.getByTestId("save-meta").click();152  await expect(page.locator("main")).toContainText("Fiche enregistrée");153154  await page.goto("/admin/importation");155  await page.getByTestId("read-repo").click();156  const diff = page.getByTestId("import-diff");157  await expect(diff).toBeVisible({ timeout: 30_000 });158  await expect(page.getByTestId("diff-counts")).toContainText("1 séance(s) nouvelle(s)");159  await expect(page.getByTestId("diff-counts")).toContainText("1 conflit(s)");160  await expect(diff.locator('[data-diff-session="S25"]')).toContainText(WORDS.newSession);161  const conflict = diff.locator('[data-change="S01.title"]');162  await expect(conflict).toHaveAttribute("data-kind", "conflict");163  await expect(conflict).toContainText("Titre de S01 choisi dans le studio");164  await expect(conflict).toContainText("révisé dans le dépôt");165  await expect(conflict.getByLabel("Garder ma version")).toBeChecked(); // the default never overwrites166  await expect(diff.locator('[data-change="S01.section.quiz"]')).toHaveAttribute("data-kind", "update");167  await expect(diff.locator('[data-change="S01.section.lab"]')).toHaveAttribute("data-kind", "update");168  await expect(diff.locator('[data-change="S05.title"]')).toHaveCount(0); // the repository did not change it: no proposal to undo the local edit169  await expect(diff).toContainText("avertissement(s) de lecture"); // S02 is half-written, 22 sessions have no directory: tolerated170171  await page.getByTestId("apply-import").click();172  await expect(page.getByTestId("confirm-import")).toContainText("Le site public ne change pas.");173  await page.getByTestId("confirm-import-ok").click();174  await expect(page.getByTestId("import-result")).toContainText("Rien n’a été publié");175176  await page.goto("/admin/seances");177  await expect(page.locator('tr[data-session="S25"]')).toContainText("Planifiée"); // a plan without material: not even a draft to read yet178  await expect(page.locator('tr[data-session="S01"]')).toContainText("Titre de S01 choisi dans le studio"); // kept179  await expect(page.locator('tr[data-session="S05"]')).toContainText("Titre retouché dans le studio");180181  // Same source again, this time as an uploaded archive: nothing left to do (idempotent).182  await page.goto("/admin/importation");183  await page.getByTestId("archive-upload-input").setInputFiles(fixture("depot-du-cours.tar.gz"));184  await expect(page.getByTestId("import-empty")).toBeVisible({ timeout: 30_000 });185  await page.getByTestId("discard-import").click();186  await expect(page.getByTestId("read-repo")).toBeVisible();187188  // The public site did not move: 24 sessions, none open, no trace of the imported material or of the new session.189  await anonymous(browser, async (p) => {190    await p.goto("/programme");191    await expect(p.locator("li[data-session]")).toHaveCount(24);192    await expect(p.locator('[data-state="open"]')).toHaveCount(0);193    const index = await (await p.request.get(`${BASE}/recherche/index.json`)).text();194    for (const leak of [WORDS.importedLab, WORDS.newSession, "Titre retouché", "choisi dans le studio"]) expect(index, leak).not.toContain(leak);195    expect(await (await p.request.get(`${BASE}/api/health`)).json()).toEqual({ status: "ok", mode: "production", sessions: 24, published: 0 });196  });197});198199/* ------------------------------------------------------------------ editing */200201test("éditer une séance : fiche, laboratoire en Markdown (rendu sûr), quiz, glossaire", async () => {202  await editor(S01);203  await page.getByTestId("outcomes").getByRole("button", { name: "Ajouter un résultat" }).click();204  await page.getByTestId("outcomes").locator("textarea").last().fill("Reconnaître un résultat ajouté pendant l’essai de bout en bout.");205  await page.getByTestId("save-meta").click();206  await expect(page.locator("main")).toContainText("Fiche enregistrée");207208  await openTab(/Contenus/);209  await page.getByTestId("edit-lab").click();210  const source = page.getByTestId("markdown-source");211  await expect(source).toHaveValue(new RegExp(WORDS.importedLab)); // what the import brought212  await source.fill([213    "# Laboratoire d’essai", "", `Observer un ${WORDS.lab1} dans son milieu.`, "",214    "<script>window.__xss = 1</script>", "", '<img src="x" onerror="window.__xss = 2">', "", "[lien piégé](javascript:window.__xss=3) et [lien sain](https://example.org/doc)", "",215    "Le billet coûte 5 $ et le café 3 $.", "", "Formule : $$E = mc^2$$", "", "```python", "def aire(r):", "    return 3.14159 * r ** 2", "```", "",216    "| Étape | Durée |", "|---|---|", "| Lire | 10 min |",217  ].join("\n"));218  const preview = page.getByTestId("markdown-preview");219  await expect(preview).toContainText(WORDS.lab1);220  await expect(preview.locator(".katex")).toHaveCount(1);                       // LaTeX typeset221  await expect(preview.locator("pre code .hljs-keyword").first()).toHaveText("def"); // code highlighted222  await expect(preview.getByRole("group", { name: /Tableau/ })).toBeVisible();   // accessible table wrapper223  await expect(preview).toContainText("5 $ et le café 3 $");                    // single dollars are not mathematics224  await expect(preview.locator("script, img, [onerror]")).toHaveCount(0);225  await expect(preview.locator('a[href^="javascript"]')).toHaveCount(0);226  await expect(preview.getByRole("link", { name: "lien sain" })).toHaveAttribute("rel", "noopener noreferrer");227  expect(await page.evaluate(() => (window as unknown as { __xss?: number }).__xss)).toBeUndefined();228  await page.getByTestId("save-markdown").click();229  await expect(page.getByTestId("editor-lab")).toContainText("Section enregistrée");230231  await page.getByTestId("edit-quiz").click();232  const quiz = page.getByTestId("quiz-editor");233  await expect(quiz.locator("[data-question-editor]")).toHaveCount(2); // the repository's quiz234  await page.getByTestId("add-question").click();235  const q = quiz.locator("[data-question-editor]").last();236  await q.getByLabel("Énoncé").fill("Question ajoutée dans le studio : que vaut deux plus deux ?");237  await q.getByLabel("Texte du choix A").fill("Trois");238  await q.getByLabel("Texte du choix B").fill("Quatre");239  await q.getByLabel("Le choix B est une bonne réponse").check();240  await q.getByLabel("Explication (affichée après la réponse)").fill("Deux plus deux font quatre.");241  await page.getByTestId("quiz-preview-toggle").click();242  await expect(page.getByTestId("quiz-preview")).toContainText("Question ajoutée dans le studio"); // rendered by the public exercise engine243  await page.getByTestId("save-quiz").click();244  await expect(page.getByTestId("editor-quiz")).toContainText("Section enregistrée");245246  await page.getByTestId("edit-glossary").click();247  await page.getByTestId("add-term").click();248  const term = page.getByTestId("glossary-editor").locator(".rounded-xl").last();249  await term.getByLabel("Terme français").fill("terme d’essai");250  await term.getByLabel("Définition").fill("Définition ajoutée pendant l’essai de bout en bout.");251  await page.getByTestId("save-glossary").click();252  await expect(page.getByTestId("editor-glossary")).toContainText("Section enregistrée");253254  // A stale edit is refused: the same form state cannot be replayed over a newer revision.255  const stale = await call(page, "PATCH", `sessions/${S01}`, { patch: { title: "Ancien onglet" }, rev: 1 });256  expect(stale.status()).toBe(409);257});258259/* ------------------------------------------------------------------ media */260261test("téléverser une vidéo : fichier déguisé refusé, envoi par morceaux, encodage par le processus de traitement", async () => {262  await editor(S01, /Capsules/);263  await page.getByTestId("capsule-title").fill("Introduction d’essai");264  await page.getByTestId("create-capsule").click();265  const capsule = page.getByTestId("capsule-introduction-d-essai");266  await expect(capsule).toHaveAttribute("data-status", "empty");267268  // A web page renamed .mp4: refused on its content, not its name.269  await page.getByTestId("master-introduction-d-essai-input").setInputFiles(fixture("pas-une-video.mp4"));270  await expect(page.getByTestId("master-introduction-d-essai-error")).toContainText("ne correspond pas à son extension", { timeout: 20_000 });271  await expect(capsule).toHaveAttribute("data-status", "empty");272273  await page.getByTestId("master-introduction-d-essai-input").setInputFiles(fixture("capsule.mp4"));274  await expect(capsule).toHaveAttribute("data-status", /queued|processing|ready/, { timeout: 20_000 });275  await expect(capsule).toHaveAttribute("data-status", "ready", { timeout: 120_000 }); // the worker did it, in its own process276  await expect(page.getByTestId("capsule-duration")).toHaveText("0:08");277  await expect(page.getByTestId("capsule-renditions")).toContainText("360p");278  await expect(page.getByTestId("capsule-renditions")).not.toContainText("720p"); // a 360-line source is never upscaled279  await expect(capsule.locator('img[alt^="Affiche"]')).toBeVisible();280281  // The same file again is recognised before anything is sent.282  await page.getByTestId("capsule-title").fill("Reprise du même fichier");283  await page.getByTestId("create-capsule").click();284  await page.getByTestId("master-reprise-du-meme-fichier-input").setInputFiles(fixture("capsule.mp4"));285  await expect(page.getByTestId("duplicate-note")).toContainText("déjà dans le stockage", { timeout: 20_000 });286  await expect(page.getByTestId("capsule-reprise-du-meme-fichier")).toHaveAttribute("data-status", "ready", { timeout: 120_000 });287288  await page.goto("/admin/traitements");289  await expect(page.locator('tr[data-state="succeeded"]')).toHaveCount(2);290  await expect(page.locator('tr[data-state="failed"]')).toHaveCount(0);291});292293test("sous-titres : fichier invalide refusé, fichier valide attaché, minutage, transcription, chapitres", async () => {294  await editor(S01, /Capsules/);295  const capsule = page.getByTestId("capsule-introduction-d-essai");296  await page.getByTestId("captions-introduction-d-essai-input").setInputFiles(fixture("captions-invalides.vtt"));297  await expect(page.getByTestId("captions-introduction-d-essai-error")).toContainText(/chevauchement|fin avant le début/, { timeout: 20_000 });298  await expect(capsule.getByTestId("caption-tracks")).toContainText("Aucun sous-titre");299300  await page.getByTestId("captions-introduction-d-essai-input").setInputFiles(fixture("captions.fr.vtt"));301  await expect(capsule.getByTestId("caption-report")).toContainText("4 répliques validées", { timeout: 20_000 });302  await expect(capsule.getByTestId("caption-tracks")).toContainText("fr-CA");303  await expect(capsule.getByTestId("caption-tracks")).toContainText("Transcription interrogeable attachée"); // imported from the VTT304305  await capsule.getByTestId("timing-preview").click();306  const timing = page.getByTestId("timing-dialog");307  await expect(timing.getByTestId("timing-cues").locator("li")).toHaveCount(4);308  await timing.getByTestId("timing-cues").locator("button").nth(1).click(); // seek to the second cue309  await expect(timing.getByTestId("timing-cues").locator('button[aria-current="true"]')).toContainText(WORDS.caption);310  expect(await timing.locator("video").evaluate((v: HTMLVideoElement) => v.currentTime)).toBeGreaterThanOrEqual(2);311  await timing.getByRole("button", { name: "Fermer" }).click();312313  await capsule.getByTestId("edit-chapters").click();314  const chapters = page.getByTestId("chapters-dialog");315  await chapters.getByLabel("Titre du chapitre 1").fill("Ouverture");316  await chapters.getByTestId("add-chapter").click();317  await chapters.getByLabel("Début du chapitre 2").fill("0:04");318  await chapters.getByLabel("Titre du chapitre 2").fill("Seconde moitié");319  await chapters.getByTestId("save-chapters").click();320  await expect(chapters).toBeHidden();321  await expect(capsule.getByTestId("edit-chapters")).toHaveText("Chapitres");322});323324test("ressources : contenu vérifié, somme de contrôle, remplacement sans briser le lien", async () => {325  await editor(S01, /Ressources/);326  await page.getByTestId("resource-title").fill("Diapositives de la séance");327  await page.getByTestId("resource-upload-input").setInputFiles(fixture("pas-un-pdf.pdf")); // a program named .pdf328  await expect(page.getByTestId("resource-upload-error")).toContainText("ne correspond pas à son extension", { timeout: 20_000 });329  await page.getByTestId("resource-upload-input").setInputFiles(fixture("diapositives.pdf"));330  const res = page.getByTestId("resource-diapositives-de-la-seance");331  await expect(res.locator("p", { hasText: "Version actuelle" })).toContainText("v1 — diapositives.pdf", { timeout: 20_000 });332  await expect(res).toContainText("SHA-256");333  await expect(res).toContainText("/telecharger/S01/diapositives-de-la-seance");334  await res.locator("summary").click();335  await page.getByTestId("replace-diapositives-de-la-seance-input").setInputFiles(fixture("diapositives-v2.pdf"));336  await expect(res.locator("p", { hasText: "Version actuelle" })).toContainText("v2 — diapositives-v2.pdf", { timeout: 20_000 });337  await expect(res).toContainText("historique (2 versions)");338  await expect(res).toContainText("/telecharger/S01/diapositives-de-la-seance"); // same address339  // The same bytes as the current version are not accepted as a « new » version.340  await page.getByTestId("replace-diapositives-de-la-seance-input").setInputFiles(fixture("diapositives-v2.pdf"));341  await expect(page.getByTestId("replace-diapositives-de-la-seance-error")).toContainText("identique à la version actuelle", { timeout: 20_000 });342});343344/* ------------------------------------------------------------------ private preview, publication, public checks */345346const labPublic = async (p: Page) => p.locator("#laboratoire");347const MEDIA = (key: string) => `${BASE}/media/${key}`;348let hls = "", captionPath = "";349350test("aperçu privé : visible de l’éditeur connecté, de personne d’autre", async ({ browser }) => {351  await editor(S01, /Contenus/);352  for (const key of ["lab", "quiz", "glossary"]) await page.locator(`tr[data-section="${key}"] select`).selectOption("public");353  await expect(page.locator('tr[data-section="glossary"] select')).toHaveValue("public");354  await openTab(/Capsules/);355  await page.getByTestId("capsule-introduction-d-essai").getByLabel(/Visibilité de la capsule/).selectOption("public");356  await expect(page.getByTestId("capsule-introduction-d-essai").getByLabel(/Visibilité de la capsule/)).toHaveValue("public");357  await openTab(/Ressources/);358  await page.getByTestId("resource-diapositives-de-la-seance").getByLabel(/Visibilité de la ressource/).selectOption("public");359  await expect(page.getByTestId("resource-diapositives-de-la-seance").getByLabel(/Visibilité de la ressource/)).toHaveValue("public");360  await page.getByTestId("resource-diapositives-de-la-seance").getByLabel("Permis").click(); // saved on the server, then shown checked361  await expect(page.getByTestId("resource-diapositives-de-la-seance").getByLabel("Permis")).toBeChecked();362  await openTab(/Publication/);363  await expect(page.getByTestId("to-draft")).toBeVisible(); // S01 is in the « preview » state364  await expect(page.getByTestId("publish-panel")).toContainText("Capsule « Introduction d’essai »");365  await expect(page.getByTestId("publish-panel")).toContainText("Capsule « Reprise du même fichier » — privée");366367  const detail = await (await call(page, "GET", `sessions/${S01}`)).json() as { session: { capsuleRows: { id: string; data: { media: { hls: string; captions: { path: string }[] } } }[] } };368  const media = detail.session.capsuleRows.find((c) => c.id === "introduction-d-essai")!.data.media;369  hls = media.hls; captionPath = media.captions[0]!.path;370371  await page.goto(`/admin/apercu/seances/${SLUG}`);372  await expect(page.getByTestId("private-preview-banner")).toBeVisible();373  await expect(page.locator("article")).toHaveAttribute("data-access", "open");374  await expect(page.locator("#laboratoire")).toContainText(WORDS.lab1);375  await expect(page.locator("[data-question]").first()).toBeVisible();376  await page.getByTestId("start-watching").click();377  await expect(page).toHaveURL(/\/admin\/apercu\/seances\/.+\/regarder/); // navigation stays inside the preview378  await expect.poll(async () => page.locator("video").evaluate((v: HTMLVideoElement) => v.readyState), { timeout: 20_000 }).toBeGreaterThanOrEqual(1);379380  // Nobody else: not the page, not the media, not the search index, by any address.381  await anonymous(browser, async (p) => {382    const r = await p.request.get(`${BASE}/admin/apercu/seances/${SLUG}`, { maxRedirects: 0 });383    expect(r.status()).toBe(307);384    for (const url of [MEDIA(hls), MEDIA(hls.replace("master.m3u8", "fallback.mp4")), MEDIA(hls.replace("master.m3u8", "v360/index.m3u8")), MEDIA(hls.replace("master.m3u8", "v360/seg_00000.ts")), MEDIA(captionPath), `${BASE}/admin/apercu/media/${hls}`, `${BASE}/admin/api/sessions/${S01}/sections/quiz`, `${BASE}/telecharger/S01/diapositives-de-la-seance`]) {385      expect((await p.request.get(url, { maxRedirects: 0 })).status(), url).toBeGreaterThanOrEqual(401);386    }387    await p.goto(`/seances/${SLUG}`);388    await expect(p.locator("article")).toHaveAttribute("data-access", "upcoming");389    await expect(p.locator("body")).not.toContainText(WORDS.lab1);390    const index = await (await p.request.get(`${BASE}/recherche/index.json`)).text();391    for (const leak of [WORDS.lab1, WORDS.caption, "Deux plus deux font quatre", "terme d’essai"]) expect(index, leak).not.toContain(leak);392    expect(await (await p.request.get(`${BASE}/sitemap.xml`)).text()).not.toContain("regarder");393  });394});395396test("publier : confirmation explicite, puis visible de tous sans compte ni témoin", async ({ browser }) => {397  await editor(S01, /Publication/);398  await page.getByTestId("publish-now").click();399  const dialog = page.getByTestId("confirm-publish");400  await expect(dialog.getByTestId("will-publish")).toContainText("Laboratoire");401  await expect(dialog.getByTestId("will-publish")).toContainText("Capsule « Introduction d’essai »");402  await expect(page.getByTestId("session-editor")).toHaveAttribute("data-public", "none"); // nothing happens before the explicit button403  await page.getByTestId("confirm-publish-ok").click();404  await expect(page.getByTestId("session-editor")).toHaveAttribute("data-public", "published");405  await expect(page.getByTestId("history-panel").locator('tr[data-version="1"]')).toContainText("En vigueur");406407  await anonymous(browser, async (p) => {408    // No rebuild, no restart: the next request sees it.409    await p.goto(`/seances/${SLUG}`);410    await expect(p.locator("article")).toHaveAttribute("data-access", "open");411    await expect(p.getByRole("heading", { level: 1 })).toHaveText("Titre de S01 choisi dans le studio");412    await expect(await labPublic(p)).toContainText(WORDS.lab1);413    await expect(p.locator("#laboratoire .katex")).toHaveCount(1);414    await expect(p.locator("#laboratoire script, #laboratoire img")).toHaveCount(0);415    await expect(p.locator("[data-question]")).toHaveCount(3);416    await expect(p.locator("#glossaire")).toContainText("terme d’essai");417    await expect(p.locator('[data-capsule="introduction-d-essai"]')).toBeVisible();418    await expect(p.locator('[data-capsule="reprise-du-meme-fichier"]')).toHaveCount(0); // private capsule: not published419420    // Video, captions, transcript.421    await p.getByTestId("start-watching").click();422    const video = p.locator("video");423    await expect.poll(async () => video.evaluate((v: HTMLVideoElement) => v.readyState), { timeout: 20_000 }).toBeGreaterThanOrEqual(1);424    expect(await video.evaluate((v: HTMLVideoElement) => v.textTracks.length)).toBe(1);425    expect(Math.round(await video.evaluate((v: HTMLVideoElement) => v.duration))).toBe(8);426    await expect(p.locator("body")).toContainText(WORDS.caption); // the transcript panel427    for (const [url, type] of [[MEDIA(hls), "mpegurl"], [MEDIA(hls.replace("master.m3u8", "fallback.mp4")), "video/mp4"], [MEDIA(captionPath), "text/vtt"]] as const) {428      const r = await p.request.get(url);429      expect(r.status(), url).toBe(200);430      expect(r.headers()["content-type"]).toContain(type);431    }432    expect((await p.request.get(MEDIA(hls.replace(/[^/]+\/master\.m3u8$/, "captions.fr-CA.0000000000.vtt")))).status()).toBe(404); // a file that no publication names433434    // Transcript search hit, with its timestamp.435    await p.goto(`/recherche?q=${WORDS.caption}`);436    const hit = p.locator(`a[href*="/seances/${SLUG}/regarder"]`).first();437    await expect(hit).toBeVisible();438    expect(await hit.getAttribute("href")).toMatch(/t=2/);439440    // Structured data on the home page: the course and its video exist for search engines only now.441    await p.goto("/");442    expect((await p.locator('script[type="application/ld+json"]').allTextContents()).map((x) => (JSON.parse(x) as { "@type": string })["@type"])).toEqual(["WebSite", "Course", "VideoObject"]);443    await expect(p.getByTestId("count-published")).toHaveText("1 sur 24");444    await expect(p.getByTestId("cta-start")).toBeVisible(); // « Commencer gratuitement » now has somewhere to go445446    // Sitemap, health, and the resource: public but not downloadable while no licence is recorded.447    const sitemap = await (await p.request.get(`${BASE}/sitemap.xml`)).text();448    expect(sitemap).toContain(`${BASE}/seances/${SLUG}/regarder`);449    expect(await (await p.request.get(`${BASE}/api/health`)).json()).toMatchObject({ status: "ok", published: 1 });450    expect((await p.request.get(`${BASE}/telecharger/S01/diapositives-de-la-seance`)).status()).toBe(404);451    // Answer keys of sessions that are not published stay out of reach.452    for (const url of [`${BASE}/contenu/S02/quiz.json`, `${BASE}/admin/api/sessions/S02/sections/quiz`, `${BASE}/seances/s25`, `${BASE}/seances/25-seance-du-depot`]) expect((await p.request.get(url, { maxRedirects: 0 })).status(), url).toBeGreaterThanOrEqual(401);453    const index = await (await p.request.get(`${BASE}/recherche/index.json`)).text();454    expect(index).toContain(WORDS.lab1);455    expect(index).not.toContain("Deux plus deux font quatre"); // quiz explanations are never indexed456  });457});458459test("licence consignée et plan publié : le téléchargement s’ouvre, la nouvelle séance entre au plan", async ({ browser }) => {460  await page.goto("/admin/cours");461  await expect(page.getByTestId("plan-dirty")).toContainText("S25 — nouvelle séance");462  await page.getByTestId("course-license").fill("CC BY-NC-SA 4.0");463  await page.getByTestId("save-course").click();464  await expect(page.locator("main")).toContainText("Réglages enregistrés");465  await anonymous(browser, async (p) => { expect((await p.request.get(`${BASE}/telecharger/S01/diapositives-de-la-seance`)).status()).toBe(404); }); // saved, not published466  await page.getByTestId("publish-plan").click();467  await expect(page.getByTestId("confirm-plan")).toContainText("Identité du cours ou licence");468  await page.getByTestId("confirm-plan-ok").click();469  await expect(page.getByTestId("plan-panel")).toContainText("Le plan en ligne est à jour");470  await anonymous(browser, async (p) => {471    const r = await p.request.get(`${BASE}/telecharger/S01/diapositives-de-la-seance`);472    expect(r.status()).toBe(200);473    expect(r.headers()["content-disposition"]).toContain("attachment");474    expect((await r.body()).toString()).toContain("deuxième version"); // the replacement, at the unchanged address475    await p.goto("/programme");476    await expect(p.locator("li[data-session]")).toHaveCount(25);477    await expect(p.locator('li[data-session="S25"] [data-state="upcoming"]')).toBeVisible();478  });479});480481test("modifier, publier de nouveau, revenir en arrière, puis retirer : le public suit exactement", async ({ browser }) => {482  // An edit stays private until it is published.483  await editor(S01, /Contenus/);484  await page.getByTestId("edit-lab").click();485  await page.getByTestId("markdown-source").fill(`# Laboratoire d’essai\n\nDeuxième version : observer un ${WORDS.lab2}.`.replace(/\\n/g, "\n"));486  await page.getByTestId("save-markdown").click();487  await expect(page.getByTestId("editor-lab")).toContainText("Section enregistrée");488  await anonymous(browser, async (p) => { await p.goto(`/seances/${SLUG}`); await expect(await labPublic(p)).toContainText(WORDS.lab1); await expect(p.locator("body")).not.toContainText(WORDS.lab2); });489490  // The address changes too: the old one must redirect once published.491  await openTab(/Fiche/);492  await page.getByTestId("field-slug").fill("01-adresse-renommee");493  await page.getByTestId("save-meta").click();494  await expect(page.locator("main")).toContainText("Fiche enregistrée");495  await openTab(/Publication/);496  await expect(page.getByTestId("publish-panel")).toContainText("La copie de travail diffère");497  await page.getByTestId("publish-now").click();498  await page.getByTestId("confirm-publish-ok").click();499  await expect(page.getByTestId("history-panel").locator('tr[data-version="2"]')).toContainText("En vigueur");500  await anonymous(browser, async (p) => {501    const r = await p.request.get(`${BASE}/seances/${SLUG}`, { maxRedirects: 0 });502    expect(r.status()).toBe(308);503    expect(r.headers().location).toBe("/seances/01-adresse-renommee");504    expect((await p.request.get(`${BASE}/seances/${SLUG}/regarder`, { maxRedirects: 0 })).headers().location).toBe("/seances/01-adresse-renommee/regarder");505    await p.goto("/seances/01-adresse-renommee");506    await expect(await labPublic(p)).toContainText(WORDS.lab2);507    await expect(p.locator("body")).not.toContainText(WORDS.lab1);508  });509510  // Roll back to version 1: the first text and the first address are public again; the second text is gone everywhere.511  await page.getByTestId("rollback-1").click();512  await expect(page.getByTestId("confirm-rollback")).toContainText("version 1");513  await page.getByTestId("confirm-rollback-ok").click();514  await expect(page.getByTestId("history-panel").locator('tr[data-version="3"]')).toContainText("Retour à une version");515  await anonymous(browser, async (p) => {516    await p.goto(`/seances/${SLUG}`);517    await expect(await labPublic(p)).toContainText(WORDS.lab1);518    await expect(p.locator("body")).not.toContainText(WORDS.lab2);519    expect((await p.request.get(`${BASE}/seances/01-adresse-renommee`, { maxRedirects: 0 })).status()).toBe(404);520    const index = await (await p.request.get(`${BASE}/recherche/index.json`)).text();521    expect(index).toContain(WORDS.lab1); expect(index).not.toContain(WORDS.lab2);522  });523524  // Withdraw: the session disappears from the public site — page content, video, captions, search, sitemap.525  await page.getByTestId("withdraw").click();526  await page.getByTestId("confirm-withdraw-ok").click();527  await expect(page.getByTestId("session-editor")).toHaveAttribute("data-public", "none");528  await anonymous(browser, async (p) => {529    await p.goto(`/seances/${SLUG}`);530    await expect(p.locator("article")).toHaveAttribute("data-access", "upcoming");531    await expect(p.locator("body")).not.toContainText(WORDS.lab1);532    await expect(p.locator("[data-question], [data-capsule], video")).toHaveCount(0);533    for (const url of [MEDIA(hls), MEDIA(hls.replace("master.m3u8", "fallback.mp4")), MEDIA(hls.replace("master.m3u8", "v360/seg_00000.ts")), MEDIA(captionPath), `${BASE}/telecharger/S01/diapositives-de-la-seance`]) expect((await p.request.get(url)).status(), url).toBe(404);534    const index = await (await p.request.get(`${BASE}/recherche/index.json`)).text();535    for (const gone of [WORDS.lab1, WORDS.lab2, WORDS.caption, "terme d’essai"]) expect(index, gone).not.toContain(gone);536    expect(await (await p.request.get(`${BASE}/sitemap.xml`)).text()).not.toContain("regarder");537    expect(await (await p.request.get(`${BASE}/api/health`)).json()).toMatchObject({ published: 0 });538    await p.goto("/");539    expect((await p.locator('script[type="application/ld+json"]').allTextContents()).map((x) => (JSON.parse(x) as { "@type": string })["@type"])).toEqual(["WebSite"]);540  });541});542543test("programmer une publication : invisible avant l’échéance, annulable", async ({ browser }) => {544  await editor(S01, /Publication/);545  await page.getByTestId("schedule").click();546  await page.getByTestId("confirm-schedule-ok").click(); // tomorrow, by default547  await expect(page.getByTestId("scheduled-entry")).toContainText("mise en ligne le");548  await anonymous(browser, async (p) => { await p.goto(`/seances/${SLUG}`); await expect(p.locator("article")).toHaveAttribute("data-access", "upcoming"); expect(await (await p.request.get(`${BASE}/recherche/index.json`)).text()).not.toContain(WORDS.lab2); });549  await page.goto("/admin");550  await expect(page.getByTestId("schedule-panel")).toContainText("S01"); // the dashboard's publication calendar551  await editor(S01, /Publication/);552  await page.getByRole("button", { name: "Annuler la programmation" }).click();553  await expect(page.getByTestId("scheduled-entry")).toHaveCount(0);554});555556/* ------------------------------------------------------------------ tools, journal, access */557558test("outils : index, liens, sous-titres, exportation ; journal : qui, quand, quoi, avant et après", async () => {559  await page.goto("/admin/outils");560  await page.getByTestId("rebuild-index").click();561  await expect(page.getByTestId("index-report")).toContainText("documents indexés");562  await page.getByTestId("check-links").click();563  await expect(page.getByTestId("links-report")).toContainText("séances", { timeout: 30_000 });564  await expect(page.getByTestId("links-report").locator('tr[data-level="error"]')).toHaveCount(0);565  await page.getByTestId("check-captions").click();566  await expect(page.getByTestId("captions-report")).toContainText("Valide · 4 répliques");567  const [download] = await Promise.all([page.waitForEvent("download"), page.getByTestId("export-link").click()]);568  expect(download.suggestedFilename()).toMatch(/^atlas-ia-export-.*\.tar\.gz$/);569570  await page.goto("/admin/journal");571  const log = page.getByTestId("audit-log");572  for (const action of ["publication.published", "publication.rolled_back", "publication.withdrawn", "import.applied", "capsule.transcoded", "auth.login.ok", "auth.passkey.enrolled.setup"]) await expect(log.locator(`tr[data-action="${action}"]`).first(), action).toBeVisible();573  await expect(log.locator('tr[data-action="publication.published"]').first()).toContainText("Enseignant d’essai");574  await expect(log.locator('tr[data-action="capsule.transcoded"]').first()).toContainText("Processus de traitement");575  await log.locator('tr[data-action="section.updated"]').first().getByRole("button", { name: "Détail" }).click();576  await expect(page.getByTestId("audit-detail")).toContainText("Avant");577  await expect(page.getByTestId("audit-detail")).toContainText("Après");578  // Nothing secret is ever written to the journal.579  const all = await (await call(page, "GET", "audit")).text(), cookie = (await ctx.cookies()).find((c) => c.name === "atlas_studio")!.value;580  expect(all).not.toContain(cookie);581  expect(all).not.toContain((await csrf(page))!);582  expect(all).not.toContain(state().enrol.split("jeton=")[1]!);583});584585let authorCtx: BrowserContext, author: Page;586587test("accès : un auteur autorisé par le propriétaire rédige, mais ne publie pas et ne gère pas les accès", async ({ browser }) => {588  await page.goto("/admin/acces");589  await page.getByTestId("new-editor-name").fill("Autrice invitée");590  await page.getByTestId("new-editor-role").selectOption("author");591  await page.getByTestId("add-editor").click();592  const link = await page.getByTestId("enrol-link-value").inputValue();593  expect(link).toContain("/admin/enrolement?jeton=");594  await expect(page.getByTestId("editors-table")).toContainText("Autrice invitée");595596  authorCtx = await browser.newContext({ baseURL: BASE, locale: "fr-CA" }); author = await authorCtx.newPage();597  await withAuthenticator(authorCtx, author);598  await author.goto(link);599  await author.getByTestId("passkey-enrol").click();600  await expect(author.getByTestId("studio-dashboard")).toBeVisible();601  await expect(author.getByRole("link", { name: "Accès" })).toHaveCount(0);602  expect((await author.goto("/admin/acces"))!.status()).toBe(404); // not a hidden link: the page does not exist for this role603  await author.goto("/admin");604  // Server-side authorisation, whatever the browser sends:605  expect((await call(author, "GET", "access")).status()).toBe(403);606  expect((await call(author, "GET", "tools/export")).status()).toBe(403);607  expect((await call(author, "POST", "access/editors", { name: "Complice", role: "owner" })).status()).toBe(403);608  expect((await call(author, "POST", `sessions/${S01}/publish`, { confirm: S01 })).status()).toBe(403);609  expect((await call(author, "POST", "course/publish", { confirm: "course" })).status()).toBe(403);610  expect((await call(author, "POST", `sessions/${S01}/withdraw`, { confirm: S01 })).status()).toBe(403);611  // …but editing is allowed, and the publication tab says why publishing is not.612  const detail = await (await call(author, "GET", "sessions/S06")).json() as { session: { rev: number } };613  expect((await call(author, "PATCH", "sessions/S06", { patch: { tags: ["essai"] }, rev: detail.session.rev })).status()).toBe(200);614  await author.goto(`/admin/seances/${S01}#publication`);615  await expect(author.getByTestId("cannot-publish")).toBeVisible();616  await expect(author.getByTestId("publish-now")).toBeDisabled();617});618619test("accès : désactiver un éditeur ferme ses sessions sur-le-champ ; la dernière clé du propriétaire ne se révoque pas", async () => {620  await page.goto("/admin/acces");621  const row = page.getByTestId("editors-table").locator("tr", { hasText: "Autrice invitée" });622  await row.getByRole("button", { name: "Désactiver" }).click();623  await page.getByTestId("confirm-access-ok").click();624  await expect(row).toContainText("désactivé");625  expect((await call(author, "GET", "dashboard")).status()).toBe(401); // her open session died with the decision626  await author.goto("/admin"); await expect(author).toHaveURL(/\/admin\/connexion$/);627  await author.getByTestId("passkey-login").click();628  await expect(author.getByTestId("passkey-error")).toBeVisible({ timeout: 20_000 }); // and her passkey no longer opens anything629  await authorCtx.close();630631  const keys = await (await call(page, "GET", "access")).json() as { passkeys: { id: string; editor_id: string }[]; me: string };632  const mine = keys.passkeys.find((k) => k.editor_id === keys.me)!;633  const r = await call(page, "DELETE", `access/passkeys/${mine.id}`);634  expect(r.status()).toBe(409);635  expect((await r.json() as { error: { code: string } }).error.code).toBe("last_owner");636});637638/* ------------------------------------------------------------------ negative security tests */639640const READS = ["dashboard", "health", "sessions", "sessions/S01", "sessions/S01/sections/quiz", "sessions/S01/capsules/introduction-d-essai/sidecars", "course", "uploads/config", "imports", "jobs", "audit", "audit/1", "access", "tools/export", "tools/backups"];641const WRITES: [string, string, unknown][] = [642  ["POST", "sessions", { title: "x", short: "x", part: "I", level: "débutant" }], ["PATCH", "sessions/S01", { patch: { title: "Piraté" }, rev: 1 }], ["POST", "sessions/S01/state", { state: "preview" }],643  ["PUT", "sessions/S01/sections/lab", { body: "Piraté" }], ["DELETE", "sessions/S01/sections/lab", undefined], ["POST", "sessions/S01/capsules", { title: "x" }], ["DELETE", "sessions/S01/capsules/introduction-d-essai", undefined],644  ["POST", "sessions/S01/publish", { confirm: "S01" }], ["POST", "sessions/S01/rollback", { confirm: "S01", toVersion: 1 }], ["POST", "sessions/S01/withdraw", { confirm: "S01" }], ["POST", "sessions/S01/archive", { confirm: "S01" }],645  ["PATCH", "course", { patch: { license: "x" }, rev: 1 }], ["POST", "course/publish", { confirm: "course" }], ["POST", "uploads", { purpose: "master", filename: "a.mp4", size: 10, fingerprint: "0".repeat(64), context: {} }],646  ["PUT", "uploads/up_0123456789abcdef/chunks/0", "x"], ["POST", "uploads/up_0123456789abcdef/complete", {}], ["POST", "imports", {}], ["POST", "imports/imp_0123456789ab/apply", { confirm: "imp_0123456789ab" }],647  ["POST", "jobs/1/cancel", {}], ["POST", "jobs/1/retry", {}], ["POST", "tools/search-index", {}], ["POST", "tools/links", {}], ["POST", "access/editors", { name: "Intrus", role: "owner" }], ["DELETE", "access/passkeys/abcdefgh1234", undefined],648];649650test("sécurité : toute l’API privée refuse l’anonyme, l’origine étrangère, le jeton CSRF faux ou absent", async ({ request }) => {651  const send = (ctxReq: APIRequestContext, method: string, path: string, data: unknown, headers: Record<string, string>) => ctxReq.fetch(`${BASE}/admin/api/${path}`, { method, data: data === undefined ? undefined : typeof data === "string" ? data : JSON.stringify(data), headers: { "content-type": "application/json", ...headers } });652  // 1. No session at all: 401 everywhere, reads and writes, and nothing about which routes exist.653  for (const path of [...READS, "route/qui/n-existe/pas"]) expect((await request.get(`${BASE}/admin/api/${path}`)).status(), `GET ${path}`).toBe(401);654  for (const [method, path, data] of WRITES) expect((await send(request, method, path, data, { origin: BASE })).status(), `${method} ${path}`).toBe(401);655  // 2. A real session, but the request comes from another origin, or without / with a wrong CSRF token: 403, and nothing changes.656  const token = (await csrf(page))!, before = await (await call(page, "GET", `sessions/${S01}`)).text();657  for (const [method, path, data] of WRITES) {658    expect((await send(page.request, method, path, data, { origin: "https://evil.example", "x-csrf-token": token })).status(), `origine étrangère : ${method} ${path}`).toBe(403);659    expect((await send(page.request, method, path, data, { origin: BASE, "sec-fetch-site": "cross-site", "x-csrf-token": token })).status(), `intersites : ${method} ${path}`).toBe(403);660    expect((await send(page.request, method, path, data, { origin: BASE })).status(), `sans jeton : ${method} ${path}`).toBe(403);661    expect((await send(page.request, method, path, data, { origin: BASE, "x-csrf-token": `${token.slice(0, -2)}xx` })).status(), `jeton faux : ${method} ${path}`).toBe(403);662  }663  expect(await (await call(page, "GET", `sessions/${S01}`)).text()).toBe(before);664  // 3. Responses of the private API are never cacheable nor indexable.665  const ok = await call(page, "GET", "dashboard");666  expect(ok.status()).toBe(200);667  expect(ok.headers()["cache-control"]).toContain("no-store");668  expect(ok.headers()["x-robots-tag"]).toContain("noindex");669});670671test("sécurité : rejeu d’une cérémonie, traversée de chemin, morceau altéré, limite de débit", async ({ browser, request }) => {672  // A WebAuthn answer is good for one challenge, once: capture a real sign-in and replay it.673  const c = await browser.newContext({ baseURL: BASE }), p = await c.newPage();674  await p.goto("/admin/connexion");675  const options = await (await p.request.post(`${BASE}/admin/api/auth/login/options`, { data: {}, headers: { origin: BASE } })).json() as { challengeId: string };676  const bogus = { challengeId: options.challengeId, response: { id: "AAAA", rawId: "AAAA", type: "public-key", response: { clientDataJSON: "e30", authenticatorData: "AAAA", signature: "AAAA" }, clientExtensionResults: {} } };677  expect((await p.request.post(`${BASE}/admin/api/auth/login/verify`, { data: bogus, headers: { origin: BASE } })).status()).toBe(401);             // unknown credential678  expect((await p.request.post(`${BASE}/admin/api/auth/login/verify`, { data: bogus, headers: { origin: BASE } })).status()).toBe(400);             // the challenge was consumed by the first try679  expect((await request.post(`${BASE}/admin/api/auth/login/verify`, { data: bogus, headers: { origin: BASE } })).status()).toBe(400);               // and it never belonged to another browser680  expect((await p.request.post(`${BASE}/admin/api/auth/login/options`, { data: {}, headers: { origin: "https://evil.example" } })).status()).toBe(403);681  await c.close();682683  // Path traversal, by every door that takes a path.684  for (const path of ["/admin/apercu/media/..%2f..%2fatlas.db", "/admin/apercu/media/%2e%2e/%2e%2e/atlas.db", "/admin/apercu/media/S01/..%2f..%2f..%2fmasters", "/admin/apercu/contenu/S01/..%2f..%2fatlas.db", "/admin/apercu/telecharger/S01/..%2f..%2fatlas.db", "/admin/api/uploads/..%2f..%2fatlas.db", "/admin/api/sessions/..%2fS01", "/admin/api/figures/S01/..%2f..%2fatlas.db"]) {685    const r = await page.request.get(BASE + path);686    expect(r.status(), path).toBeGreaterThanOrEqual(400);687    expect((await r.body()).toString().startsWith("SQLite format"), path).toBe(false);688  }689  for (const path of ["/media/..%2f..%2fatlas.db", "/media/%2e%2e%2f%2e%2e%2fmasters", "/contenu/S01/..%2f..%2fatlas.db", "/telecharger/S01/..%2f..%2fatlas.db", "/telecharger/..%2f..%2f/atlas.db"]) expect((await request.get(BASE + path)).status(), path).toBe(404);690  // An upload cannot name its own destination: file names are reduced to a harmless base name.691  const up = await (await call(page, "POST", "uploads", { purpose: "resource", filename: "../../../../etc/passwd.pdf", size: 9, fingerprint: "a".repeat(64), context: { sessionId: S01, meta: { kind: "slides", title: "x", visibility: "private", download: false, license: null } } })).json() as { upload: { id: string; filename: string } };692  expect(up.upload.filename).toBe("passwd.pdf");693  // A piece that does not hash to what was announced is refused.694  const bad = await page.request.fetch(`${BASE}/admin/api/uploads/${up.upload.id}/chunks/0`, { method: "PUT", data: Buffer.from("%PDF-1.4\n"), headers: { origin: BASE, "x-csrf-token": (await csrf(page))!, "content-type": "application/octet-stream", "x-chunk-sha256": "b".repeat(64) } });695  expect(bad.status()).toBe(422);696  expect((await call(page, "POST", `uploads/${up.upload.id}/complete`, {})).status()).toBe(409); // incomplete: nothing to assemble697  expect((await call(page, "DELETE", `uploads/${up.upload.id}`)).status()).toBe(200);698  // Size and type limits are checked before any byte travels.699  expect((await call(page, "POST", "uploads", { purpose: "master", filename: "film.exe", size: 10, fingerprint: "a".repeat(64), context: { sessionId: S01, capsuleId: "introduction-d-essai" } })).status()).toBe(415);700  expect((await call(page, "POST", "uploads", { purpose: "captions", filename: "a.vtt", size: 50_000_000, fingerprint: "a".repeat(64), context: { sessionId: S01, capsuleId: "introduction-d-essai" } })).status()).toBe(413);701702  // Authentication endpoints are rate limited per address (30 per minute): the flood is cut off.703  const statuses: number[] = [];704  for (let i = 0; i < 40; i++) statuses.push((await request.post(`${BASE}/admin/api/auth/login/options`, { data: {}, headers: { origin: BASE, "x-forwarded-for": "203.0.113.77" } })).status());705  expect(statuses.filter((s) => s === 429).length).toBeGreaterThanOrEqual(10);706  expect(statuses.slice(0, 20).every((s) => s === 200)).toBe(true);707});708709test("santé détaillée : réservée au jeton, complète", async ({ request }) => {710  expect((await request.get(`${BASE}/api/health/details`)).status()).toBe(404);711  expect((await request.get(`${BASE}/api/health/details`, { headers: { authorization: "Bearer mauvais-jeton-0123456789" } })).status()).toBe(404);712  const r = await request.get(`${BASE}/api/health/details`, { headers: { authorization: `Bearer ${STUDIO.healthToken}` } });713  const body = await r.json() as { status: string; checks: Record<string, { ok: boolean }> & { content: { source: string; sessions: number }; worker: { state: string }; ffmpeg: { ffmpeg: string | null } } };714  expect(Object.keys(body.checks).sort()).toEqual(["content", "database", "ffmpeg", "storage", "worker"]);715  expect(body.checks.database!.ok).toBe(true);716  expect(body.checks.content).toMatchObject({ source: "studio", sessions: 25 });717  expect(body.checks.worker.state).toBe("ok");718  expect(body.checks.ffmpeg.ffmpeg).toBeTruthy();719  expect(r.status()).toBe(body.status === "ok" ? 200 : 503);720});721722/* ------------------------------------------------------------------ accessibility and screenshots */723724const SCREENS: [string, string][] = [["tableau-de-bord", "/admin"], ["seances", "/admin/seances"], ["seance-fiche", "/admin/seances/S01"], ["seance-contenus", "/admin/seances/S01#contenus"], ["seance-capsules", "/admin/seances/S01#capsules"], ["seance-ressources", "/admin/seances/S01#ressources"], ["seance-publication", "/admin/seances/S01#publication"], ["cours", "/admin/cours"], ["importation", "/admin/importation"], ["traitements", "/admin/traitements"], ["outils", "/admin/outils"], ["journal", "/admin/journal"], ["acces", "/admin/acces"], ["apercu-prive", "/admin/apercu/seances/01-adresse-renommee"]];725726/** Audits the page and returns its violations; the caller asserts once, so one run lists every problem of every screen. */727async function audit(p: Page, label: string): Promise<string[]> {728  const results = await new AxeBuilder({ page: p }).withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa", "best-practice"]).analyze();729  return results.violations.map((v) => `[${label}] ${v.id} (${v.impact}) — ${v.help}\n    ${v.nodes.slice(0, 3).map((n) => `${n.target.join(" ")} :: ${n.failureSummary?.split("\n")[1]?.trim() ?? ""}`).join("\n    ")}`);730}731732for (const theme of ["light", "dark"] as const) {733  test(`axe · studio · ${theme}`, async () => {734    test.setTimeout(180_000);735    const p = await ctx.newPage(), found: string[] = [];736    await setTheme(p, theme);737    for (const [name, path] of SCREENS) {738      await p.goto(path, { waitUntil: "networkidle" });739      await expect(p.locator("html"), `thème appliqué sur ${name}`).toHaveAttribute("data-theme", theme);740      found.push(...await audit(p, `${name} (${theme})`));741    }742    // Editors open, dialogs open.743    await p.goto(`/admin/seances/${S01}#contenus`, { waitUntil: "networkidle" });744    await p.getByTestId("edit-lab").click(); await expect(p.getByTestId("markdown-preview")).toBeVisible(); found.push(...await audit(p, `éditeur Markdown (${theme})`));745    await p.getByTestId("edit-quiz").click(); await expect(p.getByTestId("quiz-editor")).toBeVisible(); found.push(...await audit(p, `éditeur de quiz (${theme})`));746    await p.goto(`/admin/seances/${S01}#publication`, { waitUntil: "networkidle" });747    await p.getByTestId("schedule").click(); await expect(p.getByTestId("confirm-schedule")).toBeVisible(); found.push(...await audit(p, `dialogue de programmation (${theme})`));748    await p.close();749    expect(found, found.join("\n")).toEqual([]);750  });751}752753test("axe · connexion et enrôlement (sans session)", async ({ browser }) => {754  const found: string[] = [];755  for (const theme of ["light", "dark"] as const) {756    const c = await browser.newContext({ baseURL: BASE, locale: "fr-CA" }), p = await c.newPage();757    await setTheme(p, theme);758    for (const path of ["/admin/connexion", "/admin/enrolement?jeton=jeton-invalide-0123456789abcdef"]) { await p.goto(path, { waitUntil: "networkidle" }); found.push(...await audit(p, `${path} (${theme})`)); }759    await c.close();760  }761  expect(found, found.join("\n")).toEqual([]);762});763764test("captures du studio à 1440 px et en largeur tablette, sans débordement horizontal", async () => {765  test.setTimeout(240_000);766  const out = resolve(process.env.ATLAS_STUDIO_SHOTS ?? "e2e/.tmp/studio/shots");767  for (const [width, height, label] of [[1440, 900, "1440"], [834, 1112, "tablette"]] as const) {768    for (const theme of ["light", "dark"] as const) {769      const p = await ctx.newPage();770      await p.setViewportSize({ width, height });771      await setTheme(p, theme);772      for (const [name, path] of SCREENS) {773        if (theme === "dark" && !["tableau-de-bord", "seance-capsules", "seance-publication"].includes(name)) continue;774        await p.goto(path, { waitUntil: "networkidle" });775        const overflow = await p.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);776        expect(overflow, `débordement horizontal : ${name} à ${label} px`).toBeLessThanOrEqual(0);777        await p.screenshot({ path: resolve(out, `${label}-${theme}-${name}.png`), fullPage: true });778      }779      await p.close();780    }781  }782});783
Files main
Menu

Theme