SPB Git

Repository Public

sdk-ts.test.ts 28.4 KB 428 lines typescript

1// SDK TypeScript (@spboucher/spmail) : comportements du client (reprises, idempotence, erreurs, signature) avec un fetch factice,2// puis parcours complet contre le vrai serveur (vrai PostgreSQL, vrai Stalwart, adresses api-…@stg.spboucher.ai purgées à la fin).3import assert from "node:assert/strict"4import { execFileSync } from "node:child_process"5import path from "node:path"6import { after, before, test } from "node:test"7import { Client, EXTERNAL_ADDR, ORIGIN, Receiver, reauth, startServer, stopServer, until } from "../harness"8import { mkKey, mkMailbox, purgeAll, setupAdmin, type Box } from "./v1-helpers"9import {10  AuthenticationError, BadRequestError, ConflictError, ConnectionError, NotFoundError, OPERATION_SCOPES, PermissionDeniedError, RateLimitError, SPMail, SPMailError,11  ServerError, SignatureVerificationError, TimeoutError, constructWebhookEvent, signWebhookPayload, verifyWebhookSignature, type MessageSummary,12} from "../../packages/sdk-ts/src/index"1314const PKG = path.resolve(import.meta.dirname, "../../packages/sdk-ts")15const ALL = ["mail.send", "mail.read", "mail.search", "mail.modify", "mail.delete", "mail.drafts", "mail.attachments.read", "mail.attachments.write", "mail.addresses.read", "mail.aliases.manage", "mail.webhooks.manage"]16let admin: Client17let A: Box, B: Box, C: Box, X: Box18let a: SPMail, b: SPMail, c: SPMail19let tokenA = ""20let keyAId = ""2122// ------------------------------------------------------------------ fetch factice : file de réponses, journal des appels23type Call = { url: string; method: string; headers: Record<string, string>; body: unknown }24function fake(script: (Response | Error | ((call: Call) => Response | Promise<Response>))[]) {25  const calls: Call[] = []26  const fetch = async (url: string, init?: RequestInit): Promise<Response> => {27    const call = { url, method: init?.method ?? "GET", headers: (init?.headers ?? {}) as Record<string, string>, body: init?.body }28    calls.push(call)29    const next = script.shift()30    if (!next) throw new Error("fake fetch: script exhausted")31    if (next instanceof Error) throw next32    return typeof next === "function" ? next(call) : next33  }34  return { fetch, calls }35}36const json = (status: number, body: unknown, headers: Record<string, string> = {}) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "x-request-id": "req_test", ...headers } })37const err = (status: number, code: string, headers: Record<string, string> = {}) => json(status, { error: { code, message: `msg ${code}`, details: { n: 1 } } }, headers)38const sdk = (f: ReturnType<typeof fake>, extra: Record<string, unknown> = {}) => new SPMail({ apiKey: "spm_unit_test", baseUrl: "http://localhost:1", fetch: f.fetch, ...extra })3940before(async () => {41  await startServer()42  admin = await setupAdmin()43  ;[A, B, C, X] = await Promise.all([mkMailbox(admin, "sa"), mkMailbox(admin, "sb"), mkMailbox(admin, "sc"), mkMailbox(admin, "ext")])44  assert.equal(X.address, EXTERNAL_ADDR)45  const mk = async (box: Box, external: "allow" | "approval" = "allow") => new SPMail({ apiKey: (await mkKey(admin, { scopes: ALL, addresses: [box.addressId], external })).token, baseUrl: ORIGIN })46  const ka = await mkKey(admin, { scopes: ALL, addresses: [A.addressId] })47  tokenA = ka.token48  keyAId = ka.id49  a = new SPMail({ apiKey: ka.token, baseUrl: ORIGIN })50  b = await mk(B)51  c = await mk(C)52})53after(async () => {54  await purgeAll(admin)55  await stopServer()56})5758// ================================================================== sans réseau59test("les types générés sont à jour par rapport à docs/OPENAPI.yaml", () => {60  const out = execFileSync("node", ["scripts/generate.mjs", "--check"], { cwd: PKG, encoding: "utf8" })61  assert.match(out, /up to date/)62  assert.deepEqual(OPERATION_SCOPES.getMessagesId, ["mail.read"])63})6465test("construction : clé obligatoire, http refusé hors boucle locale, la clé n'apparaît dans aucune représentation", async () => {66  assert.throws(() => new SPMail({ apiKey: "" }), TypeError)67  assert.throws(() => new SPMail({ apiKey: "spm_x", baseUrl: "http://mail.example.org" }), /plain http/)68  assert.equal(new SPMail({ apiKey: "spm_x" }).baseUrl, "https://mail.spboucher.ai/api/v1")69  assert.equal(new SPMail({ apiKey: "spm_x", baseUrl: "https://h.example/api/v1/" }).baseUrl, "https://h.example/api/v1")70  const client = new SPMail({ apiKey: "spm_secretsecret_value" })71  const { inspect } = await import("node:util")72  assert.ok(!inspect(client, { depth: 10, showHidden: true }).includes("secretsecret"))73  assert.ok(!JSON.stringify(client).includes("secretsecret"))74  // une erreur ne transporte jamais la clé75  const f = fake([err(401, "invalid_api_key")])76  const e = await sdk(f, { apiKey: "spm_secretsecret_value" }).me().catch((x) => x)77  assert.ok(e instanceof AuthenticationError)78  assert.ok(!inspect(e, { depth: 10 }).includes("secretsecret") && !JSON.stringify({ ...e, m: e.message }).includes("secretsecret"))79  assert.equal(f.calls[0].headers.authorization, "Bearer spm_secretsecret_value")80})8182test("erreurs typées : statut, code, message, détails, identifiant de requête", async () => {83  const cases: [number, string, new (...args: any[]) => SPMailError][] = [[400, "invalid_request", BadRequestError], [401, "key_revoked", AuthenticationError], [403, "insufficient_scope", PermissionDeniedError],84    [404, "not_found", NotFoundError], [409, "idempotency_conflict", ConflictError], [429, "daily_send_limit_exceeded", RateLimitError], [500, "internal", ServerError]]85  for (const [status, code, cls] of cases) {86    const e = await sdk(fake([err(status, code)]), { maxRetries: 0 }).messages.get("msg_x").catch((x) => x)87    assert.ok(e instanceof cls && e instanceof SPMailError, `${status} → ${cls.name}`)88    assert.deepEqual([e.status, e.code, e.message, e.details, e.requestId], [status, code, `msg ${code}`, { n: 1 }, "req_test"])89  }90  // enveloppe héritée {error, message} et réponse non JSON91  const legacy = await sdk(fake([json(403, { error: "reauth_required", message: "again" })])).me().catch((x) => x)92  assert.deepEqual([legacy.code, legacy.message], ["reauth_required", "again"])93  const html = await sdk(fake([new Response("<html>", { status: 502 })]), { maxRetries: 0 }).me().catch((x) => x)94  assert.ok(html instanceof ServerError && html.code === "http_error")95})9697test("reprises sûres : 429 + Retry-After, 502/503/504 et pannes réseau ; jamais pour un POST sans clé d'idempotence", async () => {98  // 429 : attend Retry-After puis réussit99  let f = fake([err(429, "rate_limited", { "retry-after": "1" }), json(200, { ok: true })])100  let t0 = Date.now()101  await sdk(f).me()102  assert.equal(f.calls.length, 2)103  assert.ok(Date.now() - t0 >= 1000, "Retry-After respecté")104  // 429 au-delà du délai acceptable : levé tel quel, avec retryAfterSec105  f = fake([err(429, "rate_limited", { "retry-after": "3600" })])106  const rl = await sdk(f).me().catch((x) => x)107  assert.ok(rl instanceof RateLimitError && rl.retryAfterSec === 3600 && f.calls.length === 1)108  // plafond quotidien : jamais réessayé109  f = fake([err(429, "daily_send_limit_exceeded", { "retry-after": "1" })])110  await assert.rejects(sdk(f).messages.send({ from: "a@x", to: ["b@x"], text: "x" }), RateLimitError)111  assert.equal(f.calls.length, 1)112  // GET : 503 puis panne réseau puis succès (recul exponentiel)113  f = fake([err(503, "mail_server_unavailable"), new TypeError("fetch failed"), json(200, { data: [], next_cursor: null, has_more: false })])114  t0 = Date.now()115  await sdk(f, { maxRetries: 2 }).messages.list()116  assert.equal(f.calls.length, 3)117  assert.ok(Date.now() - t0 >= 250, "recul entre les essais")118  // maxRetries épuisé119  f = fake([err(502, "mail_server_error"), err(502, "mail_server_error")])120  await assert.rejects(sdk(f, { maxRetries: 1 }).me(), ServerError)121  assert.equal(f.calls.length, 2)122  // POST créateur : même Idempotency-Key à chaque essai123  f = fake([new TypeError("socket hang up"), err(504, "x"), json(200, { id: "msg_out_1", status: "sent" })])124  await sdk(f).messages.send({ from: "a@x", to: ["b@x"], text: "x" })125  const keys = f.calls.map((c) => c.headers["idempotency-key"])126  assert.equal(keys.length, 3)127  assert.match(keys[0], /^sdk-[0-9a-f-]{36}$/)128  assert.ok(keys.every((k) => k === keys[0]), "une seule clé pour tous les essais d'un même appel")129  // deux appels distincts : deux clés ; clé fournie : respectée130  f = fake([json(200, {}), json(200, {}), json(200, {})])131  const s = sdk(f)132  await s.messages.send({ from: "a@x", to: ["b@x"], text: "x" })133  await s.messages.send({ from: "a@x", to: ["b@x"], text: "x" })134  await s.messages.send({ from: "a@x", to: ["b@x"], text: "x" }, { idempotencyKey: "commande-42" })135  assert.notEqual(f.calls[0].headers["idempotency-key"], f.calls[1].headers["idempotency-key"])136  assert.equal(f.calls[2].headers["idempotency-key"], "commande-42")137  assert.throws(() => { void s.messages.send({ from: "a@x", to: ["b@x"], text: "x" }, { idempotencyKey: "é\n" }).catch(() => {}); throw new TypeError("sync") }, TypeError)138  await assert.rejects(s.messages.send({ from: "a@x", to: ["b@x"], text: "x" }, { idempotencyKey: "é\n" }), TypeError)139  // POST non idempotent (téléversement, PATCH d'un brouillon) : aucune reprise sur 503 ni sur panne réseau140  f = fake([err(503, "mail_server_unavailable")])141  await assert.rejects(sdk(f).files.upload({ data: "x", filename: "a.txt" }), ServerError)142  assert.equal(f.calls.length, 1)143  assert.equal(f.calls[0].headers["idempotency-key"], undefined)144  f = fake([new TypeError("fetch failed")])145  await assert.rejects(sdk(f).drafts.update("msg_x", { subject: "x" }), ConnectionError)146  assert.equal(f.calls.length, 1)147  // idempotency_in_progress : réessayé avec la même clé148  f = fake([err(409, "idempotency_in_progress"), json(200, { id: "msg_out_1" })])149  await sdk(f).messages.send({ from: "a@x", to: ["b@x"], text: "x" })150  assert.equal(f.calls.length, 2)151})152153test("délai d'attente et annulation", async () => {154  const hang = (call: Call) => new Promise<Response>(() => { void call })155  const slow = (_url: string, init?: RequestInit) => new Promise<Response>((_, reject) => init!.signal!.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError"))))156  void hang157  const t = await new SPMail({ apiKey: "spm_x", baseUrl: "http://localhost:1", fetch: slow, timeoutMs: 80, maxRetries: 0 }).me().catch((x) => x)158  assert.ok(t instanceof TimeoutError && t.code === "timeout")159  const ctl = new AbortController()160  setTimeout(() => ctl.abort(), 30)161  const ab = await new SPMail({ apiKey: "spm_x", baseUrl: "http://localhost:1", fetch: slow }).me({ signal: ctl.signal }).catch((x) => x)162  assert.ok(ab instanceof ConnectionError && ab.code === "aborted")163})164165test("pagination : l'itérateur suit next_cursor et encode les filtres", async () => {166  const page = (ids: string[], next: string | null) => json(200, { data: ids.map((id) => ({ id })), next_cursor: next, has_more: next !== null })167  const f = fake([page(["1", "2"], "c1"), page([], "c2"), page(["3"], null)])168  const seen: string[] = []169  for await (const m of sdk(f).messages.iterate({ folder: "inbox", unread: true, address: ["a@x", "b@x"], limit: 2 })) seen.push(m.id)170  assert.deepEqual(seen, ["1", "2", "3"])171  assert.equal(f.calls[0].url, "http://localhost:1/api/v1/messages?folder=inbox&unread=true&address=a%40x%2Cb%40x&limit=2")172  assert.match(f.calls[1].url, /cursor=c1$/)173  assert.match(f.calls[2].url, /cursor=c2$/)174})175176test("signature des webhooks (WebCrypto) : valide, altérée, hors fenêtre, mal formée", async () => {177  const secret = "whsec_test_secret"178  const payload = JSON.stringify({ id: "evt_1", type: "message.received", occurred_at: "2026-11-19T06:04:19.412Z", address: "a@x", mailbox: "a@x", data: { message_id: "msg_1" } })179  const header = await signWebhookPayload({ payload, secret })180  // même valeur que l'algorithme de référence de docs/API.md (node:crypto)181  const crypto = await import("node:crypto")182  const ts = header.match(/^t=(\d+)/)![1]183  assert.equal(header, `t=${ts},v1=${crypto.createHmac("sha256", secret).update(`${ts}.${payload}`).digest("hex")}`)184  assert.equal(await verifyWebhookSignature({ payload, header, secret }), true)185  assert.equal(await verifyWebhookSignature({ payload: new TextEncoder().encode(payload), header, secret }), true)186  assert.equal(await verifyWebhookSignature({ payload: `${payload} `, header, secret }), false)187  assert.equal(await verifyWebhookSignature({ payload, header, secret: "whsec_other" }), false)188  assert.equal(await verifyWebhookSignature({ payload, header: null, secret }), false)189  assert.equal(await verifyWebhookSignature({ payload, header: "v1=abc", secret }), false)190  const old = await signWebhookPayload({ payload, secret, timestamp: Date.now() / 1000 - 301 })191  assert.equal(await verifyWebhookSignature({ payload, header: old, secret }), false)192  assert.equal(await verifyWebhookSignature({ payload, header: old, secret, toleranceSec: 600 }), true)193  const ev = await constructWebhookEvent({ payload, header, secret })194  assert.equal(ev.type, "message.received")195  await assert.rejects(constructWebhookEvent({ payload, header: old, secret }), SignatureVerificationError)196})197198// ================================================================== contre le vrai serveur199test("me, health, adresses, dossiers", async () => {200  const me = await a.me()201  assert.equal(me.type, "key")202  assert.deepEqual(me.addresses.map((x) => [x.address, x.read]), [[A.address, "full"]])203  assert.equal(me.limits.external_send_policy, "allow")204  const h = await a.health()205  assert.deepEqual([h.ok, h.database, h.mail_server], [true, "ok", "reachable"])206  const list = await a.addresses.list()207  assert.deepEqual(list.map((x) => x.address), [A.address])208  assert.equal((await a.addresses.get(A.address)).id, A.addressId)209  const folders = await a.folders.list()210  assert.ok(folders.some((f) => f.role === "inbox"))211  const made = await a.folders.create({ address: A.address, name: "Factures SDK" })212  assert.match(made.id, /^fld_/)213})214215test("erreurs réelles : 401, 403 (portée manquante), 404, 400", async () => {216  const bad = await new SPMail({ apiKey: "spm_aaaaaaaaaa_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", baseUrl: ORIGIN }).me().catch((x) => x)217  assert.ok(bad instanceof AuthenticationError && bad.code === "invalid_api_key")218  assert.match(bad.requestId ?? "", /^req_/)219  const ro = new SPMail({ apiKey: (await mkKey(admin, { scopes: ["mail.read"], addresses: [A.addressId] })).token, baseUrl: ORIGIN })220  const denied = await ro.messages.send({ from: A.address, to: [B.address], subject: "x", text: "x" }).catch((x) => x)221  assert.ok(denied instanceof PermissionDeniedError && denied.code === "insufficient_scope")222  assert.ok(JSON.stringify(denied.details).includes("mail.send"))223  const nf = await a.messages.get("msg_inconnu").catch((x) => x)224  assert.ok(nf instanceof NotFoundError && nf.code === "not_found")225  const inv = await a.messages.send({ from: A.address, to: [B.address], subject: "x", text: "x", headers: { From: "evil@example.org" } }).catch((x) => x)226  assert.ok(inv instanceof BadRequestError && inv.code === "header_not_allowed")227  const foreign = await a.messages.send({ from: B.address, to: [A.address], subject: "x", text: "x" }).catch((x) => x)228  assert.ok(foreign instanceof PermissionDeniedError && foreign.code === "from_not_allowed")229})230231let first: MessageSummary232test("téléversement, envoi groupé avec pièce jointe, waitForDelivery, lecture paginée, pièces jointes", async () => {233  const file = await a.files.upload({ data: new TextEncoder().encode("col1,col2\n1,2\n"), filename: "données.csv", contentType: "text/csv" })234  assert.match(file.id, /^file_/)235  assert.equal(file.size, 14)236  const batch = await a.messages.sendBatch([237    { from: A.address, to: [B.address], subject: "SDK TS un", text: "Premier message", attachments: [{ file_id: file.id }] },238    { from: A.address, to: [{ email: B.address, name: "Boîte B" }], subject: "SDK TS deux", html: "<p>Deuxième <b>message</b><script>alert(1)</script></p>" },239    { from: B.address, to: [A.address], subject: "refusé", text: "x" },240  ])241  assert.deepEqual(batch.results.map((r) => r.ok), [true, true, false])242  const done = await a.waitForDelivery(batch.results[0].message!.id, { timeoutMs: 40_000 })243  assert.equal(done.status, "delivered")244  assert.deepEqual(done.recipients.map((r) => [r.address, r.status]), [[B.address, "delivered"]])245  await a.messages.waitForDelivery(batch.results[1].message!.id, { timeoutMs: 40_000 })246247  const inbox = await until(async () => { const p = await b.messages.list({ folder: "inbox", limit: 50 }); return p.data.length >= 2 ? p.data : null }, "réception des deux messages")248  assert.deepEqual(inbox.map((m) => m.subject).sort(), ["SDK TS deux", "SDK TS un"])249  // itérateur sur des pages d'un élément : tout est parcouru, sans doublon250  const walked: string[] = []251  for await (const m of b.messages.iterate({ folder: "inbox", limit: 1 })) walked.push(m.id)252  assert.deepEqual(walked.sort(), inbox.map((m) => m.id).sort())253  const page1 = await b.messages.list({ folder: "inbox", limit: 1 })254  assert.ok(page1.has_more && page1.next_cursor)255  // recherche et filtres booléens256  const found = await b.messages.list({ subject: "SDK TS un", unread: true, has_attachment: true })257  assert.equal(found.data.length, 1)258  first = found.data[0]259  const full = await b.messages.get(first.id)260  assert.equal(full.text?.trim(), "Premier message")261  assert.equal(full.from[0].email, A.address)262  const two = await b.messages.get(inbox.find((m) => m.subject === "SDK TS deux")!.id)263  assert.ok(two.html && !two.html.includes("<script"))264  const atts = await b.messages.attachments.list(first.id)265  assert.deepEqual(atts.map((x) => [x.name, x.size]), [["données.csv", 14]])266  const dl = await b.messages.attachments.download(first.id, atts[0].id)267  assert.equal(new TextDecoder().decode(dl.data), "col1,col2\n1,2\n")268  assert.equal(dl.filename, "données.csv")269  // fils et synchronisation270  const thread = await b.threads.get(first.thread_id)271  assert.deepEqual(thread.messages.map((m) => m.id), [first.id])272  assert.ok((await b.threads.list({ folder: "inbox" })).data.some((t) => t.id === first.thread_id))273  const state = await b.messages.changes()274  assert.match(state.state, /^st_/)275  assert.deepEqual((await b.messages.changes({ since: state.state })).created, [])276  // suivi des envois277  const out = await a.messages.outbound.list({ status: "delivered" })278  assert.ok(out.data.length >= 2 && out.data.every((o) => o.status === "delivered"))279  const outs: string[] = []280  for await (const o of a.messages.outbound.iterate({ limit: 1 })) outs.push(o.id)281  assert.ok(outs.length >= 2 && new Set(outs).size === outs.length)282})283284test("modifier, déplacer, répondre, transférer, supprimer", async () => {285  assert.equal((await b.messages.markRead(first.id)).unread, false)286  const up = await b.messages.update(first.id, { starred: true, add_labels: ["sdk-ts"] })287  assert.deepEqual([up.starred, up.labels], [true, ["sdk-ts"]])288  assert.equal((await b.messages.list({ label: "sdk-ts" })).data.length, 1)289  const moved = await b.messages.archive(first.id)290  assert.deepEqual(moved.folders.map((f) => f.role), ["archive"])291  await b.messages.move(first.id, "inbox")292293  const reply = await b.messages.reply(first.id, { text: "Bien reçu (SDK TS)" })294  assert.deepEqual(reply.recipients.map((r) => r.address), [A.address])295  assert.equal((await b.waitForDelivery(reply.id, { timeoutMs: 40_000 })).status, "delivered")296  const got = await until(async () => (await a.messages.list({ folder: "inbox", subject: "Re: SDK TS un" })).data[0], "réception de la réponse")297  assert.equal((await a.messages.get(got.id)).text?.trim(), "Bien reçu (SDK TS)")298299  const fwd = await b.messages.forward(first.id, { to: [C.address], text: "Pour info" })300  assert.equal((await b.waitForDelivery(fwd.id, { timeoutMs: 40_000 })).status, "delivered")301  const atC = await until(async () => (await c.messages.list({ folder: "inbox" })).data[0], "réception du transfert")302  assert.match(atC.subject, /SDK TS un/)303  assert.equal(atC.has_attachment, true)304305  assert.deepEqual(await c.messages.delete(atC.id), { ok: true, permanent: false })306  assert.deepEqual(await c.messages.delete(atC.id, { permanent: true }), { ok: true, permanent: true })307  await assert.rejects(c.messages.get(atC.id), NotFoundError)308})309310test("brouillons, programmation et annulation, idempotence réelle", async () => {311  const d = await a.drafts.create({ from: A.address, to: [C.address], subject: "Brouillon SDK", text: "v1" })312  assert.equal(d.status, "draft")313  assert.ok((await a.drafts.list()).data.some((m) => m.id === d.id))314  const d2 = await a.drafts.update(d.id, { text: "v2" })315  assert.notEqual(d2.id, d.id)316  assert.equal((await a.drafts.get(d2.id)).text?.trim(), "v2")317  const sent = await a.drafts.send(d2.id)318  assert.equal((await a.waitForDelivery(sent.id, { timeoutMs: 40_000 })).status, "delivered")319  const d3 = await a.drafts.create({ from: A.address, subject: "à jeter" })320  assert.deepEqual(await a.drafts.delete(d3.id), { ok: true })321322  // programmé : rien ne part ; waitForDelivery expire en rapportant le dernier état ; annulation323  const later = await a.messages.send({ from: A.address, to: [C.address], subject: "Plus tard", text: "x", send_at: new Date(Date.now() + 3600_000).toISOString() })324  assert.equal(later.status, "scheduled")325  assert.ok((await a.messages.scheduled.list()).data.some((o) => o.id === later.id))326  const waited = await a.waitForDelivery(later.id, { timeoutMs: 1200, intervalMs: 300 }).catch((x) => x)327  assert.ok(waited instanceof TimeoutError && (waited.details as any).last.status === "scheduled")328  assert.equal((await a.messages.scheduled.cancel(later.id)).status, "cancelled")329  const again = await a.messages.scheduled.cancel(later.id).catch((x) => x)330  assert.ok(again instanceof ConflictError && again.code === "not_cancellable")331332  // idempotence : la même clé rejoue la réponse (un seul envoi) ; un autre corps → 409333  const body = { from: A.address, to: [C.address], subject: "Idempotent SDK", text: "une seule fois" }334  const one = await a.messages.send(body, { idempotencyKey: "sdk-ts-idem-1" })335  const two = await a.messages.send(body, { idempotencyKey: "sdk-ts-idem-1" })336  assert.equal(two.id, one.id)337  const conflict = await a.messages.send({ ...body, text: "autre" }, { idempotencyKey: "sdk-ts-idem-1" }).catch((x) => x)338  assert.ok(conflict instanceof ConflictError && conflict.code === "idempotency_conflict")339  await a.waitForDelivery(one.id, { timeoutMs: 40_000 })340  const atC = await until(async () => { const p = await c.messages.list({ subject: "Idempotent SDK" }); return p.data.length ? p.data : null }, "réception")341  assert.equal(atC.length, 1)342})343344test("destinataire externe + politique approval : pending_approval, rien n'est remis", async () => {345  const careful = new SPMail({ apiKey: (await mkKey(admin, { scopes: ["mail.send"], addresses: [A.addressId], external: "approval" })).token, baseUrl: ORIGIN })346  const r = await careful.messages.send({ from: A.address, to: [EXTERNAL_ADDR], subject: "Externe SDK", text: "en attente" })347  assert.equal(r.status, "pending_approval")348  assert.ok(r.approval_id)349  const w = await careful.waitForDelivery(r.id, { timeoutMs: 1000, intervalMs: 300 }).catch((x) => x)350  assert.ok(w instanceof TimeoutError && (w.details as any).last.status === "pending_approval")351  const denying = new SPMail({ apiKey: (await mkKey(admin, { scopes: ["mail.send"], addresses: [A.addressId], external: "deny" })).token, baseUrl: ORIGIN })352  const e = await denying.messages.send({ from: A.address, to: [EXTERNAL_ADDR], subject: "x", text: "x" }).catch((x) => x)353  assert.ok(e instanceof PermissionDeniedError && e.code === "external_send_denied")354})355356test("alias : créer, puis modifier et supprimer une fois l'alias ajouté à la clé par un administrateur", async () => {357  const name = A.address.replace("api-sa-", "api-sal-")358  const al = await a.aliases.create({ address: name, mailbox: A.address, display_name: "Alias SDK" })359  assert.deepEqual([al.kind, al.inbound, al.mailbox], ["alias", "accept", A.address])360  // comportement réel : une adresse créée n'entre dans la liste d'aucune clé ; tant qu'un administrateur ne l'y ajoute pas,361  // la clé qui vient de la créer ne la voit pas (liste) et ne peut ni la modifier ni la supprimer (404)362  assert.ok(!(await a.aliases.list()).some((x) => x.address === name))363  await assert.rejects(a.aliases.update(name, { status: "suspended" }), NotFoundError)364  await assert.rejects(a.aliases.delete(al.id), NotFoundError)365  await reauth(admin)366  await admin.call("PATCH", `/api/admin/api-keys/${keyAId}`, { address_ids: [A.addressId, al.id] })367  assert.ok((await a.aliases.list()).some((x) => x.address === name))368  assert.equal((await a.aliases.update(name, { status: "suspended" })).inbound, "reject")369  assert.equal((await a.aliases.delete(al.id)).ok, true)370})371372test("webhooks : création, essai signé vérifié par le SDK, livraisons, rejeu, événements", async () => {373  const rx = await new Receiver().start()374  await reauth(admin)375  await admin.call("POST", "/api/admin/webhook-allowlist", { host_port: `127.0.0.1:${rx.port}`, note: "sdk-ts" })376  const hook = await a.webhooks.create({ name: "sdk-ts", url: rx.url, events: ["message.sent", "message.delivered", "message.received"] })377  assert.match(hook.secret ?? "", /^whsec_/)378  assert.equal((await a.webhooks.get(hook.id)).secret, undefined)379  assert.ok((await a.webhooks.list()).some((w) => w.id === hook.id))380  const t = await a.webhooks.test(hook.id)381  assert.equal(t.http_status, 200)382  const hit = await until(async () => rx.of("webhook.test")[0], "réception de webhook.test")383  const params = { payload: hit.body, header: hit.headers["spmail-signature"] as string, secret: hook.secret! }384  assert.equal(await a.webhooks.verifySignature(params), true)385  assert.equal(await a.webhooks.verifySignature({ ...params, secret: "whsec_wrong" }), false)386  const ev = await a.webhooks.constructEvent(params)387  assert.equal(ev.type, "webhook.test")388  assert.equal(ev.id, hit.headers["spmail-event-id"])389  const deliveries = await a.webhooks.deliveries.list(hook.id)390  assert.equal(deliveries.data[0].status, "delivered")391  const replayed = await a.webhooks.replay(deliveries.data[0].id)392  assert.equal(replayed.event_id, deliveries.data[0].event_id)393  await until(async () => rx.of("webhook.test").length >= 2, "rejeu reçu")394  const rotated = await a.webhooks.update(hook.id, { rotate_secret: true, active: false })395  assert.ok(rotated.secret && rotated.secret !== hook.secret && rotated.active === false)396  const events = await a.events.list({ type: "message.sent", limit: 5 })397  assert.ok(events.data.length >= 1 && events.data.every((e) => e.type === "message.sent"))398  const some: string[] = []399  for await (const e of a.events.iterate({ limit: 2 })) { some.push(e.id); if (some.length >= 5) break }400  assert.ok(some.length >= 3)401  assert.deepEqual(await a.webhooks.delete(hook.id), { ok: true })402  await rx.stop()403})404405test("modèles : liste, lecture, rendu, envoi par modèle", async () => {406  const HTML = `<!DOCTYPE html><html><head><meta charset="utf-8"></head><body><p>Bonjour {{first_name}}, votre code est <b>{{code}}</b>.</p></body></html>`407  const tpl = (await admin.call("POST", "/api/templates", { name: "Code SDK", subject: "Votre code, {{first_name}}", html: HTML, text: "Bonjour {{first_name}}, code {{code}}",408    variables: [{ name: "first_name", example: "Zoé", required: true }, { name: "code", example: "000000", required: true }] })).id as string409  const list = await a.templates.list()410  assert.deepEqual(list.map((t) => t.id), [tpl])411  assert.ok((await a.templates.get(tpl)).html.includes("{{code}}"))412  const r = await a.templates.render(tpl, { variables: { first_name: "Max", code: "123456" } })413  assert.deepEqual([r.subject, r.missing], ["Votre code, Max", []])414  assert.deepEqual((await a.templates.render(tpl, {})).missing.sort(), ["code", "first_name"])415  const missing = await a.messages.send({ from: A.address, to: [B.address], template_id: tpl, variables: { first_name: "Max" } }).catch((x) => x)416  assert.ok(missing instanceof BadRequestError && missing.code === "missing_variables")417  const sent = await a.messages.send({ from: A.address, to: [B.address], template_id: tpl, variables: { first_name: "Max", code: "424242" } })418  assert.equal((await a.waitForDelivery(sent.id, { timeoutMs: 40_000 })).status, "delivered")419  const got = await until(async () => (await b.messages.list({ subject: "Votre code, Max" })).data[0], "réception du modèle")420  assert.match((await b.messages.get(got.id)).text ?? "", /424242/)421})422423test("la clé ne fuit pas dans les erreurs réelles", async () => {424  const e = await a.messages.get("msg_nope").catch((x) => x)425  const { inspect } = await import("node:util")426  assert.ok(!inspect(e, { depth: 10 }).includes(tokenA.slice(15)))427})428
Files main
Menu

Theme