Repository Public
1// Pile jetable : base sp_mail_webdev vidée, backend relancé sur 8751 avec le build courant, lien d'amorçage émis.2import { execFileSync, spawn } from "node:child_process"3import crypto from "node:crypto"4import fs from "node:fs"5import path from "node:path"6import http from "node:http"7import { DB, DB_NAME, ORIGIN, OUT, PORT, WEB_DIR, writeState } from "./env"8import { rotateRegistry, trackMailboxes } from "./mailboxes"910const root = path.resolve(import.meta.dirname, "../..")11const env = { ...process.env, PORT: String(PORT), DATABASE_URL: DB, SPMAIL_ORIGIN: ORIGIN, SPMAIL_RATE_SCALE: "50", SPMAIL_LOG_LEVEL: "warn", SPMAIL_WEB_DIR: path.resolve(root, WEB_DIR) }1213export function killPort() {14 // jamais de pkill -f : seulement le PID qui écoute sur notre port15 let out = ""16 try {17 out = execFileSync("lsof", ["-nP", `-iTCP:${PORT}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8" })18 } catch {19 return20 }21 for (const pid of out.split("\n").filter(Boolean)) {22 try {23 process.kill(Number(pid), "SIGTERM")24 } catch {25 /* déjà arrêté */26 }27 }28}2930export default async function globalSetup() {31 fs.mkdirSync(OUT, { recursive: true })32 if (!fs.existsSync(path.resolve(root, WEB_DIR, "index.html")) || !fs.existsSync(path.join(root, "dist/server.mjs"))) throw new Error("run `pnpm build` first")33 const probe = () => fetch("http://127.0.0.1:18080/jmap/session", { signal: AbortSignal.timeout(5000) }).catch(() => null)34 if (!(await probe())) {35 // le tunnel vers le serveur de courrier tombe parfois : on le rouvre (seul usage permis de ssh ici)36 try {37 execFileSync("ssh", ["-f", "-N", "-o", "ExitOnForwardFailure=yes", "-o", "ServerAliveInterval=15", "-L", "18080:127.0.0.1:8080", "BHS64"], { stdio: "ignore", timeout: 20_000 })38 } catch {39 /* port encore tenu par un tunnel figé */40 }41 await new Promise((r) => setTimeout(r, 1500))42 if (!(await probe())) throw new Error("mail server tunnel is down: ssh -f -N -L 18080:127.0.0.1:8080 BHS64")43 }44 killPort()45 await new Promise((r) => setTimeout(r, 600))46 if (!/^sp_mail_[a-z0-9_]*dev$/.test(DB_NAME)) throw new Error("refusing to reset a database whose name is not sp_mail_…dev")47 try {48 execFileSync("createdb", [DB_NAME], { stdio: "ignore" })49 } catch {50 /* existe déjà */51 }52 execFileSync("psql", ["-q", "-d", DB_NAME, "-c", "drop schema public cascade; create schema public;"], { stdio: "ignore" })53 // faux fournisseur d'IA local (compatible OpenAI), scripté par les tests : jamais de vrai fournisseur54 const ai = await startAiStub()55 const log = fs.openSync(`${OUT}/server.log`, "w")56 const server = spawn(path.join(root, "scripts/dev.sh"), ["node", "dist/server.mjs"], { cwd: root, env: { ...env, SPMAIL_AI_LOCAL_URL: `http://127.0.0.1:${ai}/v1`, SPMAIL_AI_LOCAL_KEY: "e2e-key", SPMAIL_AI_LOCAL_MODEL: "stub-model", SPMAIL_AI_EMBED_BACKEND: "off" }, detached: true, stdio: ["ignore", log, log] })57 server.unref()58 for (let i = 0; ; i++) {59 const ok = await fetch(`${ORIGIN}/api/health/ready`).then((r) => r.ok, () => false)60 if (ok) break61 if (i > 80) throw new Error(`backend did not start (see ${OUT}/server.log)`)62 await new Promise((r) => setTimeout(r, 150))63 }64 const out = execFileSync(path.join(root, "scripts/dev.sh"), ["node", "dist/cli.mjs", "bootstrap"], { cwd: root, env, encoding: "utf8" })65 const enrollUrl = out.match(/http\S+\/enroll#[A-Za-z0-9_-]+/)?.[0]66 if (!enrollUrl) throw new Error(`no enrollment link in: ${out}`)67 const run = crypto.randomBytes(3).toString("hex")68 fs.rmSync(`${OUT}/state.json`, { force: true })69 // boîtes d'un parcours précédent interrompu : gardées comme « restes », purgées dès qu'une session existe (helpers.purgeLeftoverMailboxes)70 rotateRegistry(OUT)71 const addrA = `web-a-${run}@stg.spboucher.ai`72 const addrB = `web-b-${run}@stg.spboucher.ai`73 trackMailboxes(OUT, addrA, addrB)74 writeState({ enrollUrl, run, addrA, addrB, serverPid: server.pid })75}7677/**78 * Faux fournisseur compatible OpenAI pour les essais de la couche d'intelligence (même principe que tests/integration/next-ai.test.ts).79 * Il vit dans le processus du lanceur (global-setup), donc pendant tout le parcours. Les tests le pilotent par HTTP :80 * `POST /__script { mode: "normal" | "hostile" | "down" }`, `GET /__seen` (requêtes reçues), `POST /__reset`.81 */82export const AI_STUB_PORT = PORT + 100083const HOSTILE = '<img src=x onerror="window.__pwned=1"> [cliquez ici](javascript:alert(1)) **gras** <script>window.__pwned=1</script>'84async function startAiStub(): Promise<number> {85 let mode: "normal" | "hostile" | "down" = "normal"86 const seen: { path: string; body: unknown }[] = []87 const answer = (system: string, user: string): string => {88 const x = mode === "hostile" ? HOSTILE : ""89 if (/Task: summarise/.test(system)) return JSON.stringify({ summary: x || "Résumé du fil par le modèle d'essai.", decisions: [x || "Décision A"], action_items: [{ text: x || "Répondre à Camille", owner: null, due: null }], deadlines: [{ text: x || "Remise du rapport", date: "2026-12-01" }], timeline: [{ at: "2026-11-20", who: x || "Camille", what: x || "A envoyé le compte rendu" }] })90 if (/draft three alternative replies/.test(system)) return JSON.stringify({ suggestions: [1, 2, 3].map((n) => ({ subject: null, text: x || `Suggestion ${n} du modèle d'essai` })) })91 if (/Task: classify each/.test(system)) return JSON.stringify({ items: [...user.matchAll(/E-mail (\d+):/g)].map((m) => ({ n: Number(m[1]), category: Number(m[1]) % 2 ? "work" : "newsletter", needs_action: Number(m[1]) % 2 === 1, important: Number(m[1]) === 1, reason: x || "Demande directe." })) })92 if (/Propose four subject lines/.test(system)) return JSON.stringify({ subjects: ["Sujet un", "Sujet deux", "Sujet trois", "Sujet quatre"] })93 return x || "Texte réécrit par le modèle d'essai."94 }95 const server = http.createServer((req, res) => {96 let raw = ""97 req.on("data", (d) => (raw += d))98 req.on("end", () => {99 const url = String(req.url)100 const json = (status: number, body: unknown) => (res.writeHead(status, { "content-type": "application/json" }), res.end(JSON.stringify(body)))101 if (url === "/__script") return (mode = (JSON.parse(raw || "{}").mode ?? "normal")), json(200, { mode })102 if (url === "/__seen") return json(200, seen)103 if (url === "/__reset") return (seen.length = 0), (mode = "normal"), json(200, { ok: true })104 const body = raw ? JSON.parse(raw) : null105 seen.push({ path: url, body })106 if (!url.endsWith("/chat/completions")) return json(404, {})107 if (mode === "down") return json(503, { error: { message: "scripted" } })108 const content = answer(String(body.messages[0].content), String(body.messages[body.messages.length - 1].content))109 json(200, { id: "chatcmpl-e2e", object: "chat.completion", model: body.model, choices: [{ index: 0, message: { role: "assistant", content }, finish_reason: "stop" }], usage: { prompt_tokens: 100, completion_tokens: 20 } })110 })111 })112 await new Promise<void>((resolve, reject) => server.once("error", reject).listen(AI_STUB_PORT, "127.0.0.1", () => resolve()))113 server.unref()114 return AI_STUB_PORT115}116