Repository Public
1// /api/v1 — courrier : envoi (pièce jointe, image en ligne), réponse, transfert, brouillons, liste unifiée paginée, recherche,2// synchronisation incrémentale, déplacements, programmation, approbation des envois externes, destinataire injoignable.3import assert from "node:assert/strict"4import crypto from "node:crypto"5import { after, before, test } from "node:test"6import { ApiKey, Client, EXTERNAL_ADDR, ORIGIN, expectV1, reauth, sleep, sql, startServer, stopServer, until } from "../harness"7import { addr, mkKey, mkMailbox, purgeAll, sendAndWait, sess, setupAdmin, type Box } from "./v1-helpers"89let admin: Client10let P: Box, Q: Box, R: Box, X: Box11let kp: ApiKey, kq: ApiKey, kr: ApiKey, kpq: ApiKey12const ALL = ["mail.send", "mail.read", "mail.search", "mail.modify", "mail.delete", "mail.drafts", "mail.attachments.read", "mail.attachments.write"]13const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==", "base64")14const PDF = crypto.randomBytes(30_000)15let original = "" // message reçu par Q (avec pièces jointes)1617async function rejects(p: Promise<unknown>, status: number, code?: string) {18 await assert.rejects(p, (e: any) => e.status === status && (!code || e.code === code))19}20const find = async (k: ApiKey, subject: string, q = "folder=inbox") => (await k.call("GET", `/messages?${q}&limit=100`)).data.find((m: any) => m.subject === subject)21const arrives = (k: ApiKey, subject: string) => until(() => find(k, subject), `réception de « ${subject} »`)22const acctOf = async (b: Box) => (await admin.call("GET", `/api/jmap/${b.id}/session`)).primaryAccounts["urn:ietf:params:jmap:mail"] as string23const outbound = (k: ApiKey, id: string, ...statuses: string[]) => until(async () => { const o = await k.call("GET", `/messages/outbound/${id}`); return statuses.includes(o.status) ? o : null }, `état ${statuses.join("/")}`)2425before(async () => {26 await startServer()27 admin = await setupAdmin()28 ;[P, Q, R, X] = await Promise.all([mkMailbox(admin, "p"), mkMailbox(admin, "q"), mkMailbox(admin, "r"), mkMailbox(admin, "ext")])29 assert.equal(X.address, EXTERNAL_ADDR)30 kp = await mkKey(admin, { scopes: ALL, addresses: [P.addressId] })31 kq = await mkKey(admin, { scopes: ALL, addresses: [Q.addressId] })32 kr = await mkKey(admin, { scopes: ALL, addresses: [R.addressId] })33 kpq = await mkKey(admin, { scopes: ["mail.read", "mail.search"], addresses: [P.addressId, Q.addressId] })34})35after(async () => {36 await purgeAll(admin)37 await stopServer()38})3940test("envoi avec pièce jointe et image en ligne ; HTML assaini côté serveur ; téléchargement cloisonné", async () => {41 const up = await kp.raw("POST", `/files?filename=${encodeURIComponent("rapport été.pdf")}`, new Uint8Array(PDF), { "content-type": "application/pdf" })42 assert.equal(up.status, 201)43 const pdf = await up.json()44 assert.match(pdf.id, /^file_/)45 assert.equal(pdf.size, PDF.length)46 assert.equal(pdf.mailbox, P.address)47 const png = await (await kp.raw("POST", "/files?filename=logo.png", new Uint8Array(PNG), { "content-type": "image/png" })).json()48 // un JSON téléversé reste un flux d'octets ; multipart n'est pas interprété49 assert.equal((await kp.raw("POST", "/files?filename=a.json", new Uint8Array(Buffer.from('{"a":1}')), { "content-type": "application/json" })).status, 201)50 assert.equal((await kp.raw("POST", "/files", new Uint8Array(Buffer.from("x")), { "content-type": "multipart/form-data; boundary=x" })).status, 415)51 // un fichier appartient à la clé et à la boîte qui l'ont téléversé52 await expectV1(kq.call("POST", "/messages/send", { from: Q.address, to: [P.address], subject: "x", text: "x", attachments: [{ file_id: pdf.id }] }), 400, "unknown_file")53 await expectV1(kp.call("POST", "/messages/send", { from: P.address, to: [Q.address], subject: "x", text: "x", attachments: [{ file_id: pdf.id, inline: true }] }), 400, "invalid_inline_image")54 const noWrite = await mkKey(admin, { scopes: ["mail.send"], addresses: [P.addressId] })55 assert.equal((await noWrite.raw("POST", "/files", new Uint8Array(PNG), { "content-type": "image/png" })).status, 403)5657 const html = `<p>Bonjour <b>Q</b> — été, 日本語 <img src="cid:logo" alt="logo"><img src="x" onerror="alert(1)"><script>alert(1)</script><a href="javascript:alert(2)" onclick="x()">piège</a><a href="https://example.org/a?b=1&c=2">lien</a><iframe src="https://evil.example"></iframe></p><style>p{background:url(https://evil.example/t.gif)}</style>`58 const o = await sendAndWait(kp, { from: P.address, to: [{ email: Q.address, name: "Boîte Q" }], cc: [R.address], subject: "Pièces jointes — été 📎", text: "Bonjour Q (texte)", html, attachments: [{ file_id: pdf.id }, { file_id: png.id, inline: true, cid: "logo" }] })59 assert.equal(o.status, "delivered")60 assert.deepEqual(o.recipients.map((r: any) => [r.address, r.status]).sort(), [[Q.address, "delivered"], [R.address, "delivered"]].sort())61 assert.match(o.message_id, /^msg_/)6263 const sum = await arrives(kq, "Pièces jointes — été 📎")64 original = sum.id65 assert.equal(sum.has_attachment, true)66 assert.equal(sum.unread, true)67 const m = await kq.call("GET", `/messages/${sum.id}`)68 assert.equal(m.from[0].email, P.address)69 assert.deepEqual(m.to, [{ email: Q.address, name: "Boîte Q" }])70 assert.equal(m.text.trim(), "Bonjour Q (texte)")71 assert.ok(m.html.includes("<b>Q</b>") && m.html.includes('src="cid:logo"') && m.html.includes('href="https://example.org/a?b=1&c=2"'))72 for (const bad of ["<script", "alert(", "javascript:", "onerror", "onclick", "<iframe", "evil.example", "<style"]) assert.ok(!m.html.includes(bad), `HTML assaini : ${bad}`)73 assert.equal(m.attachments.length, 2)74 const a = m.attachments.find((x: any) => !x.inline), img = m.attachments.find((x: any) => x.inline)75 assert.equal(a.name, "rapport été.pdf")76 assert.equal(a.type, "application/pdf")77 assert.equal(img.cid, "logo")78 assert.deepEqual((await kq.call("GET", `/messages/${sum.id}/attachments`)).data.map((x: any) => x.id).sort(), [a.id, img.id].sort())79 const dl = await kq.raw("GET", `/messages/${sum.id}/attachments/${a.id}`)80 assert.equal(dl.status, 200)81 assert.match(dl.headers.get("content-disposition")!, /^attachment/)82 assert.match(dl.headers.get("content-security-policy")!, /sandbox/)83 assert.ok(Buffer.from(await dl.arrayBuffer()).equals(PDF))84 const dimg = await kq.raw("GET", `/messages/${sum.id}/attachments/${img.id}`)85 assert.match(dimg.headers.get("content-disposition")!, /^attachment/, "même une image est servie en pièce jointe")86 assert.ok(Buffer.from(await dimg.arrayBuffer()).equals(PNG))87 // la pièce jointe n'est accessible ni par une autre clé, ni par un identifiant étranger au message88 assert.equal((await kp.raw("GET", `/messages/${sum.id}/attachments/${a.id}`)).status, 404)89 const other = await arrives(kr, "Pièces jointes — été 📎")90 assert.equal((await kq.raw("GET", `/messages/${sum.id}/attachments/att_${Buffer.from("zzzz").toString("base64url")}`)).status, 404)91 assert.ok(other.id !== sum.id)92 // la copie « Envoyés » de l'expéditeur porte le HTML assaini, jamais celui de l'appelant93 const sentCopy = await kp.call("GET", `/messages/${o.message_id}`)94 assert.deepEqual(sentCopy.folders.map((f: any) => f.role), ["sent"])95 assert.equal(sentCopy.draft, false)96 assert.ok(!sentCopy.html.includes("script") && !sentCopy.html.includes("evil.example"))97})9899test("réponse (fil conservé), répondre à tous, transfert avec pièce jointe", async () => {100 const rep = await kq.call("POST", `/messages/${original}/reply`, { text: "Bien reçu.", reply_all: true })101 assert.equal(rep.status, "sent")102 assert.deepEqual(rep.recipients.map((r: any) => r.address).sort(), [P.address, R.address].sort(), "répondre à tous : expéditeur + copie, sans soi-même")103 const got = await arrives(kp, "Re: Pièces jointes — été 📎")104 const full = await kp.call("GET", `/messages/${got.id}`)105 assert.equal(full.in_reply_to.length, 1)106 assert.deepEqual(full.from.map((f: any) => f.email), [Q.address])107 // même fil que le message envoyé : les deux messages, du plus ancien au plus récent108 const thr = await kp.call("GET", `/threads/${got.thread_id}`)109 assert.deepEqual(thr.messages.map((x: any) => x.subject), ["Pièces jointes — été 📎", "Re: Pièces jointes — été 📎"])110 assert.ok((await kp.call("GET", "/threads?folder=inbox")).data.some((t: any) => t.id === got.thread_id))111 assert.equal((await kq.call("GET", `/messages/${original}`)).answered, true)112 // réponse simple depuis une clé qui ne peut pas écrire au nom de la boîte : refusée113 const ro = await mkKey(admin, { scopes: ["mail.read"], addresses: [Q.addressId] })114 await expectV1(ro.call("POST", `/messages/${original}/reply`, { text: "x" }), 403, "insufficient_scope")115 await expectV1(kp.call("POST", `/messages/${original}/reply`, { text: "x" }), 404, "not_found")116117 // transférer relit le contenu : une clé d'envoi seul ne peut pas s'en servir pour exfiltrer un message118 const sendOnlyQ = await mkKey(admin, { scopes: ["mail.send"], addresses: [Q.addressId] })119 await expectV1(sendOnlyQ.call("POST", `/messages/${original}/forward`, { to: [R.address] }), 403, "insufficient_scope")120 // transfert : la pièce jointe suit121 const fwd = await kq.call("POST", `/messages/${original}/forward`, { to: [R.address], text: "Pour information." })122 assert.equal(fwd.status, "sent")123 const f = await arrives(kr, "Fwd: Pièces jointes — été 📎")124 const ff = await kr.call("GET", `/messages/${f.id}`)125 assert.match(ff.text, /Pour information\.[\s\S]*Forwarded message[\s\S]*Bonjour Q \(texte\)/)126 const att = ff.attachments.find((x: any) => x.name === "rapport été.pdf")127 assert.ok(att, "pièce jointe conservée")128 assert.ok(Buffer.from(await (await kr.raw("GET", `/messages/${f.id}/attachments/${att.id}`)).arrayBuffer()).equals(PDF))129 assert.equal((await kq.call("GET", `/messages/${original}`)).forwarded, true)130})131132test("brouillons : création, liste, lecture, modification, envoi, suppression", async () => {133 const d = await kp.res("POST", "/drafts", { from: P.address, to: [R.address], subject: "brouillon v1", html: "<p>v1<script>x</script></p>" })134 assert.equal(d.status, 201)135 assert.equal(d.body.status, "draft")136 const id = d.body.id137 assert.ok((await kp.call("GET", "/drafts")).data.some((x: any) => x.id === id && x.draft))138 const read = await kp.call("GET", `/drafts/${id}`)139 assert.equal(read.subject, "brouillon v1")140 assert.equal(read.html, "<p>v1</p>")141 assert.equal(read.text, "v1", "partie texte dérivée du HTML")142 await expectV1(kp.call("GET", `/drafts/${original}`), 404)143 // modification : le message est recréé (nouvel identifiant), l'ancien disparaît144 const patched = await kp.call("PATCH", `/drafts/${id}`, { subject: "brouillon v2", text: "v2", html: "<p>v2</p>" })145 assert.notEqual(patched.id, id)146 await expectV1(kp.call("GET", `/drafts/${id}`), 404)147 assert.equal((await kp.call("GET", `/drafts/${patched.id}`)).subject, "brouillon v2")148 assert.equal((await kp.call("GET", "/drafts")).data.filter((x: any) => x.subject.startsWith("brouillon")).length, 1)149 // un brouillon sans destinataire ne part pas150 const empty = (await kp.call("POST", "/drafts", { from: P.address, subject: "sans destinataire" })).id151 await expectV1(kp.call("POST", `/drafts/${empty}/send`, {}), 400, "no_recipients")152 assert.deepEqual(await kp.call("DELETE", `/drafts/${empty}`), { ok: true })153 await expectV1(kp.call("GET", `/drafts/${empty}`), 404)154 // envoi du brouillon : il quitte les brouillons et arrive155 const sent = await kp.call("POST", `/drafts/${patched.id}/send`, {})156 assert.equal(sent.status, "sent")157 await expectV1(kp.call("POST", `/drafts/${patched.id}/send`, {}), 409)158 await arrives(kr, "brouillon v2")159 assert.equal((await kp.call("GET", "/drafts")).data.filter((x: any) => x.subject.startsWith("brouillon")).length, 0)160 // une clé sans mail.drafts ne crée ni ne lit de brouillon ; un brouillon au nom d'une autre adresse est refusé161 const sendOnly = await mkKey(admin, { scopes: ["mail.send"], addresses: [P.addressId] })162 await expectV1(sendOnly.call("POST", "/drafts", { from: P.address, subject: "x" }), 403, "insufficient_scope")163 await expectV1(sendOnly.call("POST", "/messages/send", { from: P.address, to: [R.address], subject: "x", text: "x", draft: true }), 403, "insufficient_scope")164 await expectV1(kp.call("POST", "/drafts", { from: Q.address, subject: "x" }), 403, "from_not_allowed")165})166167test("liste unifiée sur deux boîtes : triée par date, sans doublon ni trou, curseurs stables ; boîte de plus d'une page", async () => {168 // Messages posés directement par JMAP (aucun envoi) avec des dates choisies, dont des égalités dans et entre les boîtes.169 const t0 = Date.parse("2026-01-10T12:00:00Z")170 const expected: { subject: string; t: number }[] = []171 for (const [box, n, label] of [[P, 9, "pagea"], [Q, 8, "pagea"], [P, 130, "pageb"]] as const) {172 const acct = await acctOf(box)173 const inboxId = (await admin.jmap(box.id, [["Mailbox/get", { accountId: acct, properties: ["role"] }, "m"]]))[0][1].list.find((b: any) => b.role === "inbox").id174 const create: Record<string, unknown> = {}175 for (let i = 0; i < n; i++) {176 // pagea : une date sur deux partagée avec l'autre boîte ; pageb : paquets de 7 messages à la même seconde177 const t = label === "pagea" ? t0 + Math.floor(i / 2) * 60_000 : t0 + 86400_000 + Math.floor(i / 7) * 1000178 const subject = `${label} ${box === P ? "P" : "Q"} ${String(i).padStart(3, "0")}`179 if (label === "pagea") expected.push({ subject, t })180 create[`m${i}`] = { mailboxIds: { [inboxId]: true }, keywords: { [label]: true, $seen: true }, receivedAt: new Date(t).toISOString().replace(/\.\d+Z$/, "Z"), from: [{ email: R.address }], to: [{ email: box.address }], subject, bodyValues: { t: { value: `corps ${subject}` } }, textBody: [{ partId: "t", type: "text/plain" }] }181 }182 const r = await admin.jmap(box.id, [["Email/set", { accountId: acct, create }, "c"]])183 assert.equal(Object.keys(r[0][1].created ?? {}).length, n)184 }185 const walk = async (k: ApiKey, q: string, limit: number) => {186 const all: any[] = []187 let cursor: string | null = null, pages = 0188 do {189 const page: any = await k.call("GET", `/messages?${q}&limit=${limit}${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`)190 assert.ok(page.data.length <= limit)191 assert.equal(page.has_more, page.next_cursor !== null)192 all.push(...page.data)193 cursor = page.next_cursor194 assert.ok(++pages < 200)195 } while (cursor)196 return { all, pages }197 }198 for (const limit of [1, 4, 5, 100]) {199 const { all, pages } = await walk(kpq, "label=pagea", limit)200 assert.equal(all.length, 17, `limit=${limit}`)201 assert.equal(new Set(all.map((m) => m.id)).size, 17, "aucun doublon")202 assert.deepEqual(all.map((m) => m.subject).sort(), expected.map((e) => e.subject).sort(), "aucun trou")203 for (let i = 1; i < all.length; i++) assert.ok(Date.parse(all[i - 1].received_at) >= Date.parse(all[i].received_at), "ordre décroissant par date")204 assert.equal(pages, Math.ceil(17 / limit), "pas de page vide en fin de parcours")205 assert.ok(new Set(all.map((m) => m.mailbox)).size === 2, "les deux boîtes sont mêlées")206 }207 // les boîtes sont réellement entrelacées, pas concaténées208 const { all: mixed } = await walk(kpq, "label=pagea", 6)209 const boxes = mixed.map((m) => m.mailbox)210 assert.ok(boxes.slice(0, 6).includes(P.address) && boxes.slice(0, 6).includes(Q.address))211 // une seule adresse demandée212 assert.equal((await walk(kpq, `label=pagea&address=${Q.address}`, 3)).all.length, 8)213 assert.equal((await walk(kpq, `label=pagea&address=${Q.address},${P.address}`, 50)).all.length, 17)214 // boîte de 130 messages (plusieurs pages côté serveur de courrier, égalités d'horodatage par paquets de 7)215 for (const limit of [7, 30, 100]) {216 const { all } = await walk(kpq, "label=pageb", limit)217 assert.equal(all.length, 130, `limit=${limit}`)218 assert.equal(new Set(all.map((m) => m.id)).size, 130)219 for (let i = 1; i < all.length; i++) assert.ok(Date.parse(all[i - 1].received_at) >= Date.parse(all[i].received_at))220 }221 // un curseur n'est valable que pour la requête qui l'a produit222 const first = await kpq.call("GET", "/messages?label=pagea&limit=3")223 await expectV1(kpq.call("GET", `/messages?label=pageb&limit=3&cursor=${first.next_cursor}`), 400, "invalid_cursor")224 await expectV1(kpq.call("GET", "/messages?limit=3&cursor=garbage"), 400, "invalid_cursor")225 await expectV1(kpq.call("GET", "/messages?limit=1000"), 400, "invalid_request")226 // fils : une entrée par conversation227 const thr = await kpq.call("GET", "/threads?label=pagea&limit=100")228 assert.equal(new Set(thr.data.map((t: any) => t.id)).size, thr.data.length)229})230231test("recherche : plein texte, sujet, expéditeur, pièce jointe, non lus, dates ; scope mail.search exigé", async () => {232 const word = `licorne${crypto.randomBytes(3).toString("hex")}`233 await sendAndWait(kq, { from: Q.address, to: [P.address], subject: "note de recherche", text: `Le mot ${word} est dans le corps.` })234 const hit = await until(async () => (await kp.call("GET", `/messages?text=${word}&folder=inbox`)).data[0], "indexation plein texte")235 assert.equal(hit.subject, "note de recherche")236 assert.equal((await kp.call("GET", `/messages?subject=${encodeURIComponent("note de recherche")}&folder=inbox`)).data.length, 1)237 assert.ok((await kp.call("GET", `/messages?from=${Q.address}&folder=inbox`)).data.some((m: any) => m.id === hit.id))238 assert.deepEqual((await kp.call("GET", `/messages?text=${word}&has_attachment=true`)).data, [])239 assert.ok((await kq.call("GET", "/messages?has_attachment=true&folder=inbox")).data.some((m: any) => m.id === original))240 assert.ok((await kp.call("GET", "/messages?unread=true&folder=inbox")).data.some((m: any) => m.id === hit.id))241 assert.deepEqual((await kp.call("GET", `/messages?text=${word}&before=2026-01-01T00:00:00Z`)).data, [])242 assert.equal((await kp.call("GET", `/messages?text=${word}&after=2026-01-01T00:00:00Z&folder=inbox`)).data.length, 1)243 // recherche unifiée sur plusieurs boîtes244 assert.ok((await kpq.call("GET", `/messages?text=${word}`)).data.length >= 2, "copie envoyée (Q) + message reçu (P)")245 const noSearch = await mkKey(admin, { scopes: ["mail.read"], addresses: [P.addressId] })246 await expectV1(noSearch.call("GET", `/messages?text=${word}`), 403, "insufficient_scope")247 assert.ok(Array.isArray((await noSearch.call("GET", "/messages?unread=true")).data))248 await expectV1(kp.call("GET", "/messages?before=not-a-date"), 400, "invalid_request")249})250251test("synchronisation incrémentale (changes), drapeaux et étiquettes", async () => {252 const boot = await kq.call("GET", "/messages/changes")253 assert.match(boot.state, /^st_/)254 assert.deepEqual([boot.created, boot.updated, boot.destroyed], [[], [], []])255 await sendAndWait(kp, { from: P.address, to: [Q.address], subject: "delta 1", text: "x" })256 const m = await arrives(kq, "delta 1")257 const c1 = await kq.call("GET", `/messages/changes?since=${boot.state}`)258 assert.ok(c1.created.includes(m.id))259 assert.notEqual(c1.state, boot.state)260 // drapeaux et étiquettes261 const p = await kq.call("PATCH", `/messages/${m.id}`, { unread: false, starred: true, add_labels: ["Projet-X", "a_suivre"] })262 assert.equal(p.unread, false)263 assert.equal(p.starred, true)264 assert.deepEqual(p.labels, ["a_suivre", "projet-x"])265 assert.ok((await kq.call("GET", "/messages?label=projet-x")).data.some((x: any) => x.id === m.id))266 assert.ok((await kq.call("GET", "/messages?flagged=true")).data.some((x: any) => x.id === m.id))267 const p2 = await kq.call("PATCH", `/messages/${m.id}`, { unread: true, starred: false, remove_labels: ["projet-x"] })268 assert.deepEqual([p2.unread, p2.starred, p2.labels], [true, false, ["a_suivre"]])269 // états SP Mail Next (mots-clés système posés par JMAP, comme le font le webmail et les apps) : rendus par la liste unifiée, sans aller-retour JMAP270 assert.deepEqual([p2.pinned, p2.snoozed, p2.followup], [false, false, false])271 const acctQ = (await admin.call("GET", `/api/jmap/${Q.id}/session`)).primaryAccounts["urn:ietf:params:jmap:mail"]272 const jid = (await admin.jmap(Q.id, [["Email/query", { accountId: acctQ, filter: { subject: "delta 1" }, limit: 1 }, "q"]]))[0][1].ids[0] as string273 const kw = async (patch: Record<string, unknown>) => assert.ok((await admin.jmap(Q.id, [["Email/set", { accountId: acctQ, update: { [jid]: patch } }, "s"]]))[0][1].updated, "mots-clés posés")274 const listed = async () => (await kq.call("GET", "/messages?subject=delta%201")).data.find((x: any) => x.id === m.id)275 await kw({ "keywords/$pinned": true, "keywords/$followup": true })276 let row = await listed()277 assert.deepEqual([row.pinned, row.snoozed, row.followup], [true, false, true])278 assert.deepEqual(row.labels, ["a_suivre"], "les mots-clés système ne sont jamais des étiquettes")279 await kw({ "keywords/$pinned": null, "keywords/$followup": null, "keywords/$snoozed": true })280 row = await listed()281 assert.deepEqual([row.pinned, row.snoozed, row.followup], [false, true, false])282 const full = await kq.call("GET", `/messages/${m.id}`)283 assert.deepEqual([full.pinned, full.snoozed, full.followup], [false, true, false], "même forme sur le message complet")284 await kw({ "keywords/$snoozed": null })285 for (const bad of ["$seen", "a b", "", "x".repeat(40), "é"]) await expectV1(kq.call("PATCH", `/messages/${m.id}`, { add_labels: [bad] }), 400, "invalid_request")286 await expectV1(kq.call("PATCH", `/messages/${m.id}`, { mailboxIds: {} }), 400, "invalid_request")287 const c2 = await kq.call("GET", `/messages/changes?since=${c1.state}`)288 assert.ok(c2.updated.includes(m.id) && !c2.created.includes(m.id))289 // état inconnu ou d'une autre boîte : resynchronisation complète demandée (409)290 await expectV1(kq.call("GET", "/messages/changes?since=st_bm9wZQ"), 409, "resync_required")291 const fake = "st_" + Buffer.from(JSON.stringify({ m: Q.id, s: "zzzz" })).toString("base64url")292 await expectV1(kq.call("GET", `/messages/changes?since=${fake}`), 409, "resync_required")293 const foreign = (await kp.call("GET", "/messages/changes")).state294 await expectV1(kq.call("GET", `/messages/changes?since=${foreign}`), 409, "resync_required")295 await expectV1(kpq.call("GET", "/messages/changes"), 400, "address_required")296 assert.match((await kpq.call("GET", `/messages/changes?address=${P.address}`)).state, /^st_/)297})298299test("archiver, corbeille, restaurer, suppression définitive confirmée, dossiers", async () => {300 await sendAndWait(kp, { from: P.address, to: [R.address], subject: "à ranger", text: "x" })301 const m = await arrives(kr, "à ranger")302 assert.ok(!(await kr.call("GET", "/folders")).data.some((f: any) => f.role === "archive"), "pas de dossier Archive au départ")303 const arch = await kr.call("POST", `/messages/${m.id}/move`, { folder: "archive" })304 assert.deepEqual(arch.folders.map((f: any) => f.role), ["archive"])305 assert.ok((await kr.call("GET", "/folders")).data.some((f: any) => f.role === "archive" && f.total === 1))306 // corbeille (par défaut), puis restauration307 assert.deepEqual(await kr.call("DELETE", `/messages/${m.id}`, {}), { ok: true, permanent: false })308 assert.deepEqual((await kr.call("GET", `/messages/${m.id}`)).folders.map((f: any) => f.role), ["trash"])309 assert.ok((await kr.call("GET", "/messages?folder=trash")).data.some((x: any) => x.id === m.id))310 const back = await kr.call("POST", `/messages/${m.id}/move`, { folder: "inbox" })311 assert.deepEqual(back.folders.map((f: any) => f.role), ["inbox"])312 // dossier personnel313 const f = await kr.res("POST", "/folders", { address: R.address, name: "Projets" })314 assert.equal(f.status, 201)315 assert.deepEqual((await kr.call("POST", `/messages/${m.id}/move`, { folder: f.body.id })).folders.map((x: any) => x.name), ["Projets"])316 assert.ok((await kr.call("GET", `/messages?folder=${f.body.id}`)).data.some((x: any) => x.id === m.id))317 await expectV1(kr.call("POST", `/messages/${m.id}/move`, { folder: "nowhere" }), 400)318 const foreignFolder = (await kp.call("GET", "/folders")).data[0].id319 await expectV1(kr.call("POST", `/messages/${m.id}/move`, { folder: foreignFolder }), 400, "unknown_folder")320 await expectV1(kp.call("POST", "/folders", { address: R.address, name: "x" }), 403, "address_not_allowed")321 // suppression définitive : scope mail.delete ET confirmation explicite322 const noDelete = await mkKey(admin, { scopes: ["mail.read", "mail.modify"], addresses: [R.addressId] })323 await expectV1(noDelete.call("DELETE", `/messages/${m.id}?permanent=true`, { confirm: "permanently-delete" }), 403, "insufficient_scope")324 await expectV1(kr.call("DELETE", `/messages/${m.id}?permanent=true`, {}), 400, "confirmation_required")325 await expectV1(kr.call("DELETE", `/messages/${m.id}?permanent=true`, { confirm: "yes" }), 400, "confirmation_required")326 assert.equal((await kr.call("GET", `/messages/${m.id}`)).subject, "à ranger")327 assert.deepEqual(await kr.call("DELETE", `/messages/${m.id}?permanent=true`, { confirm: "permanently-delete" }), { ok: true, permanent: true })328 await expectV1(kr.call("GET", `/messages/${m.id}`), 404)329 // une clé en lecture seule ne modifie rien330 const ro = await mkKey(admin, { scopes: ["mail.read"], addresses: [R.addressId] })331 const any = (await ro.call("GET", "/messages?folder=inbox")).data[0]332 await expectV1(ro.call("DELETE", `/messages/${any.id}`, {}), 403, "insufficient_scope")333 await expectV1(ro.call("POST", `/messages/${any.id}/move`, { folder: "trash" }), 403, "insufficient_scope")334})335336test("programmation : send_at → scheduled → remis à l'heure ; annulation", async () => {337 const at = new Date(Date.now() + 5000)338 const r = await kp.res("POST", "/messages/send", { from: P.address, to: [R.address], subject: "programmé", text: "plus tard", send_at: at.toISOString() })339 assert.equal(r.status, 202)340 assert.equal(r.body.status, "scheduled")341 assert.deepEqual(r.body.recipients.map((x: any) => x.status), ["scheduled"])342 assert.ok((await kp.call("GET", "/messages/scheduled")).data.some((x: any) => x.id === r.body.id))343 assert.ok((await admin.call("GET", "/api/admin/scheduled")).some((x: any) => x.id === r.body.id))344 await sleep(1500)345 assert.equal(await find(kr, "programmé"), undefined, "rien n'est parti avant l'heure")346 assert.equal((await kp.call("GET", `/messages/outbound/${r.body.id}`)).status, "scheduled")347 const done = await outbound(kp, r.body.id, "delivered")348 assert.ok(new Date(done.submitted_at).getTime() >= at.getTime() - 500, "soumis à l'échéance, pas avant")349 await arrives(kr, "programmé")350 assert.deepEqual((await kp.call("GET", "/messages/scheduled")).data.filter((x: any) => x.id === r.body.id), [])351352 // annulation353 const later = await kp.call("POST", "/messages/send", { from: P.address, to: [R.address], subject: "annulé", text: "x", send_at: new Date(Date.now() + 60_000).toISOString() })354 await expectV1(kq.call("DELETE", `/messages/scheduled/${later.id}`), 404, "not_found")355 const c = await kp.call("DELETE", `/messages/scheduled/${later.id}`)356 assert.equal(c.status, "cancelled")357 await expectV1(kp.call("DELETE", `/messages/scheduled/${later.id}`), 409, "not_cancellable")358 await expectV1(kp.call("GET", `/messages/${later.message_id}`), 404) // le brouillon stocké est détruit359 // annulation par l'administrateur360 const l2 = await kp.call("POST", "/messages/send", { from: P.address, to: [R.address], subject: "annulé 2", text: "x", send_at: new Date(Date.now() + 60_000).toISOString() })361 assert.equal((await admin.call("DELETE", `/api/admin/scheduled/${l2.id}`)).outbound.status, "cancelled")362 await expectV1(kp.call("POST", "/messages/send", { from: P.address, to: [R.address], subject: "x", text: "x", send_at: new Date(Date.now() + 40 * 86400_000).toISOString() }), 400, "send_at_too_far")363 await expectV1(kp.call("POST", "/messages/send", { from: P.address, to: [R.address], subject: "x", text: "x", send_at: "demain" }), 400, "invalid_request")364 // une heure passée = envoi immédiat365 assert.equal((await kp.call("POST", "/messages/send", { from: P.address, to: [X.address], subject: "heure passée", text: "x", send_at: new Date(Date.now() - 60_000).toISOString() })).status, "sent")366})367368test("envois externes : approbation humaine par défaut, refus, politique deny / allow, domaines permis", async () => {369 // X est une boîte de recette traitée comme « externe » par le crochet de test SPMAIL_TREAT_AS_EXTERNAL (rien ne sort du serveur).370 const agent = await mkKey(admin, { scopes: ["mail.send"], addresses: [P.addressId], external: "approval" })371 const r = await agent.res("POST", "/messages/send", { from: P.address, to: [X.address], cc: [R.address], subject: "vers l'extérieur", text: "à approuver" })372 assert.equal(r.status, 202)373 assert.equal(r.body.status, "pending_approval")374 assert.match(r.body.approval_id, /^[0-9a-f-]{36}$/)375 assert.equal(r.body.external, true)376 // un destinataire interne seul ne demande aucune approbation377 assert.equal((await agent.call("POST", "/messages/send", { from: P.address, to: [R.address], subject: "interne", text: "x" })).status, "sent")378 await sleep(1500)379 assert.equal(await find(kr, "vers l'extérieur"), undefined, "rien n'est parti, pas même vers le destinataire interne")380 const pending = await admin.call("GET", "/api/admin/approvals")381 const ap = pending.find((a: any) => a.id === r.body.approval_id)382 assert.equal(ap.subject, "vers l'extérieur")383 assert.deepEqual(ap.external_recipients, [X.address])384 assert.equal(ap.from, P.address)385 assert.equal((await admin.call("GET", "/api/admin/metrics")).pending_approvals >= 1, true)386 // l'approbation exige une réauthentification ; elle envoie le brouillon stocké et lie le message sortant387 await sql`update sessions set reauth_at = null`388 await rejects(admin.call("POST", `/api/admin/approvals/${ap.id}/approve`, {}), 403, "reauth_required")389 await reauth(admin)390 const ok = await admin.call("POST", `/api/admin/approvals/${ap.id}/approve`, {})391 assert.equal(ok.outbound.id, r.body.id)392 assert.equal(ok.outbound.status, "sent")393 await rejects(admin.call("POST", `/api/admin/approvals/${ap.id}/approve`, {}), 409, "not_pending")394 assert.equal((await outbound(agent, r.body.id, "delivered")).status, "delivered")395 const kx = await mkKey(admin, { scopes: ["mail.read"], addresses: [X.addressId] })396 await arrives(kx, "vers l'extérieur")397 // refus : le message est annulé et son brouillon détruit398 const r2 = await agent.call("POST", "/messages/send", { from: P.address, to: [X.address], subject: "refusé", text: "x" })399 const rej = await admin.call("POST", `/api/admin/approvals/${r2.approval_id}/reject`, {})400 assert.equal(rej.outbound.status, "cancelled")401 assert.equal((await agent.call("GET", `/messages/outbound/${r2.id}`)).status, "cancelled")402 assert.equal((await admin.call("GET", "/api/admin/approvals?status=rejected")).length, 1)403 // approbation expirée (7 jours) : annulée par le travailleur404 const r3 = await agent.call("POST", "/messages/send", { from: P.address, to: [X.address], subject: "expirera", text: "x" })405 await sql`update send_approvals set expires_at = now() - interval '1 minute' where id = ${r3.approval_id}`406 await rejects(admin.call("POST", `/api/admin/approvals/${r3.approval_id}/approve`, {}), 409, "not_pending")407 await until(async () => (await agent.call("GET", `/messages/outbound/${r3.id}`)).status === "cancelled", "approbation expirée annulée", 15000)408 await sleep(500)409 assert.equal(await find(kx, "refusé"), undefined)410 assert.equal(await find(kx, "expirera"), undefined)411 // deny : refus net ; allow : envoi direct ; domaines permis412 const deny = await mkKey(admin, { scopes: ["mail.send"], addresses: [P.addressId], external: "deny" })413 await expectV1(deny.call("POST", "/messages/send", { from: P.address, to: [X.address], subject: "x", text: "x" }), 403, "external_send_denied")414 await expectV1(deny.call("POST", "/messages/send", { from: P.address, to: ["someone@example.org"], subject: "x", text: "x" }), 403, "external_send_denied")415 const scoped = await mkKey(admin, { scopes: ["mail.send"], addresses: [P.addressId], external: "deny", domains: ["only.example"] })416 await expectV1(scoped.call("POST", "/messages/send", { from: P.address, to: [R.address], subject: "x", text: "x" }), 403, "recipient_domain_not_allowed")417 // par défaut (aucune politique précisée) une clé est en « approval » : un agent ne peut pas écrire dehors sans validation418 await reauth(admin)419 const dflt = await admin.call("POST", "/api/admin/api-keys", { name: "défaut", scopes: ["mail.send"], address_ids: [P.addressId] })420 const d = await new ApiKey(dflt.token).res("POST", "/messages/send", { from: P.address, to: ["someone@example.org"], subject: "jamais envoyé", text: "x" })421 assert.equal(d.status, 202)422 assert.equal(d.body.status, "pending_approval")423 await admin.call("POST", `/api/admin/approvals/${d.body.approval_id}/reject`, {})424})425426test("destinataire injoignable : bounced avec la réponse SMTP ; état par destinataire", async () => {427 const ghost = addr("ghost-does-not-exist")428 const o = await sendAndWait(kp, { from: P.address, to: [ghost], subject: "vers personne", text: "x" })429 assert.equal(o.status, "bounced")430 assert.equal(o.recipients[0].status, "bounced")431 assert.match(o.recipients[0].smtp_reply, /^550 5\.1\.1/)432 assert.ok(o.final_at)433 // deux destinataires, un seul valide : chacun son état ; l'état global est le pire434 const mixed = await sendAndWait(kp, { from: P.address, to: [Q.address, addr("ghost2")], subject: "mixte", text: "x" })435 assert.equal(mixed.status, "bounced")436 assert.deepEqual(Object.fromEntries(mixed.recipients.map((r: any) => [r.address, r.status])), { [Q.address]: "delivered", [addr("ghost2")]: "bounced" })437 await arrives(kq, "mixte")438 const ev = (await kp.call("GET", "/events?type=message.bounced")).data439 assert.ok(ev.some((e: any) => e.data.outbound_id === o.id && e.data.recipients[0].smtp_reply.startsWith("550")))440 // liste des envois : pagination par curseur, filtre par état441 const page1 = await kp.call("GET", "/messages/outbound?limit=2")442 const page2 = await kp.call("GET", `/messages/outbound?limit=2&cursor=${page1.next_cursor}`)443 assert.equal(page1.data.length, 2)444 assert.ok(page2.data.length >= 1 && !page2.data.some((x: any) => page1.data.some((y: any) => y.id === x.id)))445 assert.ok((await kp.call("GET", "/messages/outbound?status=bounced")).data.every((x: any) => x.status === "bounced"))446 await expectV1(kq.call("GET", `/messages/outbound/${o.id}`), 404, "not_found")447 const metrics = await admin.call("GET", "/api/admin/metrics")448 assert.ok(metrics.by_address.find((a: any) => a.address === P.address).bounced >= 2)449 assert.ok(metrics.by_day[0].delivered >= 1)450 // session du propriétaire sur /api/v1 : mêmes routes, ses propres droits451 const mine = await sess(admin, "GET", "/me")452 assert.equal(mine.type, "user")453 assert.ok(mine.addresses.some((a: any) => a.address === P.address))454 assert.ok((await sess(admin, "GET", `/messages?address=${P.address}&limit=1`)).data.length === 1)455 assert.equal((await fetch(`${ORIGIN}/api/v1/messages`)).status, 401)456})457