Repository Public
1// Console d'administration — exploitation : tableau de bord de santé avec un contrôle en panne (sauvegarde vieillie par le fichier2// d'état que lit le backend) → alerte levée, pastille, acquittement, résolution ; appareils et révocation sous réauthentification3// (authentificateur virtuel, échec puis succès) ; événements de sécurité ; tendances avec données semées ; rôle membre : rien.4// Fichier nommé « z- » : il passe en dernier (ses alertes et ses sessions ne croisent pas les autres essais).5import { execFileSync } from "node:child_process"6import crypto from "node:crypto"7import path from "node:path"8import { addAuthenticator } from "../helpers"9import { DB, ORIGIN, PORT, writeBackupStatus } from "./env"10import { api, apiKey, clearReauth, expect, grantReauth, noOverflow, openAdmin, sendMail, st, test, toastText, waitForMessage } from "./fixtures"11import { axeThemes, nextSignCount, secondSession, shots, sql } from "./ops-helpers"1213const root = path.resolve(import.meta.dirname, "../../..")14const CHECKS = ["mail_server", "queue", "disk", "certificates", "backups", "dns", "push", "workers", "webhooks", "database"]15const backupAlert = async (state = "open") => ((await api("GET", `/api/admin/alerts?state=${state}`)).body.data as any[]).find((a) => a.key === "backup")1617test.afterAll(() => writeBackupStatus(1))1819test("santé : dix contrôles ; sauvegarde vieillie → panne, alerte levée, pastilles, acquittement, résolution", async ({ page }) => {20 test.setTimeout(240_000)21 writeBackupStatus(1)22 await expect.poll(async () => (await backupAlert()) ?? null, { timeout: 30_000 }).toBeNull()23 // serveur tout juste démarré (fichier lancé seul) : le premier tour du moniteur attend la sonde STARTTLS du certificat24 await expect.poll(async () => ((await api("GET", "/api/admin/health?fresh=1")).body.checks?.workers?.data?.workers ?? []).some((w: any) => w.name === "ops monitor"), { timeout: 60_000 }).toBe(true)25 await openAdmin(page, "overview")26 await expect(page.getByRole("heading", { level: 2, name: "Vue d'ensemble" })).toBeVisible()27 const dash = page.getByTestId("ops-dashboard")28 // le premier passage attend la sonde STARTTLS du certificat (5 s au plus)29 await expect(page.getByTestId("ops-checks")).toBeVisible({ timeout: 30_000 })30 for (const name of CHECKS) await expect(page.getByTestId(`check-${name}`)).toBeVisible()31 await expect(page.getByTestId("check-database")).toHaveAttribute("data-status", "ok")32 await expect(page.getByTestId("check-mail_server")).toHaveAttribute("data-status", "ok")33 await expect(page.getByTestId("check-mail_server-plain")).toContainText(/Le serveur de courrier répond en \d+ ms/)34 await expect(page.getByTestId("check-backups")).toHaveAttribute("data-status", "ok")35 await expect(page.getByTestId("check-backups-plain")).toContainText("Dernière sauvegarde réussie il y a")36 // l'état n'est jamais porté par la couleur seule : chaque carte a sa pastille en toutes lettres37 await expect(page.getByTestId("check-database").locator(".adm-ops-chip")).toHaveText("En ordre")38 await expect(page.getByTestId("ops-backups")).toContainText("Vérifiée")39 await expect(page.getByTestId("ops-workers").locator('tr[data-worker="ops monitor"]')).toBeVisible()40 await expect(page.getByTestId("ops-counts")).toContainText("Boîtes")41 // DNS : résumé ici, détail dans l'onglet existant (pas de doublon)42 await expect(page.getByTestId("check-dns").getByRole("link", { name: "DNS en direct" })).toHaveAttribute("href", "/admin/dns")43 await axeThemes(page, "ops-dashboard")44 await noOverflow(page)45 await shots(page, "dashboard-ok")4647 // actualisation automatique : en marche par défaut, suspendue quand l'onglet est caché48 await expect(page.getByTestId("ops-auto")).toHaveAttribute("aria-pressed", "true")4950 // ---- la sauvegarde date de 100 h : « Actualiser maintenant » (fresh=1) montre la panne en clair51 writeBackupStatus(100)52 const fresh = page.waitForRequest((r) => r.url().includes("/api/admin/health?fresh=1"))53 await page.getByTestId("ops-refresh").click()54 await fresh55 await expect(page.getByTestId("check-backups")).toHaveAttribute("data-status", "fail")56 await expect(page.getByTestId("check-backups").locator(".adm-ops-chip")).toHaveText("En panne")57 await expect(page.getByTestId("check-backups-plain")).toContainText(/La dernière sauvegarde réussie date de 4 j \(limite : 36 h\)/)58 await expect(page.getByTestId("ops-overall")).toHaveAttribute("data-status", "fail")59 await expect(page.getByTestId("ops-backups")).toContainText("au-delà de la limite de 36 h")6061 // ---- le moniteur lève UNE alerte ; pastille dans la console et sur l'entrée « Administration » du courrier62 await expect.poll(async () => (await backupAlert())?.state ?? null, { timeout: 45_000 }).toBe("open")63 await page.getByTestId("ops-refresh").click()64 await expect(page.getByTestId("ops-alerts-strip")).toContainText(/alertes? ouvertes?/)65 await expect(page.getByTestId("nav-badge-alerts")).toBeVisible()66 await shots(page, "dashboard-fail")67 await page.goto("/")68 const badge = page.getByTestId("sidebar-alerts")69 await expect(badge).toBeVisible()70 await expect(badge).toContainText(/alertes? d'exploitation ouvertes?/)71 await page.screenshot({ path: "/tmp/spmail-next-shots/web-ops/sidebar-alert-badge.png" })7273 // ---- alertes : gravité, première et dernière observation, nombre, explication du seuil ; acquittement74 await openAdmin(page, "alerts")75 const card = page.locator('[data-testid="alert-card"][data-alert-key="backup"]')76 await expect(card).toHaveAttribute("data-state", "open")77 await expect(card.getByTestId("alert-severity")).toHaveText("Panne")78 await expect(card.getByRole("heading", { name: "Sauvegarde échouée ou trop ancienne" })).toBeVisible()79 await expect(card.getByTestId("alert-explain")).toContainText("plus de 36 h")80 await expect(card).toContainText("Première observation")81 await expect(card).toContainText("Dernière observation")82 expect(Number(await card.getByTestId("alert-count").innerText())).toBeGreaterThanOrEqual(1)83 await expect(page.getByTestId("alert-types").locator('tr[data-kind="auth_anomaly"]')).toContainText("10 échecs")84 await axeThemes(page, "ops-alerts")85 await noOverflow(page)86 await shots(page, "alerts-open")87 const openBefore = ((await api("GET", "/api/admin/alerts?state=open")).body.data as any[]).filter((a) => a.state === "open").length88 await card.getByTestId("alert-ack").click()89 await expect(toastText(page, "Alerte acquittée")).toBeVisible()90 await expect(card).toHaveAttribute("data-state", "acked")91 await expect(card.getByTestId("alert-state")).toHaveText("Acquittée")92 await expect(card).toContainText("Acquittée par")93 await expect(card.getByTestId("alert-ack")).toHaveCount(0)94 expect((await backupAlert()).state).toBe("acked")95 // la pastille ne compte que les alertes encore ouvertes96 if (openBefore === 1) await expect(page.getByTestId("nav-badge-alerts")).toHaveCount(0)97 else await expect(page.getByTestId("nav-badge-alerts")).toHaveText(String(openBefore - 1))9899 // ---- le fichier d'état est réparé : l'alerte se résout d'elle-même, visible dans « Toutes »100 writeBackupStatus(1)101 await expect.poll(async () => (await backupAlert("open")) ?? null, { timeout: 45_000 }).toBeNull()102 expect((await backupAlert("all")).state).toBe("resolved")103 await page.getByRole("button", { name: "Actualiser", exact: true }).click()104 await expect(card).toHaveCount(0)105 await page.getByRole("group", { name: "Alertes affichées" }).getByRole("button", { name: "Toutes" }).click()106 await expect(card.first()).toHaveAttribute("data-state", "resolved")107 await expect(card.first().getByTestId("alert-state")).toHaveText("Résolue")108 await shots(page, "alerts-resolved")109 await openAdmin(page, "overview")110 await expect(page.getByTestId("check-backups")).toHaveAttribute("data-status", "ok", { timeout: 20_000 })111 void dash112})113114test("appareils : sessions de tous, filtres, révocation sous réauthentification (échec puis succès), retrait d'un appareil ; événements de sécurité", async ({ page, browser, authn, watch }) => {115 test.setTimeout(240_000)116 watch.allow.push(/status of 40[13]/)117 const other = await secondSession(browser)118 const mine = (await api("GET", "/api/admin/devices")).body.sessions as { id: string; current: boolean; user_id: string }[]119 const current = mine.find((s) => s.current)!120 const target = mine.filter((s) => !s.current)121 // la seconde session est la plus récente des autres122 const victim = sql(`select id from sessions where revoked_at is null and id <> '${current.id}' order by created_at desc limit 1`)123 expect(target.some((s) => s.id === victim)).toBe(true)124 sql(`insert into push_devices (session_id, user_id, apns_token, bundle_id, environment) values ('${current.id}', '${current.user_id}', '${"c0ffee".repeat(10)}abcdef', 'ai.spboucher.mail.essai', 'sandbox')`)125126 await openAdmin(page, "devices")127 await expect(page.getByRole("heading", { level: 2, name: "Appareils" })).toBeVisible()128 const sessions = page.getByTestId("devices-sessions")129 await expect(sessions.locator(`tr[data-session-id="${current.id}"]`)).toContainText("Cette session")130 const row = sessions.locator(`tr[data-session-id="${victim}"]`)131 await expect(row).toBeVisible()132 await expect(row).toContainText("Web")133 // jeton de notification : six derniers caractères seulement, jamais le jeton entier134 const push = page.getByTestId("devices-push")135 await expect(push).toContainText("…abcdef")136 expect(await page.content()).not.toContain("c0ffeec0ffee")137 // filtres138 await page.getByTestId("devices-platform").selectOption("ios")139 await expect(page.getByText("Aucune session ne correspond aux filtres.")).toBeVisible()140 await page.getByTestId("devices-platform").selectOption("web")141 await expect(row).toBeVisible()142 await page.getByTestId("devices-user").selectOption("admin")143 await expect(row).toBeVisible()144 await page.getByTestId("devices-platform").selectOption("")145 await axeThemes(page, "ops-devices")146 await noOverflow(page)147 await shots(page, "devices")148149 // ---- révocation : confirmation, puis la clé d'accès est exigée ; une clé qui ne vérifie pas est refusée et consignée150 clearReauth()151 await row.getByRole("button", { name: /Révoquer la session de admin/ }).click()152 await page.getByRole("alertdialog", { name: "Révoquer cette session ?" }).getByRole("button", { name: "Révoquer", exact: true }).click()153 const dlg = page.getByTestId("reauth-dialog")154 await expect(dlg).toBeVisible()155 const wrongKey = crypto.generateKeyPairSync("ec", { namedCurve: "P-256" }).privateKey.export({ type: "pkcs8", format: "der" }).toString("base64")156 await authn.cdp.send("WebAuthn.clearCredentials", { authenticatorId: authn.id })157 await authn.cdp.send("WebAuthn.addCredential", { authenticatorId: authn.id, credential: { ...st.credential, privateKey: wrongKey, signCount: nextSignCount() } })158 await page.getByTestId("reauth-confirm").click()159 await expect(dlg.getByRole("alert")).toBeVisible()160 expect(sql(`select count(*) from sessions where id = '${victim}' and revoked_at is null`)).toBe("1")161 // la bonne clé : l'opération est rejouée sans autre intervention162 await authn.cdp.send("WebAuthn.clearCredentials", { authenticatorId: authn.id })163 await authn.cdp.send("WebAuthn.addCredential", { authenticatorId: authn.id, credential: { ...st.credential, signCount: nextSignCount() } })164 await page.getByTestId("reauth-confirm").click()165 await expect(dlg).toBeHidden()166 await expect(toastText(page, "Session de admin révoquée.")).toBeVisible()167 await expect(row).toHaveCount(0)168 expect(sql(`select count(*) from sessions where id = '${victim}' and revoked_at is not null`)).toBe("1")169 // l'autre navigateur est renvoyé à la connexion170 await other.page.reload()171 await expect(other.page.getByRole("button", { name: "Se connecter avec une clé d'accès" })).toBeVisible()172 await other.context.close()173174 // ---- retrait de l'appareil de notification (réauthentification encore valide : pas de nouvelle invite)175 await push.getByRole("button", { name: /Retirer l'appareil de notification de admin/ }).click()176 await page.getByRole("alertdialog", { name: "Retirer cet appareil ?" }).getByRole("button", { name: "Retirer", exact: true }).click()177 await expect(toastText(page, "Appareil de admin retiré.")).toBeVisible()178 await expect(page.getByTestId("devices-push-empty")).toBeVisible()179 expect(sql("select count(*) from push_devices")).toBe("0")180 // fil d'audit181 const trail = page.getByTestId("devices-trail")182 await expect(trail.locator('li[data-action="admin.session.revoke"]').first()).toContainText("par admin")183 await expect(trail.locator('li[data-action="admin.push.remove"]').first()).toContainText("Appareil retiré")184 await shots(page, "devices-trail")185186 // ---- événements de sécurité : l'échec de réauthentification y est, compté sur 24 h ; filtres et pagination187 await openAdmin(page, "security")188 await expect(page.getByRole("heading", { level: 2, name: "Sécurité" })).toBeVisible()189 expect(Number(await page.getByTestId("security-reauth-failed").innerText())).toBeGreaterThanOrEqual(1)190 const table = page.getByTestId("security-table")191 await expect(table.locator('tr[data-action="admin.session.revoke"]').first()).toBeVisible()192 await page.getByTestId("security-filter").selectOption("reauthFailed")193 await expect(table.locator("tbody tr").first()).toHaveAttribute("data-action", "reauth.failed")194 expect(await table.locator('tbody tr:not([data-action="reauth.failed"])').count()).toBe(0)195 await expect(table.locator("tbody tr").first()).toHaveAttribute("data-failure", "true")196 await page.getByTestId("security-period").selectOption("24")197 await expect(table.locator('tbody tr[data-action="reauth.failed"]').first()).toBeVisible()198 await page.getByTestId("security-filter").selectOption("all")199 await page.getByTestId("security-period").selectOption("0")200 await expect(table.locator("tbody tr").first()).toBeVisible()201 const shown = await table.locator("tbody tr").count()202 if (shown === 50) {203 await page.getByTestId("security-more").click()204 await expect.poll(() => table.locator("tbody tr").count()).toBeGreaterThan(50)205 } else await expect(page.getByText("Fin du journal")).toBeVisible()206 // la pagination de l'API elle-même207 const p1 = (await api("GET", "/api/admin/security-events?limit=2")).body208 expect(p1.data.length).toBe(2)209 const p2 = (await api("GET", `/api/admin/security-events?limit=2&before=${p1.next_before}`)).body210 expect(Math.max(...p2.data.map((e: any) => Number(e.id)))).toBeLessThan(Number(p1.next_before))211 // aucun secret : ni jeton de clé d'API ni empreinte dans la page212 expect(await page.content()).not.toMatch(/spm_[A-Za-z0-9_-]{20,}/)213 await axeThemes(page, "ops-security")214 await noOverflow(page)215 await shots(page, "security")216})217218test("tendances : espace avec projection, issue des remises, API ; remises à problème et diagnostic ; boîtes ; file", async ({ page, watch }) => {219 watch.allow.push(/status of 40[034]/)220 test.setTimeout(180_000)221 const users = (await api("GET", "/api/admin/users")).body as { mailboxes: { id: string; address: string }[] }[]222 const boxA = users.flatMap((u) => u.mailboxes).find((m) => m.address === st.addrA)!223 const boxB = users.flatMap((u) => u.mailboxes).find((m) => m.address === st.addrB)!224 // six jours de relevés passés (le relevé du jour est écrit par le serveur) : +1 Mo par jour pour A, stable pour B225 for (let d = 6; d >= 1; d--) {226 sql(`insert into usage_snapshots (day, mailbox_id, used_bytes, received, sent, delivered, bounced, failed) values227 ((now() at time zone 'utc')::date - ${d}, '${boxA.id}', ${(7 - d) * 1048576}, ${d}, 10, 7, 1, 1), ((now() at time zone 'utc')::date - ${d}, '${boxB.id}', 524288, 1, 0, 0, 0, 0)228 on conflict (day, mailbox_id) do update set used_bytes = excluded.used_bytes, received = excluded.received, sent = excluded.sent, delivered = excluded.delivered, bounced = excluded.bounced, failed = excluded.failed`)229 }230 // un envoi interne A → B : dernière remise des deux boîtes (l'essai ne dépend pas des autres fichiers)231 const subject = `web-ops ${st.run} ${crypto.randomBytes(2).toString("hex")}`232 await sendMail(st.addrA, st.addrB, subject)233 await waitForMessage(st.addrB, subject)234 const outId = `out_essai_${st.run}`235 sql(`insert into outbound_messages (id, from_address, mailbox_id, recipients, status, attempts, last_error, final_at) values236 ('${outId}', '${st.addrA}', '${boxA.id}', '[{"address":"inconnu@stg.spboucher.ai","status":"bounced","smtp_reply":"550 5.1.1 <inconnu@stg.spboucher.ai>: Recipient address rejected: User unknown"}]'::jsonb, 'bounced', 1, 'bounced', now())237 on conflict (id) do nothing`)238239 // ---- stockage : courbe nommée et décrite, projection en tirets, tableau équivalent, par boîte240 await openAdmin(page, "storage")241 const storage = page.getByTestId("trend-storage")242 await expect(storage.getByRole("img", { name: /Évolution de l'espace utilisé — Toutes les boîtes/ })).toBeVisible()243 await expect(storage.getByTestId("trend-projection")).toBeVisible()244 await expect(storage.getByTestId("trend-storage-summary")).toContainText("Projection linéaire (moindres carrés)")245 await page.getByTestId("trend-storage-box").selectOption({ label: st.addrA })246 await expect(storage.getByRole("img", { name: new RegExp(`Évolution de l'espace utilisé — ${st.addrA.replace(/[.]/g, "\\.")}`) })).toBeVisible()247 await expect(storage.getByTestId("trend-storage-rate")).toContainText("/ jour")248 await expect(storage.getByTestId("trend-storage-projected")).not.toHaveText("—")249 await expect(storage.locator("svg desc")).toContainText("dans 30 jours")250 await axeThemes(page, "ops-storage-trend")251 await noOverflow(page)252 await shots(page, "storage-trend")253 await storage.getByRole("group", { name: /Affichage de « Évolution de l'espace/ }).getByRole("button", { name: "Tableau" }).click()254 expect(await storage.getByTestId("trend-storage-table").locator("tbody tr").count()).toBeGreaterThanOrEqual(6)255256 // ---- livraison : issue par jour (barres à motifs + légende), tableau aux mêmes nombres, remises à problème257 await openAdmin(page, "metrics")258 const del = page.getByTestId("trend-deliveries")259 await expect(del.getByRole("img", { name: "Issue des remises par jour" })).toBeVisible()260 const raw = (await api("GET", "/api/admin/trends?metric=deliveries&days=14")).body.data as { delivered: number; bounced: number; failed: number; sent: number }[]261 const out = raw.reduce((n, d) => n + d.delivered + d.bounced + d.failed + Math.max(0, d.sent - d.delivered - d.bounced - d.failed), 0)262 expect(out).toBeGreaterThanOrEqual(60)263 await expect(del.getByTestId("trend-deliveries-total")).toHaveText(String(out))264 expect(await del.locator('[data-testid="chart-days"] g[data-day]').evaluateAll((gs) => gs.reduce((n, g) => n + Number(g.getAttribute("data-total")), 0))).toBe(out)265 await del.getByRole("group", { name: /Affichage de « Issue des remises/ }).getByRole("button", { name: "Tableau" }).click()266 expect(await del.getByTestId("trend-deliveries-table").locator('tbody td[data-series="bounced"]').evaluateAll((tds) => tds.reduce((n, td) => n + Number(td.textContent), 0))).toBe(raw.reduce((n, d) => n + d.bounced, 0))267 await del.getByRole("group", { name: /Affichage de « Issue des remises/ }).getByRole("button", { name: "Graphique" }).click()268 const problem = page.locator(`[data-testid="problem-delivery"][data-outbound-id="${outId}"]`)269 await expect(problem).toContainText("inconnu@stg.spboucher.ai")270 await expect(problem.getByTestId("smtp-hint")).toHaveAttribute("data-kind", "unknown_user")271 await expect(problem.getByTestId("smtp-hint")).toContainText("L'adresse du destinataire n'existe pas")272 await expect(problem.getByTestId("smtp-hint")).toContainText("Définitif")273 await expect(problem.getByTestId("smtp-hint")).toContainText("550 5.1.1")274 await axeThemes(page, "ops-delivery-trend")275 await noOverflow(page)276 await shots(page, "delivery-trend")277278 // ---- API : requêtes et erreurs par jour, liées aux vues par clé du même onglet279 // quelques appels réels avec une clé d'API (dont un en erreur) : l'essai ne dépend pas de ceux des autres fichiers280 grantReauth()281 const addrId = (await api("GET", `/api/v1/addresses/${encodeURIComponent(st.addrA)}`)).body.id282 const key = await api("POST", "/api/admin/api-keys", { name: `Tendances ${st.run}`, scopes: ["mail.read"], address_ids: [addrId] })283 expect(key.status, JSON.stringify(key.body)).toBe(201)284 for (let i = 0; i < 3; i++) expect((await apiKey(key.body.token, "GET", "/me")).status).toBe(200)285 expect((await apiKey(key.body.token, "GET", "/messages/introuvable")).ok).toBe(false)286 await openAdmin(page, "usage")287 const apiTrend = page.getByTestId("trend-api")288 const requests = ((await api("GET", "/api/admin/trends?metric=api&days=14")).body.data as { requests: number }[]).reduce((n, d) => n + d.requests, 0)289 expect(requests).toBeGreaterThan(0)290 await expect(apiTrend.getByTestId("trend-api-requests")).toHaveText(new RegExp(`^${String(requests).replace(/\B(?=(\d{3})+(?!\d))/g, "\\s")}$`))291 await expect(apiTrend.getByRole("img", { name: "Utilisation de l'API par jour" })).toBeVisible()292 await expect(apiTrend.locator('g[data-series="errors"]')).toBeVisible()293 await axeThemes(page, "ops-api-trend")294 await noOverflow(page)295 await shots(page, "api-trend")296297 // ---- boîtes : espace, dernière remise, veilleur, lien vers les appareils du propriétaire298 await openAdmin(page, "mailboxes")299 const rowA = page.locator(`tr[data-address="${st.addrA}"]`)300 await expect(rowA.getByTestId("mb-status")).toHaveAttribute("data-watcher", "ok")301 await expect(rowA.getByTestId("mb-status")).toContainText("Veilleur actif")302 await expect(rowA.getByTestId("mb-last")).toContainText(/Dernière réception|Dernier envoi/)303 await expect(page.locator(`tr[data-address="${st.addrB}"]`).getByTestId("mb-last")).toContainText(/Dernière réception/)304 await expect(rowA.getByTestId("mb-used")).not.toHaveText("—")305 await axeThemes(page, "ops-mailboxes")306 await noOverflow(page)307 await shots(page, "mailboxes")308 await page.locator('section[data-user="admin"]').getByTestId("user-devices").click()309 await expect(page).toHaveURL(/\/admin\/devices\?user=admin$/)310 await expect(page.getByTestId("devices-user")).toHaveValue("admin")311312 // ---- file d'attente : état réel du serveur de recette (vide ou non), diagnostic par message313 await openAdmin(page, "queue")314 await expect(page.getByTestId("queue-empty").or(page.getByTestId("queue-table"))).toBeVisible()315 if (await page.getByTestId("queue-table").isVisible()) {316 await page.getByTestId("queue-table").getByRole("button", { name: "Détail" }).first().click()317 await expect(page.getByTestId("queue-detail")).toBeVisible()318 }319 await axeThemes(page, "ops-queue")320 await shots(page, "queue")321 sql(`delete from outbound_messages where id = '${outId}'`)322})323324test("rôle membre : aucune donnée d'exploitation, aucune pastille, API refusée", async ({ browser }) => {325 const env = { ...process.env, PORT: String(PORT), DATABASE_URL: DB, SPMAIL_ORIGIN: ORIGIN }326 const out = execFileSync(path.join(root, "scripts/dev.sh"), ["node", "dist/cli.mjs", "invite"], { cwd: root, env, encoding: "utf8" })327 const link = out.match(/http\S+\/enroll#[A-Za-z0-9_-]+/)?.[0]328 expect(link).toBeTruthy()329 const context = await browser.newContext({ baseURL: ORIGIN, locale: "fr-CA", storageState: { cookies: [], origins: [] } })330 const page = await context.newPage()331 const requests: string[] = []332 page.on("request", (r) => requests.push(r.url()))333 await addAuthenticator(context, page)334 await page.goto(link!)335 await page.getByLabel("Nom affiché").fill("Membre Essai")336 await page.getByLabel("Identifiant").fill(`membre${st.run}`)337 await page.getByRole("button", { name: "Créer la clé d'accès" }).click()338 await expect(page.locator("#sidebar")).toBeAttached()339 await expect(page.getByRole("link", { name: /Administration/ })).toHaveCount(0)340 await expect(page.getByTestId("sidebar-alerts")).toHaveCount(0)341 for (const tab of ["overview", "alerts", "devices", "security"]) {342 await page.goto(`/admin/${tab}`)343 await expect(page.getByRole("alert")).toContainText("Accès réservé aux administrateurs")344 await expect(page.getByTestId("ops-dashboard")).toHaveCount(0)345 }346 expect(requests.filter((u) => u.includes("/api/admin/")), "un membre n'interroge jamais l'API d'administration").toEqual([])347 const codes = await page.evaluate(async () => {348 const out: Record<string, number> = {}349 for (const u of ["/api/admin/health", "/api/admin/alerts", "/api/admin/devices", "/api/admin/trends", "/api/admin/security-events", "/api/admin/deliveries/problems", "/api/admin/mailboxes/status"]) out[u] = (await fetch(u)).status350 out.revoke = (await fetch("/api/admin/devices/sessions/3f2b8c1e-9a4d-4e6f-8b7a-1c2d3e4f5a6b", { method: "DELETE", headers: { "x-spmail": "1" } })).status351 return out352 })353 expect(Object.values(codes).every((c) => c === 403), JSON.stringify(codes)).toBe(true)354 await context.close()355 grantReauth()356})357