Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr SMS Gateway8 * File : sdk/typescript/tests/client.test.mjs9 * Module : sdk10 * Repository : https://git.spboucher.ai/maclustr-sms11 * Project Website : https://sms.spboucher.ai12 * Created : 2026-11-3013 * Last Modified : 2026-11-3014 *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: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Tests unitaires (fetch simulé) et, si MACLUSTR_SMS_E2E=1, scénario de bout en bout contre un vrai backend (téléphone SIMULÉ).43import assert from "node:assert/strict"44import crypto from "node:crypto"45import { test } from "node:test"46import { MacLustrSMS, MacLustrSMSError, MacLustrSMSTimeout, verifyWebhook, WebhookVerificationError } from "../dist/index.js"4748const MSG = { id: "sms_1", direction: "outbound", status: "queued", to: "+14185550123", from: "+14185550124", text: "x", segments: 1 }49function stub(script) {50 const seen = [], slept = []51 const f = async (url, init) => {52 seen.push({ url, method: init.method, headers: init.headers, body: init.body ? JSON.parse(init.body) : undefined })53 const r = script.shift()54 if (r instanceof Error) throw r55 const [status, body, headers] = r ?? [200, {}, {}]56 return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...(headers ?? {}) } })57 }58 const sms = new MacLustrSMS({ apiKey: "mlsk_test", baseUrl: "http://stub/", fetch: f, sleep: async ms => void slept.push(ms) })59 return { sms, seen, slept }60}6162test("send : corps, en-têtes, clé d'idempotence générée", async () => {63 const { sms, seen } = stub([[201, MSG]])64 const m = await sms.send({ to: "+14185550123", text: "x", simId: "sim-1", from: "+14185550124", ttlSeconds: 120 })65 assert.equal(m.id, "sms_1"); assert.equal(m.replayed, false)66 assert.equal(seen[0].url, "http://stub/v1/messages")67 assert.deepEqual(seen[0].body, { to: "+14185550123", text: "x", sim_id: "sim-1", from: "+14185550124", ttl_seconds: 120 })68 assert.equal(seen[0].headers.authorization, "Bearer mlsk_test")69 assert.match(seen[0].headers["idempotency-key"], /^[0-9a-f-]{36}$/)70})71test("réessais (réseau, 5xx, 429) avec la même Idempotency-Key ; Retry-After respecté", async () => {72 const { sms, seen, slept } = stub([new TypeError("fetch failed"), [503, { error: { code: "kill_switch_active", message: "x" } }], [429, { error: { code: "rate_limited", message: "x" } }, { "retry-after": "7" }], [200, MSG, { "idempotent-replayed": "true" }]])73 const m = await sms.send({ to: "+14185550123", text: "x" })74 assert.equal(m.replayed, true); assert.equal(seen.length, 4)75 assert.equal(new Set(seen.map(s => s.headers["idempotency-key"])).size, 1)76 assert.deepEqual(slept, [500, 1000, 7000])77})78test("pas de réessai sur une erreur 4xx ; erreur typée", async () => {79 const { sms, seen } = stub([[422, { error: { code: "invalid_phone_number", message: "numéro invalide", details: [1] } }]])80 await assert.rejects(sms.send({ to: "123", text: "x" }), e => e instanceof MacLustrSMSError && e.status === 422 && e.code === "invalid_phone_number" && e.apiMessage === "numéro invalide" && e.details[0] === 1)81 assert.equal(seen.length, 1)82})83test("abandon après maxRetries ; erreur réseau typée", async () => {84 const a = stub([[500, {}], [500, {}], [500, {}], [500, {}]])85 await assert.rejects(a.sms.getMessage("sms_1"), e => e.status === 500)86 assert.equal(a.seen.length, 4)87 const b = stub([new TypeError("x"), new TypeError("x"), new TypeError("x"), new TypeError("x")])88 await assert.rejects(b.sms.health(), e => e.status === 0 && e.code === "network_error")89})90test("itérateur paginé et filtres", async () => {91 const { sms, seen } = stub([[200, { data: [{ ...MSG, id: "a" }, { ...MSG, id: "b" }], has_more: true, next_cursor: "c1" }], [200, { data: [{ ...MSG, id: "c" }], has_more: false, next_cursor: null }]])92 const ids = []93 for await (const m of sms.iterMessages({ limit: 2, status: "queued", simId: "sim-1" })) ids.push(m.id)94 assert.deepEqual(ids, ["a", "b", "c"])95 assert.equal(seen[1].url, "http://stub/v1/messages?status=queued&sim_id=sim-1&limit=2&cursor=c1")96})97test("wait : submitted, final, délai dépassé", async () => {98 let s = stub([[200, { ...MSG, status: "dispatched" }], [200, { ...MSG, status: "submitted" }]])99 assert.equal((await s.sms.wait("sms_1")).status, "submitted")100 s = stub([[200, { ...MSG, status: "submitted" }], [200, { ...MSG, status: "delivered" }]])101 assert.equal((await s.sms.wait("sms_1", { until: "final" })).status, "delivered")102 s = stub([[200, MSG]])103 await assert.rejects(s.sms.wait("sms_1", { timeoutMs: 500 }), e => e instanceof MacLustrSMSTimeout && e.lastMessage.status === "queued")104})105test("health sans en-tête d'autorisation ; clé obligatoire", async () => {106 const { sms, seen } = stub([[200, { status: "ok" }]])107 await sms.health()108 assert.equal(seen[0].headers.authorization, undefined)109 const old = process.env.MACLUSTR_SMS_API_KEY; delete process.env.MACLUSTR_SMS_API_KEY110 assert.throws(() => new MacLustrSMS())111 if (old) process.env.MACLUSTR_SMS_API_KEY = old112})113test("vérification par code : jamais réessayée à l'envoi ni au contrôle ; retryAfter exposé", async () => {114 const ver = { id: "ver_1", to: "+14185550123", status: "pending", attempts: 0, attempts_remaining: 5, message_id: "sms_1", message_status: "queued" }115 let s = stub([[201, ver]])116 const v = await s.sms.startVerification({ to: "+14185550123", brand: "Lou-Ka", locale: "fr", ttlSeconds: 300 })117 assert.equal(v.id, "ver_1"); assert.equal(v.attempts_remaining, 5)118 assert.deepEqual(s.seen[0].body, { to: "+14185550123", brand: "Lou-Ka", locale: "fr", ttl_seconds: 300 })119 assert.equal(s.seen[0].headers["idempotency-key"], undefined)120 for (const first of [[503, {}], new TypeError("fetch failed")]) {121 s = stub([first, [201, ver]])122 await assert.rejects(s.sms.startVerification({ to: "+14185550123" }))123 assert.equal(s.seen.length, 1)124 }125 s = stub([[429, { error: { code: "verification_too_soon", message: "x" } }, { "retry-after": "27" }], [201, ver]])126 await assert.rejects(s.sms.startVerification({ to: "+14185550123" }), e => e.status === 429 && e.code === "verification_too_soon" && e.retryAfter === 27)127 assert.equal(s.seen.length, 1)128 s = stub([[500, {}], [200, { ...ver, valid: true }]])129 await assert.rejects(s.sms.checkVerification("ver_1", "123456")); assert.equal(s.seen.length, 1)130 s = stub([[200, { ...ver, status: "approved", valid: true }]])131 assert.equal((await s.sms.checkVerification("ver_1", 123456)).valid, true)132 assert.equal(s.seen[0].url, "http://stub/v1/verifications/ver_1/check"); assert.deepEqual(s.seen[0].body, { code: "123456" })133 s = stub([[500, {}], [200, ver]])134 assert.equal((await s.sms.getVerification("ver_1")).status, "pending"); assert.equal(s.seen.length, 2)135})136test("verifyWebhook", async () => {137 const body = '{"event":"sms.received","id":"evt_1","data":{"text":"é"}}', secret = "whsec_x"138 const sign = (ts, b = body) => "v1=" + crypto.createHmac("sha256", secret).update(`${ts}.${b}`).digest("hex")139 const ts = Math.floor(Date.now() / 1000)140 assert.equal((await verifyWebhook({ secret, timestamp: String(ts), body, signature: sign(ts) })).event, "sms.received")141 assert.equal((await verifyWebhook({ secret, timestamp: ts, body: new TextEncoder().encode(body), signature: sign(ts) })).id, "evt_1")142 for (const p of [{ secret: "autre" }, { body: body + " " }, { signature: "v1=00" }, { signature: null }, { timestamp: "abc" }, { timestamp: null }])143 await assert.rejects(verifyWebhook({ secret, timestamp: ts, body, signature: sign(ts), ...p }), WebhookVerificationError)144 const old = ts - 301145 await assert.rejects(verifyWebhook({ secret, timestamp: old, body, signature: sign(old) }), /tolérance/)146 assert.equal((await verifyWebhook({ secret, timestamp: old, body, signature: sign(old), toleranceSeconds: 600 })).id, "evt_1")147})148149test("bout en bout contre un vrai backend (téléphone simulé)", { skip: process.env.MACLUSTR_SMS_E2E !== "1" && "lancer sdk/tests-e2e/run.mjs" }, async () => {150 const sms = new MacLustrSMS(), control = process.env.E2E_CONTROL, to = process.env.E2E_TO151 const sleep = ms => new Promise(r => setTimeout(r, ms))152 assert.equal((await sms.health()).status, "ok")153 const hook = await sms.createWebhook({ url: control + "/hook", events: ["sms.delivered", "sms.received"], description: "ts-e2e" })154 assert.match(hook.secret, /^whsec_/)155 try {156 const m = await sms.send({ to, text: "Notification MacLustr (typescript)", idempotencyKey: "ts-e2e-1" })157 const again = await sms.send({ to, text: "Notification MacLustr (typescript)", idempotencyKey: "ts-e2e-1" })158 assert.equal(again.id, m.id); assert.equal(again.replayed, true)159 const done = await sms.wait(m.id, { timeoutMs: 20_000, until: "final", intervalMs: 200 })160 assert.equal(done.status, "delivered")161 await assert.rejects(sms.send({ to: "12345", text: "x" }), e => e.status === 422 && e.code === "invalid_phone_number")162 await assert.rejects(sms.send({ to: "+15145550111", text: "x" }), e => e.status === 403 && e.code === "recipient_not_allowed")163 await assert.rejects(sms.cancel(m.id), e => e.code === "not_cancellable")164 for (let i = 0; i < 2; i++) await sms.send({ to, text: `page ${i} (typescript)` })165 const page = await sms.listMessages({ limit: 2 })166 assert.equal(page.data.length, 2); assert.equal(page.has_more, true)167 const ids = []168 for await (const x of sms.iterMessages({ limit: 2 })) ids.push(x.id)169 assert.ok(ids.length >= 3 && new Set(ids).size === ids.length && ids.includes(m.id))170171 const text = `Réponse typescript ${Date.now()}`172 await fetch(control + "/receive", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ from: to, text }) })173 let got174 for (let i = 0; i < 50 && !got; i++) { got = (await sms.inbox({ from: to, limit: 20 })).data.find(x => x.text === text); if (!got) await sleep(100) }175 assert.ok(got); assert.equal(got.status, "received"); assert.equal(got.from, to)176 const conv = (await sms.conversations()).data.find(c => c.peer === to)177 assert.ok((await sms.conversationMessages(conv.id)).data.some(x => x.id === got.id))178179 // Vérification par code : le code n'est lisible que dans le SMS (ici : celui reçu par l'appareil simulé).180 const vto = process.env.E2E_VERIFY_TO181 const v = await sms.startVerification({ to: vto, brand: "Tests SDK", locale: "en" })182 assert.equal(v.status, "pending"); assert.equal(v.attempts_remaining, 5)183 await assert.rejects(sms.startVerification({ to: vto }), e => e.status === 429 && e.code === "verification_too_soon" && e.retryAfter > 0 && e.retryAfter <= 30)184 const { code } = await (await fetch(control + "/code?to=" + encodeURIComponent(vto))).json()185 const bad = await sms.checkVerification(v.id, String((Number(code) + 1) % 1000000).padStart(6, "0"))186 assert.equal(bad.valid, false); assert.equal(bad.attempts_remaining, 4)187 const good = await sms.checkVerification(v.id, code)188 assert.equal(good.valid, true); assert.equal(good.status, "approved")189 assert.equal((await sms.checkVerification(v.id, code)).valid, false)190 assert.equal((await sms.getVerification(v.id)).status, "approved")191 await assert.rejects(sms.getVerification("ver_inconnu"), e => e.status === 404)192193 const [dev] = await sms.devices()194 assert.ok(dev.online && dev.sims[0].send_enabled)195 assert.equal((await sms.device(dev.id)).id, dev.id)196 assert.equal((await sms.sims(dev.id))[0].id, dev.sims[0].id)197 assert.equal((await sms.numbers())[0].sim_id, dev.sims[0].id)198 assert.ok((await sms.usage()).quota.used_today >= 3)199 assert.ok("pending" in (await sms.queue()))200201 let mine = []202 for (let i = 0; i < 80; i++) {203 mine = []204 for (const h of await (await fetch(control + "/hits")).json())205 try { mine.push(await verifyWebhook({ secret: hook.secret, timestamp: h.headers["x-maclustr-timestamp"], body: h.body, signature: h.headers["x-maclustr-signature"] })) } catch {} // autre secret : webhook d'un autre SDK206 if (mine.some(e => e.event === "sms.delivered") && mine.some(e => e.event === "sms.received" && e.data.text === text)) break207 await sleep(100)208 }209 assert.ok(mine.some(e => e.event === "sms.delivered" && e.data.id === m.id))210 assert.ok(mine.some(e => e.event === "sms.received" && e.data.text === text))211 assert.ok((await sms.listWebhooks()).some(w => w.id === hook.id))212 } finally { assert.equal(await sms.deleteWebhook(hook.id), true) }213})214