Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr SMS Gateway8 * File : sdk/tests-e2e/run.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// Scénario de bout en bout des SDK et de la CLI contre un VRAI backend (processus serveur + PostgreSQL).43// Le téléphone est SIMULÉ (FakeDevice de backend/tests/harness.ts, qui parle le protocole réel) : AUCUN SMS n'est émis44// sur un réseau cellulaire. Ce script prouve l'intégration client ↔ API, pas l'envoi réel.45//46// node --import tsx sdk/tests-e2e/run.mjs [python] [typescript] [swift] [cli] (depuis la racine du dépôt)47//48// Base jetable maclustr_sms_sdk_test (créée puis supprimée), serveur sur 8771, serveur de contrôle sur 8772.49import { spawn, spawnSync } from "node:child_process"50import crypto from "node:crypto"51import http from "node:http"52import path from "node:path"53import { fileURLToPath } from "node:url"5455const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..")56process.chdir(ROOT)57const DBNAME = "maclustr_sms_sdk_test", PORT = 8771, CONTROL_PORT = 8772, TO = "+14185550123"58process.env.SMS_TEST_PORT = String(PORT)59process.env.SMS_TEST_DB = `postgres://127.0.0.1/${DBNAME}`60const PG = "/opt/homebrew/opt/postgresql@17/bin"61const pgEnv = { ...process.env, PATH: `${PG}:${process.env.PATH}` }62spawnSync("dropdb", ["--if-exists", DBNAME], { env: pgEnv })63if (spawnSync("createdb", [DBNAME], { env: pgEnv, stdio: "inherit" }).status !== 0) throw new Error("createdb a échoué")6465const h = await import("../../backend/tests/harness.ts")66const dev = new h.FakeDevice()67const hits = []68const control = http.createServer((req, res) => {69 let body = ""70 req.on("data", d => (body += d)).on("end", () => {71 if (req.method === "POST" && req.url === "/hook") { hits.push({ headers: req.headers, body }); return res.writeHead(204).end() }72 if (req.method === "GET" && req.url === "/hits") return res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(hits))73 if (req.method === "GET" && req.url.startsWith("/code?")) {74 // Le code de vérification n'existe que dans le SMS : on le lit dans le dernier texte « reçu » par l'appareil simulé pour ce numéro.75 const to = new URL(req.url, "http://x").searchParams.get("to")76 return void h.until(() => dev.modem.findLast(m => m.to === to && /\b\d{6,8}\b/.test(m.text)), "SMS de vérification remis à l'appareil simulé", 8000)77 .then(m => res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ code: /\b(\d{6,8})\b/.exec(m.text)[1] })), () => res.writeHead(504).end("{}"))78 }79 if (req.method === "POST" && req.url === "/receive") { const j = JSON.parse(body); dev.receive(j.from, j.text); return res.writeHead(202).end() }80 res.writeHead(404).end()81 })82})8384const results = []85let failed = false86try {87 await h.resetDatabase()88 await h.startServer()89 const key = /mlsk_[A-Za-z0-9_-]+/.exec(h.cli("create-key", "--app", "sdk-tests", "--scopes", "messages:send,messages:read,messages:cancel,inbox:read,devices:read,numbers:read,webhooks:manage,usage:read,queue:read,verify:manage"))[0]90 await h.sql`update applications set rate_per_minute = 600, daily_quota = 10000`91 // Association : code inséré directement en base (le tableau de bord n'est pas sollicité ici).92 const code = "E2E2-SDKS-TEST"93 await h.sql`insert into pairing_codes(code_hash, name_hint, expires_at) values (${crypto.createHash("sha256").update(code.replace(/-/g, "")).digest("hex")}, 'Appareil simulé', now() + interval '5 minutes')`94 const paired = await dev.pair(code, "Appareil simulé (tests SDK)")95 if (paired.status !== 201) throw new Error("association refusée : " + JSON.stringify(paired.body))96 await dev.connect()97 await h.until(() => dev.outbox.length === 0, "inventaire SIM acquitté")98 await h.sql`update sim_profiles set enabled = true, daily_limit = 10000`99 await h.sql`insert into allowed_recipients(number, label) values (${TO}, 'tests SDK')`100 // Un numéro de vérification par client : la limite est d'un code par 30 s et par numéro.101 const VERIFY_TO = { python: "+14185550131", typescript: "+14185550132", swift: "+14185550133", cli: "+14185550134" }102 for (const n of Object.values(VERIFY_TO)) await h.sql`insert into allowed_recipients(number, label) values (${n}, 'tests SDK (vérification)')`103 await new Promise(r => control.listen(CONTROL_PORT, "127.0.0.1", r))104105 const env = { ...process.env, MACLUSTR_SMS_E2E: "1", MACLUSTR_SMS_URL: h.ORIGIN, MACLUSTR_SMS_API_KEY: key, E2E_CONTROL: `http://127.0.0.1:${CONTROL_PORT}`, E2E_TO: TO, MACLUSTR_SMS_NO_KEYCHAIN: "1" }106 const suites = {107 python: ["sdk/python", "python3", ["-W", "error", "-m", "unittest", "discover", "-s", "tests"], { PYTHONPATH: "." }],108 typescript: ["sdk/typescript", "npm", ["test", "--silent"], {}],109 swift: ["sdk/swift", "swift", ["test"], {}],110 cli: ["cli", process.execPath, ["--test", "tests/cli.test.mjs"], {}],111 }112 const wanted = process.argv.slice(2).length ? process.argv.slice(2) : Object.keys(suites)113 for (const name of wanted) {114 const [cwd, cmd, args, extra] = suites[name]115 console.log(`\n━━ ${name} ━━`)116 const before = dev.modem.length117 const code = await new Promise(r => spawn(cmd, args, { cwd: path.join(ROOT, cwd), env: { ...env, ...extra, E2E_VERIFY_TO: VERIFY_TO[name] }, stdio: "inherit" }).on("close", r))118 // Contrôle indépendant du client : ce que l'appareil simulé a réellement « remis au modem ».119 const sent = dev.modem.slice(before).map(m => m.text)120 const idem = sent.filter(t => t.startsWith("Notification MacLustr") || t.startsWith("Bonjour depuis MacLustr")).length121 const codes = dev.modem.slice(before).filter(m => m.to === VERIFY_TO[name]).length // un seul code envoyé : le second démarrage est refusé (429)122 const ok = code === 0 && idem === 1 && sent.length === 4 && codes === 1123 results.push({ suite: name, exit: code, modem_sends: sent.length, idempotent_text_sent: idem, verification_codes_sent: codes, ok })124 if (!ok) failed = true125 }126} catch (e) { failed = true; console.error(e) } finally {127 control.close()128 await dev.close().catch(() => {})129 await h.stopServer()130 await h.sql.end()131 spawnSync("dropdb", ["--if-exists", DBNAME], { env: pgEnv })132}133console.log("\n━━ bilan (appareil simulé, aucun SMS réel) ━━")134console.table(results)135console.log(`webhooks reçus par le serveur de contrôle : ${hits.length}`)136process.exit(failed ? 1 : 0)137