Repository Public
1// /api/v1 — modèles : lecture, rendu et envoi réel par modèle (mise en page conservée, valeurs échappées, variables contrôlées, cloisonnement).2import assert from "node:assert/strict"3import { after, before, test } from "node:test"4import { ApiKey, Client, cli, startServer, stopServer, tokenOf, until } from "../harness"5import { mkKey, mkMailbox, purgeAll, setupAdmin, type Box } from "./v1-helpers"67let admin: Client8let A: Box, B: Box9let ka: ApiKey, kb: ApiKey10let tpl = ""11const HTML = `<!DOCTYPE html><html><head><meta charset="utf-8"><style>@media (prefers-color-scheme: dark){.card{background:#111!important}}</style></head><body><table role="presentation" width="600"><tr><td class="card" style="padding:24px">Bonjour {{first_name}}, votre code est <b>{{code}}</b>. <a href="{{action_url}}">Ouvrir</a><script>alert(1)</script></td></tr></table></body></html>`12async function rejects(p: Promise<unknown>, status: number, code?: string) {13 await assert.rejects(p, (e: any) => e.status === status && (!code || e.code === code))14}1516before(async () => {17 await startServer()18 admin = await setupAdmin()19 ;[A, B] = await Promise.all([mkMailbox(admin, "ta"), mkMailbox(admin, "tb")])20 ka = await mkKey(admin, { scopes: ["mail.send"], addresses: [A.addressId] })21 kb = await mkKey(admin, { scopes: ["mail.read", "mail.search"], addresses: [B.addressId] })22 tpl = (await admin.call("POST", "/api/templates", { name: "Code", subject: "Votre code, {{first_name}}", html: HTML, text: "Bonjour {{first_name}}, code {{code}} : {{action_url}}",23 variables: [{ name: "first_name", example: "Zoé", required: true }, { name: "code", example: "000000", required: true }, { name: "action_url", example: "https://example.org/x", required: false }] })).id24})25after(async () => {26 await purgeAll(admin)27 await stopServer()28})2930test("une clé lit et rend les modèles de la personne qui l'a créée", async () => {31 const list = await ka.call("GET", "/templates")32 assert.deepEqual(list.templates.map((t: any) => t.id), [tpl])33 assert.equal(list.templates[0].html, undefined)34 const full = await ka.call("GET", `/templates/${tpl}`)35 assert.ok(!full.html.includes("<script"))36 const r = await ka.call("POST", `/templates/${tpl}/render`, { variables: { first_name: "<i>Max</i>", code: "123456" } })37 assert.equal(r.subject, "Votre code, <i>Max</i>")38 assert.match(r.html, /Bonjour <i>Max<\/i>/)39 assert.deepEqual(r.missing, [])40 assert.deepEqual((await ka.call("POST", `/templates/${tpl}/render`, { variables: {} })).missing, ["code", "first_name"])41})4243test("envoi réel par modèle : mise en page conservée, valeurs échappées, lien contrôlé", async () => {44 const sent = await ka.call("POST", "/messages/send", { from: A.address, to: [{ email: B.address }], template_id: tpl,45 variables: { first_name: "Zoé <b>", code: "424242", action_url: "javascript:alert(1)" } })46 assert.ok(["queued", "sent", "delivered"].includes(sent.status), `état inattendu : ${sent.status} ${JSON.stringify(sent.recipients)} ${sent.last_error ?? ""}`)47 const got = await until(async () => (await kb.call("GET", "/messages?folder=inbox&limit=50")).data.find((m: any) => m.subject === "Votre code, Zoé <b>"), "réception du message issu du modèle")48 const jmapAcct = (await admin.call("GET", `/api/jmap/${B.id}/session`)).primaryAccounts["urn:ietf:params:jmap:mail"]49 const q = await admin.jmap(B.id, [["Email/query", { accountId: jmapAcct, filter: { subject: "Votre code" } }, "q"],50 ["Email/get", { accountId: jmapAcct, "#ids": { resultOf: "q", name: "Email/query", path: "/ids" }, properties: ["htmlBody", "textBody", "bodyValues"], fetchAllBodyValues: true }, "g"]])51 const e = q[1][1].list[0]52 const html = e.bodyValues[e.htmlBody[0].partId].value as string, text = e.bodyValues[e.textBody[0].partId].value as string53 assert.match(html, /prefers-color-scheme/, "le bloc <style> du modèle est conservé")54 assert.match(html, /role="presentation"/)55 assert.match(html, /Bonjour Zoé <b>, votre code est <b>424242<\/b>/)56 assert.match(html, /<a href="#"/, "une URL non http(s) est neutralisée")57 assert.ok(!/<script|javascript:/i.test(html))58 assert.match(text, /code 424242/)59 assert.ok(got.id)60})6162test("variables manquantes ou inconnues, conflit avec html, sujet imposé", async () => {63 const base = { from: A.address, to: [{ email: B.address }], template_id: tpl }64 await rejects(ka.call("POST", "/messages/send", { ...base, variables: { first_name: "Zoé" } }), 400, "missing_variables")65 await rejects(ka.call("POST", "/messages/send", { ...base, variables: { first_name: "Z", code: "1", inconnue: "x" } }), 400, "unknown_variables")66 await rejects(ka.call("POST", "/messages/send", { ...base, html: "<p>x</p>", variables: { first_name: "Z", code: "1" } }), 400, "template_conflict")67 await rejects(ka.call("POST", "/messages/send", { from: A.address, to: [{ email: B.address }], text: "x", variables: { a: "b" } }), 400, "template_conflict")68 await rejects(ka.call("POST", "/messages/send", { ...base, template_id: "00000000-0000-4000-8000-000000000000", variables: {} }), 404, "unknown_template")69 const s = await ka.call("POST", "/messages/send", { ...base, subject: "Sujet imposé", variables: { first_name: "Z", code: "9" } })70 assert.ok(["queued", "sent", "delivered"].includes(s.status), s.status)71 await until(async () => (await kb.call("GET", "/messages?folder=inbox&limit=50")).data.find((m: any) => m.subject === "Sujet imposé"), "sujet imposé reçu")72})7374test("cloisonnement : la clé d'un autre utilisateur ne voit ni n'envoie ce modèle", async () => {75 const other = new Client("web")76 await other.enroll(tokenOf(await cli("invite")), "tiers", "Tiers")77 await rejects(other.call("GET", `/api/templates/${tpl}`), 404)78 const r = await other.raw("GET", `/api/v1/templates/${tpl}`)79 assert.equal(r.status, 404)80 assert.equal(((await (await other.raw("GET", "/api/v1/templates")).json()) as any).templates.length, 0)81})8283test("List-Unsubscribe long : livré tel quel (aucun mot encodé), en-tête en un clic présent", async () => {84 const url = `https://www.spboucher.ai/api/newsletter/unsubscribe/${"a".repeat(120)}`85 const subject = `Désabonnement ${Date.now()}`86 await ka.call("POST", "/messages/send", { from: A.address, to: [{ email: B.address }], subject, text: "x",87 headers: { "List-Unsubscribe": `<${url}>, <mailto:unsubscribe@stg.spboucher.ai>`, "List-Unsubscribe-Post": "List-Unsubscribe=One-Click" } })88 const jmapAcct = (await admin.call("GET", `/api/jmap/${B.id}/session`)).primaryAccounts["urn:ietf:params:jmap:mail"]89 const raw = await until(async () => {90 const q = await admin.jmap(B.id, [["Email/query", { accountId: jmapAcct, filter: { subject: "Désabonnement" } }, "q"],91 ["Email/get", { accountId: jmapAcct, "#ids": { resultOf: "q", name: "Email/query", path: "/ids" }, properties: ["subject", "header:List-Unsubscribe:asRaw", "header:List-Unsubscribe-Post:asText"] }, "g"]])92 return q[1][1].list.find((m: any) => m.subject === subject)93 }, "message avec List-Unsubscribe reçu")94 const lu = String(raw["header:List-Unsubscribe:asRaw"]).replace(/\r?\n[ \t]+/g, "")95 assert.ok(!lu.includes("=?"), `mot encodé dans l'en-tête : ${lu}`)96 assert.ok(lu.includes(`<${url}>`) && lu.includes("<mailto:unsubscribe@stg.spboucher.ai>"), lu)97 assert.match(String(raw["header:List-Unsubscribe-Post:asText"]), /List-Unsubscribe=One-Click/)98 await rejects(ka.call("POST", "/messages/send", { from: A.address, to: [{ email: B.address }], subject: "x", text: "x", headers: { "List-Unsubscribe": "<javascript:alert(1)>" } }), 400, "invalid_header")99})100