Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr SMS Gateway8 * File : cli/tests/cli.test.mjs9 * Module : cli10 * 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 de la CLI : serveur HTTP local pour les cas unitaires ; si MACLUSTR_SMS_E2E=1, scénario contre un vrai backend (téléphone SIMULÉ).43import assert from "node:assert/strict"44import { spawn } from "node:child_process"45import http from "node:http"46import { after, before, test } from "node:test"47import { fileURLToPath } from "node:url"4849const BIN = fileURLToPath(new URL("../maclustr-sms.mjs", import.meta.url))50function run(args, env = {}, input) {51 return new Promise(resolve => {52 const p = spawn(process.execPath, [BIN, ...args], { env: { PATH: process.env.PATH, HOME: process.env.HOME, MACLUSTR_SMS_NO_KEYCHAIN: "1", ...env } })53 let stdout = "", stderr = ""54 p.stdout.on("data", d => (stdout += d)); p.stderr.on("data", d => (stderr += d))55 p.on("close", code => { let json; try { json = JSON.parse(stdout) } catch {} ; resolve({ code, stdout, stderr, json }) })56 p.stdin.end(input ?? "")57 })58}5960const MSG = { id: "sms_1", direction: "outbound", status: "queued", to: "+14185550123", from: "+14185550124", text: "Bonjour", segments: 1, encoding: "gsm7", device_id: "android-01", sim_id: "sim-1", created_at: "2026-11-30T22:00:00.000Z", error: null }61let server, url, seen = [], script = []62before(async () => {63 server = http.createServer((req, res) => {64 let body = ""65 req.on("data", d => (body += d)).on("end", () => {66 seen.push({ method: req.method, url: req.url, headers: req.headers, body: body ? JSON.parse(body) : undefined })67 const [status, json, headers] = script.shift() ?? [200, {}, {}]68 res.writeHead(status, { "content-type": "application/json", ...(headers ?? {}) }).end(JSON.stringify(json))69 })70 })71 await new Promise(r => server.listen(0, "127.0.0.1", r))72 url = `http://127.0.0.1:${server.address().port}`73})74after(() => server.close())75const env = () => ({ MACLUSTR_SMS_URL: url, MACLUSTR_SMS_API_KEY: "mlsk_" + "a".repeat(43) })76const reset = s => { seen = []; script = s }7778test("aide, version, usage", async () => {79 assert.match((await run(["--help"])).stdout, /send --to N --text T/)80 assert.equal((await run(["--version"])).stdout.trim(), "1.0.0")81 const r = await run(["nimporte"], env())82 assert.equal(r.code, 2); assert.match(r.stderr, /commande inconnue/)83 assert.equal((await run(["send", "--to", "+14185550123"], env())).code, 2)84})85test("la clé n'est jamais acceptée en argument ; clé absente = erreur claire", async () => {86 reset([])87 const r = await run(["send", "--to", "+14185550123", "--text", "x", "--key", "mlsk_" + "b".repeat(43)], env())88 assert.equal(r.code, 2); assert.match(r.stderr, /jamais en argument/); assert.equal(seen.length, 0)89 const n = await run(["queue", "--json"], { MACLUSTR_SMS_URL: url })90 assert.equal(n.code, 1); assert.equal(n.json.error.code, "no_api_key")91})92test("send : corps, clé d'idempotence, sortie lisible et JSON", async () => {93 reset([[201, MSG]])94 const r = await run(["send", "--to", "+14185550123", "--text", "Bonjour", "--sim", "sim-1", "--ttl", "120"], env())95 assert.equal(r.code, 0, r.stderr); assert.match(r.stdout, /sms_1\s+QUEUED/)96 assert.deepEqual(seen[0].body, { to: "+14185550123", text: "Bonjour", sim_id: "sim-1", ttl_seconds: 120 })97 assert.match(seen[0].headers["idempotency-key"], /^[0-9a-f-]{36}$/)98 assert.equal(seen[0].headers.authorization, "Bearer mlsk_" + "a".repeat(43))99 reset([[200, MSG, { "idempotent-replayed": "true" }]])100 const j = await run(["send", "--to", "+14185550123", "--text", "Bonjour", "--idempotency-key", "k1", "--json"], env())101 assert.equal(j.json.id, "sms_1"); assert.equal(j.json.replayed, true); assert.equal(seen[0].headers["idempotency-key"], "k1")102})103test("send --wait : codes de sortie selon l'issue", async () => {104 reset([[201, MSG], [200, { ...MSG, status: "submitted" }]])105 assert.equal((await run(["send", "--to", "+14185550123", "--text", "x", "--wait", "5", "--json"], env())).code, 0)106 reset([[201, MSG], [200, { ...MSG, status: "failed", error: { code: "no_service", detail: null } }]])107 const f = await run(["send", "--to", "+14185550123", "--text", "x", "--wait", "--json"], env())108 assert.equal(f.code, 3); assert.equal(f.json.error.code, "no_service")109 reset([[201, MSG], [200, { ...MSG, status: "unknown" }]])110 const u = await run(["send", "--to", "+14185550123", "--text", "x", "--wait", "5"], env())111 assert.equal(u.code, 4); assert.match(u.stdout, /ne pas renvoyer sans vérifier/)112 reset([[201, MSG]])113 const t = await run(["send", "--to", "+14185550123", "--text", "x", "--wait", "0", "--json"], env())114 assert.equal(t.code, 5); assert.equal(t.json.wait_timed_out, true)115})116test("erreur d'API : code de sortie 1, message et JSON normalisés ; pas de réessai sur 4xx", async () => {117 reset([[422, { error: { code: "invalid_phone_number", message: "numéro de destinataire invalide" } }]])118 const r = await run(["send", "--to", "123", "--text", "x"], env())119 assert.equal(r.code, 1); assert.match(r.stderr, /invalid_phone_number/); assert.equal(seen.length, 1)120 reset([[403, { error: { code: "insufficient_scope", message: "scope" } }]])121 const j = await run(["inbox", "--json"], env())122 assert.deepEqual(j.json, { error: { code: "insufficient_scope", message: "scope", status: 403 } })123})124test("réessai sur 503 avec la même Idempotency-Key", async () => {125 reset([[503, { error: { code: "x", message: "x" } }], [201, MSG]])126 const r = await run(["send", "--to", "+14185550123", "--text", "x", "--json"], env())127 assert.equal(r.code, 0); assert.equal(seen.length, 2)128 assert.equal(seen[0].headers["idempotency-key"], seen[1].headers["idempotency-key"])129})130test("listes : tableau, --json, --all suit les curseurs", async () => {131 reset([[200, { data: [MSG], has_more: true, next_cursor: "c1" }], [200, { data: [{ ...MSG, id: "sms_2" }], has_more: false, next_cursor: null }]])132 const a = await run(["messages", "--limit", "1", "--all", "--json"], env())133 assert.deepEqual(a.json.data.map(m => m.id), ["sms_1", "sms_2"]); assert.match(seen[1].url, /cursor=c1/)134 reset([[200, { data: [MSG], has_more: true, next_cursor: "c1" }]])135 const t = await run(["messages", "--status", "queued"], env())136 assert.match(t.stdout, /ID\s+STATUT/); assert.match(t.stdout, /--cursor c1/); assert.match(seen[0].url, /status=queued/)137 reset([[200, { data: [] }]])138 assert.match((await run(["webhooks", "list"], env())).stdout, /aucun résultat/)139})140141test("verify : jamais réessayé, retry_after exposé, code de sortie selon la validité", async () => {142 const ver = { id: "ver_1", to: "+14185550123", status: "pending", attempts: 0, attempts_remaining: 5, expires_at: "2026-11-30T22:10:00.000Z", message_status: "queued" }143 reset([[201, ver]])144 const s = await run(["verify", "start", "--to", "+14185550123", "--brand", "Lou-Ka", "--locale", "fr", "--json"], env())145 assert.equal(s.json.id, "ver_1"); assert.deepEqual(seen[0].body, { to: "+14185550123", brand: "Lou-Ka", locale: "fr" }); assert.equal(seen[0].headers["idempotency-key"], undefined)146 reset([[503, { error: { code: "x", message: "x" } }], [201, ver]])147 assert.equal((await run(["verify", "start", "--to", "+14185550123", "--json"], env())).code, 1); assert.equal(seen.length, 1)148 reset([[429, { error: { code: "verification_too_soon", message: "attendre" } }, { "retry-after": "27" }], [201, ver]])149 const t = await run(["verify", "start", "--to", "+14185550123", "--json"], env())150 assert.deepEqual(t.json.error, { code: "verification_too_soon", message: "attendre", status: 429, retry_after: 27 }); assert.equal(seen.length, 1)151 reset([[200, { ...ver, attempts_remaining: 4, valid: false }]])152 const bad = await run(["verify", "check", "ver_1", "--code", "000000"], env())153 assert.equal(bad.code, 3); assert.match(bad.stdout, /REFUSÉ/); assert.deepEqual(seen[0].body, { code: "000000" })154 reset([[500, {}], [200, { ...ver, valid: true }]])155 assert.equal((await run(["verify", "check", "ver_1", "--code", "123456", "--json"], env())).code, 1); assert.equal(seen.length, 1)156 reset([[200, { ...ver, status: "approved", valid: true }]])157 const ok = await run(["verify", "check", "ver_1", "--code", "123456", "--json"], env())158 assert.equal(ok.code, 0); assert.equal(ok.json.valid, true)159 reset([[200, ver]])160 assert.match((await run(["verify", "status", "ver_1"], env())).stdout, /ver_1\s+PENDING/)161 assert.equal((await run(["verify", "check", "ver_1"], env())).code, 2)162})163164const E2E = process.env.MACLUSTR_SMS_E2E === "1"165test("bout en bout contre un vrai backend (téléphone simulé)", { skip: !E2E && "lancer sdk/tests-e2e/run.mjs" }, async () => {166 const e = { MACLUSTR_SMS_URL: process.env.MACLUSTR_SMS_URL, MACLUSTR_SMS_API_KEY: process.env.MACLUSTR_SMS_API_KEY }, to = process.env.E2E_TO, control = process.env.E2E_CONTROL167 const j = async (...a) => { const r = await run([...a, "--json"], e); assert.ok(r.json !== undefined, `${a.join(" ")} → ${r.stdout}${r.stderr}`); return r }168 const st = await j("status")169 assert.equal(st.json.health.status, "ok"); assert.equal(st.json.devices[0].online, true)170 const doc = await j("doctor")171 assert.equal(doc.code, 0, JSON.stringify(doc.json)); assert.equal(doc.json.ok, true)172 assert.deepEqual(Object.values(doc.json.scopes), Array(10).fill(true)); assert.equal(doc.json.scopes["verify:manage"], true)173 assert.ok(doc.json.checks.find(c => c.name === "sim").ok)174 assert.match((await run(["doctor"], e)).stdout, /rien de bloquant/)175 const bad = await run(["doctor", "--json"], { ...e, MACLUSTR_SMS_API_KEY: "mlsk_" + "z".repeat(43) })176 assert.equal(bad.code, 1); assert.equal(bad.json.checks.find(c => c.name === "authentification").ok, false)177178 const s = await j("send", "--to", to, "--text", "Bonjour depuis MacLustr (cli)", "--idempotency-key", "cli-e2e-1", "--wait", "20", "--final")179 assert.equal(s.code, 0); assert.equal(s.json.status, "delivered")180 const again = await j("send", "--to", to, "--text", "Bonjour depuis MacLustr (cli)", "--idempotency-key", "cli-e2e-1")181 assert.equal(again.json.id, s.json.id); assert.equal(again.json.replayed, true)182 const inv = await j("send", "--to", "12345", "--text", "x")183 assert.equal(inv.code, 1); assert.equal(inv.json.error.code, "invalid_phone_number"); assert.equal(inv.json.error.status, 422)184 assert.equal((await j("send", "--to", "+15145550111", "--text", "x")).json.error.code, "recipient_not_allowed")185 assert.equal((await j("cancel", s.json.id)).json.error.code, "not_cancellable")186 const m = await run(["message", s.json.id], e)187 assert.match(m.stdout, /DELIVERED/); assert.match(m.stdout, /sms\.delivery\.confirmed/)188189 // Vérification par code : le code n'est lisible que dans le SMS (ici : celui reçu par l'appareil simulé).190 const vto = process.env.E2E_VERIFY_TO191 const v = await j("verify", "start", "--to", vto, "--brand", "Tests CLI")192 assert.equal(v.json.status, "pending")193 const soon = await j("verify", "start", "--to", vto)194 assert.equal(soon.code, 1); assert.equal(soon.json.error.code, "verification_too_soon"); assert.ok(soon.json.error.retry_after > 0 && soon.json.error.retry_after <= 30)195 const { code } = await (await fetch(control + "/code?to=" + encodeURIComponent(vto))).json()196 const wrong = await j("verify", "check", v.json.id, "--code", String((Number(code) + 1) % 1000000).padStart(6, "0"))197 assert.equal(wrong.code, 3); assert.equal(wrong.json.valid, false)198 const right = await j("verify", "check", v.json.id, "--code", code)199 assert.equal(right.code, 0); assert.equal(right.json.valid, true)200 assert.equal((await j("verify", "check", v.json.id, "--code", code)).code, 3)201 assert.equal((await j("verify", "status", v.json.id)).json.status, "approved")202203 for (let i = 0; i < 2; i++) await j("send", "--to", to, "--text", `page ${i} (cli)`)204 const p = await j("messages", "--limit", "2")205 assert.equal(p.json.data.length, 2); assert.equal(p.json.has_more, true)206 const all = await j("messages", "--limit", "2", "--all")207 assert.ok(all.json.data.length >= 3 && all.json.data.some(x => x.id === s.json.id))208209 const text = `Réponse cli ${Date.now()}`210 await fetch(control + "/receive", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ from: to, text }) })211 let got212 for (let i = 0; i < 50 && !got; i++) { got = (await j("inbox", "--from", to)).json.data.find(x => x.text === text); if (!got) await new Promise(r => setTimeout(r, 100)) }213 assert.ok(got); assert.equal(got.status, "received")214 const conv = (await j("conversations")).json.data.find(c => c.peer === to)215 assert.match((await run(["conversations", conv.id], e)).stdout, new RegExp("← +" + text))216217 assert.equal((await j("devices", "list")).json[0].online, true)218 assert.equal((await j("sims", "list")).json[0].send_enabled, true)219 assert.equal((await j("numbers")).json.length, 1)220 assert.ok("pending" in (await j("queue")).json)221 assert.ok((await j("usage")).json.quota.used_today >= 3)222 for (const c of [["devices", "list"], ["sims", "list"], ["numbers"], ["queue"], ["usage"], ["inbox"], ["conversations"], ["status"]]) assert.equal((await run(c, e)).code, 0, c.join(" "))223224 const w = await j("webhooks", "add", "--url", control + "/hook", "--events", "sms.delivered,sms.received", "--description", "cli-e2e")225 assert.match(w.json.secret, /^whsec_/)226 assert.ok((await j("webhooks", "list")).json.some(x => x.id === w.json.id))227 assert.equal((await j("webhooks", "rm", w.json.id)).json.deleted, true)228})229