Repository Public
1// Montage commun aux essais de la console : session de l'administrateur d'essai, authentificateur virtuel réimporté2// (réauthentification), erreurs de console, axe (clair + sombre), accès direct à l'API pour préparer et vérifier.3import AxeBuilder from "@axe-core/playwright"4import { expect, test as base, type Page } from "@playwright/test"5import { execFileSync } from "node:child_process"6import crypto from "node:crypto"7import fs from "node:fs"8import { addAuthenticator, type Authn } from "../helpers"9import { trackMailboxes } from "../mailboxes"10import { API_HEADERS, DB_NAME, ORIGIN, OUT, STG, STORAGE, readState } from "./env"1112export const st = readState()1314export interface Watch {15 /** erreurs de console et exceptions (dont les violations de CSP) */16 errors: string[]17 /** motifs d'erreurs attendues dans cet essai (réponse 403 voulue, par exemple) */18 allow: RegExp[]19 requests: string[]20}2122/** Bruit que le navigateur émet quand axe tente (en vain, c'est voulu) de s'injecter dans un cadre isolé sans scripts. */23const AXE_SANDBOX_NOISE = /Blocked script execution in 'about:srcdoc' because the document's frame is sandboxed/24const axeRunning = new WeakSet<Page>()2526export const test = base.extend<{ watch: Watch; authn: Authn }>({27 watch: [28 async ({ page }, use) => {29 const watch: Watch = { errors: [], allow: [], requests: [] }30 page.on("request", (r) => watch.requests.push(r.url()))31 page.on("console", (m) => {32 if (m.type() === "error" && !(axeRunning.has(page) && AXE_SANDBOX_NOISE.test(m.text()))) watch.errors.push(m.text())33 })34 page.on("pageerror", (e) => watch.errors.push(`pageerror: ${e.message}`))35 await use(watch)36 const unexpected = watch.errors.filter((e) => !watch.allow.some((re) => re.test(e)))37 expect(unexpected, "erreurs de console ou violations de CSP").toEqual([])38 // aucune ressource chargée hors de l'origine de l'application39 const foreign = watch.requests.filter((u) => /^https?:/.test(u) && !/^http:\/\/(localhost|127\.0\.0\.1):\d+\//.test(u))40 expect(foreign, "requêtes vers une autre origine").toEqual([])41 },42 { auto: true },43 ],44 // L'authentificateur virtuel vit dans le contexte de chaque essai : la clé du lanceur y est réimportée, avec un compteur de45 // signatures en avance sur tous les usages précédents (sinon le serveur y verrait un clone, à juste titre).46 authn: [47 async ({ context, page }, use) => {48 const a = await addAuthenticator(context, page)49 const signCount = 1000 + Math.floor((Date.now() - st.epoch) / 10)50 await a.cdp.send("WebAuthn.addCredential", { authenticatorId: a.id, credential: { ...st.credential, signCount } })51 await use(a)52 },53 { auto: true },54 ],55})56export { expect }5758// ---------------------------------------------------------------- accessibilité59/** Aucune violation sérieuse ou critique (WCAG 2.1 AA). Les cadres isolés sans scripts sont exclus : axe ne peut pas s'y injecter. */60export async function axe(page: Page, name: string) {61 axeRunning.add(page)62 try {63 const r = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]).exclude(".adm-frame").exclude(".html-frame iframe").exclude(".tpl-frame iframe").analyze()64 const bad = r.violations.filter((v) => v.impact === "serious" || v.impact === "critical")65 fs.appendFileSync(`${OUT}/axe.log`, `${name}: ${r.violations.length} violation(s), ${bad.length} serious/critical, ${r.passes.length} passes\n${bad.map((v) => ` ${v.id}: ${v.nodes.map((n) => n.target.join(" ")).join(" | ")}`).join("\n")}\n`)66 expect(bad.map((v) => `${v.id}: ${v.nodes.map((n) => n.target.join(" ")).slice(0, 3).join(" | ")}`), `axe ${name}`).toEqual([])67 } finally {68 await page.waitForTimeout(50)69 axeRunning.delete(page)70 }71}72/** Le même écran en clair puis en sombre (le thème « système » suit `prefers-color-scheme`). */73export async function axeBoth(page: Page, name: string) {74 await page.emulateMedia({ colorScheme: "light" })75 await axe(page, `${name} (clair)`)76 await page.emulateMedia({ colorScheme: "dark" })77 await page.waitForTimeout(300) // fin des transitions de couleur (sinon axe mesure un contraste intermédiaire)78 await axe(page, `${name} (sombre)`)79 await page.emulateMedia({ colorScheme: "light" })80 await page.waitForTimeout(300)81}82export const noOverflow = async (page: Page) => expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), "pas de défilement horizontal").toBe(true)83export const toastText = (page: Page, text: string | RegExp) => page.locator(".toast").filter({ hasText: text })8485// ---------------------------------------------------------------- réauthentification86/** Base jetable : marque la session du lanceur comme réauthentifiée à l'instant (préparation de données, pas l'essai de l'invite). */87export const grantReauth = () => execFileSync("psql", ["-q", "-d", DB_NAME, "-c", "update sessions set reauth_at = now()"], { stdio: "ignore" })88/** Efface la réauthentification : la prochaine opération sensible répondra `403 reauth_required` (essai de l'invite). */89export const clearReauth = () => execFileSync("psql", ["-q", "-d", DB_NAME, "-c", "update sessions set reauth_at = null"], { stdio: "ignore" })90/** L'invite « Confirmez avec votre clé d'accès » est affichée : on confirme (l'authentificateur virtuel répond), elle se ferme. */91export async function confirmReauth(page: Page) {92 const dlg = page.getByTestId("reauth-dialog")93 await expect(dlg).toBeVisible()94 await page.getByTestId("reauth-confirm").click()95 await expect(dlg).toBeHidden()96}9798// ---------------------------------------------------------------- API (session du lanceur, hors de la page)99const cookie = () => (JSON.parse(fs.readFileSync(STORAGE, "utf8")) as { cookies: { name: string; value: string }[] }).cookies.map((c) => `${c.name}=${c.value}`).join("; ")100export interface ApiResult<T = any> {101 status: number102 ok: boolean103 body: T104 headers: Headers105}106/** Appel de l'API avec la session de l'administrateur d'essai (en-têtes anti-CSRF compris). */107export async function api<T = any>(method: string, path: string, body?: unknown): Promise<ApiResult<T>> {108 const r = await fetch(`${ORIGIN}${path}`, { method, headers: { cookie: cookie(), ...API_HEADERS, ...(body === undefined ? {} : { "content-type": "application/json" }) }, body: body === undefined ? undefined : JSON.stringify(body) })109 const text = await r.text()110 let parsed: unknown = text111 try {112 parsed = JSON.parse(text)113 } catch {114 /* corps non JSON */115 }116 return { status: r.status, ok: r.ok, body: parsed as T, headers: r.headers }117}118/** Appel de /api/v1 avec un jeton de clé d'API (aucun cookie). */119export async function apiKey<T = any>(token: string, method: string, path: string, body?: unknown): Promise<ApiResult<T>> {120 const r = await fetch(`${ORIGIN}/api/v1${path}`, { method, headers: { authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "content-type": "application/json" }) }, body: body === undefined ? undefined : JSON.stringify(body) })121 const text = await r.text()122 let parsed: unknown = text123 try {124 parsed = JSON.parse(text)125 } catch {126 /* corps non JSON */127 }128 return { status: r.status, ok: r.ok, body: parsed as T, headers: r.headers }129}130131/** Adresse d'essai conforme à la règle : web-<nom>-<aléa>@stg.spboucher.ai. */132export const testAddress = (name: string) => {133 const address = `web-${name}-${st.run}${crypto.randomBytes(2).toString("hex")}@${STG}`134 // inscrite dès sa naissance : boîte, alias ou liste, le démontage (ou le lancement suivant) la retrouve — un alias y est sans effet135 trackMailboxes(OUT, address)136 return address137}138139/** Crée une boîte de recette (propriété de l'administrateur d'essai) ; le nettoyage final la supprime avec son courrier. */140export async function createMailbox(name: string, displayName = name): Promise<{ id: string; address: string }> {141 const address = testAddress(name)142 const r = await api("POST", "/api/admin/mailboxes", { address, display_name: displayName })143 if (!r.ok) throw new Error(`createMailbox ${address}: ${r.status} ${JSON.stringify(r.body)}`)144 const users = (await api<{ mailboxes: { id: string; address: string }[] }[]>("GET", "/api/admin/users")).body145 const mb = users.flatMap((u) => u.mailboxes).find((m) => m.address === address)146 if (!mb) throw new Error(`createMailbox ${address}: not listed`)147 return mb148}149/** Crée une adresse de type alias par /api/v1 (session administrateur). */150export async function createAlias(name: string, mailbox: string, extra: Record<string, unknown> = {}): Promise<{ id: string; address: string }> {151 const address = testAddress(name)152 const r = await api("POST", "/api/v1/aliases", { address, mailbox, ...extra })153 if (!r.ok) throw new Error(`createAlias ${address}: ${r.status} ${JSON.stringify(r.body)}`)154 return r.body155}156/** Envoie un message par /api/v1 avec la session (aucune politique de clé) ; rend l'envoi suivi. */157export async function sendMail(from: string, to: string | string[], subject: string, text = "Bonjour."): Promise<{ id: string; status: string }> {158 const r = await api("POST", "/api/v1/messages/send", { from, to: (Array.isArray(to) ? to : [to]).map((email) => ({ email })), subject, text })159 if (!r.ok) throw new Error(`sendMail ${from} → ${to}: ${r.status} ${JSON.stringify(r.body)}`)160 return r.body161}162/** Attend qu'un message portant cet objet soit visible dans la boîte (API de lecture) ; rend son résumé. */163export async function waitForMessage(address: string, subject: string, timeoutMs = 45_000): Promise<any> {164 const until = Date.now() + timeoutMs165 for (;;) {166 const r = await api("GET", `/api/v1/messages?address=${encodeURIComponent(address)}&subject=${encodeURIComponent(subject)}&limit=5`)167 const hit = r.ok ? (r.body.data as { subject: string }[]).find((m) => m.subject === subject) : undefined168 if (hit) return hit169 if (Date.now() > until) throw new Error(`message « ${subject} » not received in ${address} (${r.status})`)170 await new Promise((res) => setTimeout(res, 700))171 }172}173/** Ouvre une page de la console et attend son titre. */174export async function openAdmin(page: Page, tab: string) {175 await page.goto(`/admin/${tab}`)176 await expect(page.getByRole("heading", { name: "Administration", level: 1 })).toBeVisible()177 await expect(page.locator("main#main")).toBeVisible()178}179