Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SP Mail8 * File : tests/e2e/admin/global-teardown.ts9 * Module : tests10 * Repository : https://git.spboucher.ai/sp-mail11 * Project Website : https://mail.spboucher.ai12 * Created : 2026-11-1913 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// Nettoyage : tout ce que le parcours a créé sur le serveur de courrier (alias, listes, boîtes web-*@stg.spboucher.ai) est44// supprimé, les clés d'API révoquées, les webhooks retirés ; contrôle par /api/admin/overview ; puis le backend est arrêté.45import { execFileSync } from "node:child_process"46import fs from "node:fs"47import { cookieCall, purgeTracked, trackedMailboxes } from "../mailboxes"48import { API_HEADERS, DB_NAME, ORIGIN, OUT, STORAGE, isTestAddress } from "./env"49import { killPort } from "./global-setup"5051interface Addr {52 id: string53 address: string54 kind: string55 extra_destinations: string[]56}5758export default async function globalTeardown() {59 try {60 if (!fs.existsSync(STORAGE)) return console.warn("[e2e-admin] no session saved: nothing purged")61 const cookies = (JSON.parse(fs.readFileSync(STORAGE, "utf8")) as { cookies: { name: string; value: string }[] }).cookies62 const h = { cookie: cookies.map((c) => `${c.name}=${c.value}`).join("; "), ...API_HEADERS }63 const get = async <T>(p: string): Promise<T> => (await fetch(`${ORIGIN}${p}`, { headers: h })).json() as Promise<T>64 const call = (method: string, p: string, body?: unknown) => fetch(`${ORIGIN}${p}`, { method, headers: body === undefined ? h : { ...h, "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) })65 // La suppression par /api/v1 exige une réauthentification récente : la base jetable la consigne pour la session du lanceur66 // (nettoyage seulement — les essais de l'invite de clé d'accès passent, eux, par l'interface).67 // (plusieurs suites partagent le PostgreSQL du poste : un refus passager de connexion ne doit pas empêcher la purge)68 for (let i = 0; ; i++) {69 try {70 execFileSync("psql", ["-q", "-d", DB_NAME, "-c", "update sessions set reauth_at = now()"], { stdio: "ignore" })71 break72 } catch (e) {73 if (i >= 4) throw e74 await new Promise((r) => setTimeout(r, 1500))75 }76 }7778 for (const k of await get<{ id: string; state: string }[]>("/api/admin/api-keys").catch(() => [])) if (k.state === "active") await call("DELETE", `/api/admin/api-keys/${k.id}`)79 for (const w of (await get<{ data: { id: string }[] }>("/api/v1/webhooks").catch(() => ({ data: [] }))).data ?? []) await call("DELETE", `/api/v1/webhooks/${w.id}`)80 for (const e of await get<{ host_port: string }[]>("/api/admin/webhook-allowlist").catch(() => [])) await call("DELETE", `/api/admin/webhook-allowlist?host_port=${encodeURIComponent(e.host_port)}`)8182 const addresses = ((await get<{ data: Addr[] }>("/api/v1/addresses").catch(() => ({ data: [] }))).data ?? []).filter((a) => isTestAddress(a.address))83 for (const a of addresses.filter((x) => x.kind !== "mailbox" && x.kind !== "shared")) {84 if (a.extra_destinations?.length) await call("PATCH", `/api/v1/addresses/${a.id}`, { extra_destinations: [] })85 const r = await call("DELETE", `/api/v1/addresses/${a.id}`)86 if (!r.ok) console.log(`[e2e-admin] alias ${a.address} → ${r.status} ${await r.text()}`)87 }88 const users = await get<{ mailboxes: { id: string; address: string }[] }[]>("/api/admin/users")89 for (const u of users)90 for (const m of u.mailboxes) {91 if (!isTestAddress(m.address)) continue92 const r = await call("DELETE", `/api/admin/mailboxes/${m.id}?purge=delete-all-mail`)93 if (!r.ok) console.log(`[e2e-admin] purge ${m.address} → ${r.status} ${await r.text()}`)94 }95 // boîtes inscrites par ce parcours que sa base ne connaît plus (détachées) : reprises puis purgées — celles-là seulement96 const tracked = trackedMailboxes(OUT)97 const failed = await purgeTracked(OUT, cookieCall(ORIGIN, h.cookie))98 // contrôle : plus aucun compte de CE parcours sur le serveur de courrier99 const ov = await get<{ accounts?: { address: string; aliases?: unknown }[] }>("/api/admin/overview")100 const left = (ov.accounts ?? []).map((a) => a.address ?? "").filter((a) => tracked.includes(a))101 console.log(`[e2e-admin] boîtes de ce parcours restées sur le serveur de courrier : ${left.length ? left.join(", ") : "aucune"}${failed.length ? ` (purge en échec, gardées au registre : ${failed.join(", ")})` : ""}`)102 } finally {103 if (!process.env.E2E_KEEP_SERVER) killPort()104 }105}106