Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr SMS Gateway8 * File : backend/tests/harness.ts9 * Module : backend10 * 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// Banc d'essai : un vrai processus serveur, une vraie base PostgreSQL, un appareil simulé qui parle le protocole réel43// (clé ECDSA P-256, signature du défi, journal de commandes, boîte d'envoi). Rien n'est bouchonné côté serveur.44// L'appareil simulé remplace UNIQUEMENT le téléphone : ces tests ne prouvent aucun envoi sur le réseau cellulaire.45import { spawn, spawnSync, type ChildProcess } from "node:child_process"46import crypto from "node:crypto"47import http from "node:http"48import postgres from "postgres"49import WebSocket from "ws"5051export const PORT = Number(process.env.SMS_TEST_PORT ?? 8761)52export const ORIGIN = `http://localhost:${PORT}`53export const DB = process.env.SMS_TEST_DB ?? "postgres://127.0.0.1/maclustr_sms_test"54if (!/_test$/.test(DB)) throw new Error("les tests refusent de tourner hors d'une base *_test")55export const sql = postgres(DB, { onnotice: () => {}, max: 4 })56const ENV = { ...process.env, DATABASE_URL: DB, PORT: String(PORT), HOST: "127.0.0.1", SMS_ORIGIN: ORIGIN, SMS_RP_ID: "localhost", SMS_LOG_LEVEL: "warn", SMS_WEB_DIR: process.env.SMS_TEST_WEB_DIR ?? "/nonexistent",57 SMS_DATA_KEY: crypto.randomBytes(32).toString("base64"), SMS_WEBHOOK_ALLOW_HOSTS: "127.0.0.1", SMS_WEBHOOK_BACKOFF_S: "1,1", SMS_RATE_SCALE: "50", SMS_HEARTBEAT_S: "2", SMS_RELEASES_DIR: process.env.SMS_TEST_RELEASES_DIR ?? "/nonexistent" }5859let server: ChildProcess | undefined60export const sleep = (ms: number) => new Promise(r => setTimeout(r, ms))61export async function until<T>(cond: () => T | Promise<T>, what: string, timeout = 10_000): Promise<NonNullable<T>> {62 const t0 = Date.now()63 while (Date.now() - t0 < timeout) { const v = await cond(); if (v) return v as NonNullable<T>; await sleep(30) }64 throw new Error(`délai dépassé en attendant : ${what}`)65}66export async function resetDatabase() { await sql.unsafe("drop schema public cascade; create schema public;") }67export async function startServer() {68 server = spawn(process.execPath, ["--import", "tsx", "backend/src/index.ts"], { env: ENV, stdio: ["ignore", "inherit", "inherit"] })69 for (let i = 0; i < 100; i++) { try { if ((await fetch(`${ORIGIN}/api/health/ready`)).ok) return } catch {} await sleep(100) }70 throw new Error("le serveur n'a pas démarré")71}72export async function stopServer(signal: NodeJS.Signals = "SIGTERM") {73 const s = server; server = undefined74 if (!s) return75 await new Promise<void>(r => { s.once("exit", () => r()); s.kill(signal) })76}77export function cli(...args: string[]) {78 const r = spawnSync("node_modules/.bin/tsx", ["backend/src/admin-cli.ts", ...args], { env: ENV, encoding: "utf8" })79 if (r.status !== 0) throw new Error(r.stderr || r.stdout)80 return r.stdout81}8283// ── Client HTTP ───────────────────────────────────────────────────────────────84export interface Res { status: number; body: any; headers: Headers }85export async function call(method: string, path: string, opts: { key?: string; cookie?: string; body?: unknown; headers?: Record<string, string> } = {}): Promise<Res> {86 const headers: Record<string, string> = { ...(opts.headers ?? {}) }87 if (opts.key) headers.authorization = `Bearer ${opts.key}`88 if (opts.cookie) { headers.cookie = opts.cookie; headers["x-requested-with"] ??= "maclustr-sms"; headers.origin ??= ORIGIN }89 if (opts.body !== undefined) headers["content-type"] = "application/json"90 const res = await fetch(ORIGIN + path, { method, headers, body: opts.body === undefined ? undefined : JSON.stringify(opts.body) })91 const text = await res.text()92 let body: any = text93 try { body = JSON.parse(text) } catch {}94 return { status: res.status, body, headers: res.headers }95}9697// ── Authentificateur WebAuthn logiciel (ES256, attestation « none ») ──────────98const b64u = (b: Buffer | Uint8Array) => Buffer.from(b).toString("base64url")99const cborBytes = (b: Buffer) => b.length < 24 ? Buffer.concat([Buffer.from([0x40 + b.length]), b]) : b.length < 256 ? Buffer.concat([Buffer.from([0x58, b.length]), b]) : Buffer.concat([Buffer.from([0x59, b.length >> 8, b.length & 255]), b])100const cborText = (s: string) => Buffer.concat([Buffer.from([0x60 + s.length]), Buffer.from(s)])101export class Authenticator {102 creds = new Map<string, { key: crypto.KeyObject; userHandle: string; counter: number }>()103 create(options: any) {104 const { privateKey, publicKey } = crypto.generateKeyPairSync("ec", { namedCurve: "P-256" })105 const jwk = publicKey.export({ format: "jwk" }), id = crypto.randomBytes(16)106 const cose = Buffer.concat([Buffer.from([0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21]), cborBytes(Buffer.from(jwk.x!, "base64url")), Buffer.from([0x22]), cborBytes(Buffer.from(jwk.y!, "base64url"))])107 const authData = Buffer.concat([crypto.createHash("sha256").update(options.rp.id).digest(), Buffer.from([0x5d]), Buffer.alloc(4), Buffer.alloc(16), Buffer.from([0, id.length]), id, cose])108 const attestationObject = Buffer.concat([Buffer.from([0xa3]), cborText("fmt"), cborText("none"), cborText("attStmt"), Buffer.from([0xa0]), cborText("authData"), cborBytes(authData)])109 const clientDataJSON = Buffer.from(JSON.stringify({ type: "webauthn.create", challenge: options.challenge, origin: ORIGIN, crossOrigin: false }))110 this.creds.set(b64u(id), { key: privateKey, userHandle: options.user.id, counter: 0 })111 return { id: b64u(id), rawId: b64u(id), type: "public-key", clientExtensionResults: {}, authenticatorAttachment: "platform", response: { clientDataJSON: b64u(clientDataJSON), attestationObject: b64u(attestationObject), transports: ["internal"] } }112 }113 get(options: any) {114 const id = [...this.creds.keys()][0], c = this.creds.get(id)!115 c.counter++116 const counter = Buffer.alloc(4); counter.writeUInt32BE(c.counter)117 const authData = Buffer.concat([crypto.createHash("sha256").update(options.rpId).digest(), Buffer.from([0x1d]), counter])118 const clientDataJSON = Buffer.from(JSON.stringify({ type: "webauthn.get", challenge: options.challenge, origin: ORIGIN, crossOrigin: false }))119 const signature = crypto.sign("sha256", Buffer.concat([authData, crypto.createHash("sha256").update(clientDataJSON).digest()]), c.key)120 return { id, rawId: id, type: "public-key", clientExtensionResults: {}, authenticatorAttachment: "platform", response: { clientDataJSON: b64u(clientDataJSON), authenticatorData: b64u(authData), signature: b64u(signature), userHandle: c.userHandle } }121 }122}123export const cookieOf = (r: Res) => (r.headers.getSetCookie?.() ?? []).map(c => c.split(";")[0]).filter(c => !c.endsWith("=")).join("; ")124125// ── Appareil Android simulé ───────────────────────────────────────────────────126type Mode = "ok" | "fail" | "ack_only" | "accept_only" | "stall_in_submitting" | "unknown" | "expired_check"127interface Entry { state: "accepted" | "submitting" | "submitted" | "failed" | "unknown"; cmd: any; parts: number }128export class FakeDevice {129 keys = crypto.generateKeyPairSync("ec", { namedCurve: "P-256" })130 deviceId = ""131 ws: WebSocket | null = null132 authenticated = false133 closeCode: number | null = null134 mode: Mode = "ok"135 deliver = true136 journal = new Map<string, Entry>() // journal local des commandes (clé : command_id)137 modem: { command_id: string; to: string; text: string; subscription_id: number }[] = [] // ce qui a réellement été « remis au modem »138 outbox: { type: string; id: string; ts: string; data: any }[] = [] // événements non acquittés139 frames: any[] = []140 config: any = null141 sims = [{ subscription_id: 1, slot_index: 0, carrier_name: "Opérateur Test", display_name: "SIM 1", is_embedded: false, number: "+14185550124" as string | null, country_iso: "ca", mcc_mnc: "302999", state: "ready", signal_level: 3, roaming: false, is_default_sms: true }]142 get publicKey() { return this.keys.publicKey.export({ format: "der", type: "spki" }).toString("base64") }143 sign(s: string, key = this.keys.privateKey) { return crypto.sign("sha256", Buffer.from(s, "utf8"), key).toString("base64") }144145 async pair(code: string, name = "Appareil de test") {146 const r = await call("POST", "/v1/device/pair", { body: { code, public_key: this.publicKey, name, manufacturer: "Test", model: "Simulateur", android_version: "16", sdk_int: 36, app_version: "1.0.0", app_build: 1 } })147 if (r.status === 201) this.deviceId = r.body.device_id148 return r149 }150 private raw(type: string, data: any, id: string = crypto.randomUUID()) { this.ws?.readyState === WebSocket.OPEN && this.ws.send(JSON.stringify({ type, id, ts: new Date().toISOString(), data })) }151 /** Événement fiable : conservé en boîte d'envoi jusqu'à l'accusé de réception, renvoyé à la reconnexion. */152 emit(type: string, data: any, id: string = crypto.randomUUID()) {153 const f = { type, id, ts: new Date().toISOString(), data }154 this.outbox.push(f)155 if (this.authenticated && this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify(f))156 return id157 }158 connect(opts: { hello?: (nonce: string) => any; status?: boolean } = {}): Promise<void> {159 this.authenticated = false; this.closeCode = null160 const ws = (this.ws = new WebSocket(`ws://localhost:${PORT}/ws/device`))161 return new Promise((resolve, reject) => {162 ws.on("message", buf => {163 const f = JSON.parse(buf.toString())164 this.frames.push(f)165 if (f.type === "server.hello") {166 const signed_at = new Date().toISOString()167 const data = opts.hello ? opts.hello(f.data.nonce) : { device_id: this.deviceId, nonce: f.data.nonce, signed_at, signature: this.sign(`maclustr-sms-device-auth-v1\n${this.deviceId}\n${f.data.nonce}\n${signed_at}`), protocol: 1, app_version: "1.0.0", app_build: 1 }168 this.raw("device.hello", data)169 } else if (f.type === "device.authenticated") {170 this.authenticated = true171 for (const o of this.outbox) ws.send(JSON.stringify(o)) // reprise : renvoi des événements non acquittés, dans l'ordre172 if (opts.status !== false) {173 this.emit("device.status", this.status()); this.emit("device.sim.updated", { sims: this.sims })174 const beat = setInterval(() => (ws.readyState === WebSocket.OPEN ? this.heartbeat() : clearInterval(beat)), 1000)175 ws.once("close", () => clearInterval(beat))176 }177 resolve()178 } else if (f.type === "ack") this.outbox = this.outbox.filter(o => o.id !== f.data.ack)179 else if (f.type === "device.config.updated") { this.config = f.data; this.raw("ack", { ack: f.id }) }180 else if (f.type === "sms.send.request") this.onCommand(f)181 else if (f.type === "device.diagnostic.request") { this.raw("ack", { ack: f.id }); this.emit("device.diagnostic", { request_id: f.data.request_id, checks: [{ name: "send_sms_permission", ok: true, detail: "" }] }) }182 })183 ws.on("close", code => { this.closeCode = code; this.authenticated = false; reject(new Error("fermé : " + code)) })184 ws.on("error", () => {})185 })186 }187 status(over: any = {}) { return { battery_pct: 87, charging: true, battery_temp_c: 31.5, power_save: false, battery_optimization_exempt: true, network: "wifi", airplane_mode: false, gateway_state: "running", permissions: { send_sms: true, receive_sms: true, read_phone_state: true, post_notifications: true }, uptime_s: 100, pending_commands: 0, pending_events: 0, app_version: "1.0.0", app_build: 1, android_version: "16", sdk_int: 36, manufacturer: "Test", model: "Simulateur", ...over } }188 heartbeat() { this.raw("device.heartbeat", { battery_pct: 87, charging: true, pending_events: this.outbox.length }) }189190 /** Règles anti-doublon du protocole (§5) : le journal local tranche, un command_id connu n'est jamais renvoyé au modem. */191 private onCommand(f: any) {192 const c = f.data, ids = { command_id: c.command_id, message_id: c.message_id }193 const known = this.journal.get(c.command_id)194 if (this.mode === "ack_only" && !known) { this.journal.set(c.command_id, { state: "accepted", cmd: c, parts: 1 }); this.raw("ack", { ack: f.id }); return }195 this.raw("ack", { ack: f.id })196 if (known) {197 if (known.state === "accepted") { this.emit("sms.send.accepted", ids); if (this.mode !== "accept_only" && this.mode !== "ack_only") this.process(c) }198 else if (known.state === "submitting") { known.state = "unknown"; this.emit("sms.send.unknown", { ...ids, reason: "interrupted_during_submit" }) }199 else if (known.state === "submitted") this.emit("sms.send.submitted", { ...ids, parts: known.parts, submitted_at: new Date().toISOString() })200 else if (known.state === "unknown") this.emit("sms.send.unknown", { ...ids, reason: "interrupted_during_submit" })201 else this.emit("sms.send.failed", { ...ids, code: "generic_failure", definitive: true, parts: known.parts, parts_sent: 0 })202 return203 }204 this.journal.set(c.command_id, { state: "accepted", cmd: c, parts: 1 })205 this.emit("sms.send.accepted", ids)206 if (this.mode !== "accept_only") this.process(c)207 }208 process(c: any) {209 const ids = { command_id: c.command_id, message_id: c.message_id }, e = this.journal.get(c.command_id)!210 const parts = e.parts = Math.max(1, Math.ceil(c.text.length / 153) > 1 && c.text.length > 160 ? Math.ceil(c.text.length / 153) : 1)211 if (Date.parse(c.expires_at) < Date.now()) { e.state = "failed"; this.emit("sms.send.failed", { ...ids, code: "expired", definitive: true, parts, parts_sent: 0 }); return }212 if (this.mode === "fail") { e.state = "failed"; this.emit("sms.send.failed", { ...ids, code: "no_service", detail: "RESULT_ERROR_NO_SERVICE", android_result_code: 4, parts, parts_sent: 0, definitive: true }); return }213 e.state = "submitting"214 this.emit("sms.send.submitting", { ...ids, parts })215 if (this.mode === "stall_in_submitting") { this.modem.push({ command_id: c.command_id, to: c.to, text: c.text, subscription_id: c.subscription_id }); return }216 if (this.mode === "unknown") { e.state = "unknown"; this.emit("sms.send.unknown", { ...ids, reason: "sent_result_timeout" }); return }217 this.modem.push({ command_id: c.command_id, to: c.to, text: c.text, subscription_id: c.subscription_id })218 e.state = "submitted"219 this.emit("sms.send.submitted", { ...ids, parts, submitted_at: new Date().toISOString() })220 if (this.deliver && c.delivery_report) for (let p = 1; p <= parts; p++) this.emit("sms.delivery.confirmed", { ...ids, part: p, parts, status: "delivered", delivered_at: new Date().toISOString(), pdu_status: 0 })221 }222 receive(from: string, text: string, subscription_id = 1, id?: string) { return this.emit("sms.received", { from, subscription_id, slot_index: 0, text, parts: 1, received_at: new Date().toISOString() }, id) }223 async close() { const ws = this.ws; if (!ws || ws.readyState >= WebSocket.CLOSING) return; await new Promise<void>(r => { ws.once("close", () => r()); ws.terminate() }) }224}225226// ── Récepteur de webhooks local ───────────────────────────────────────────────227export class WebhookSink {228 hits: { headers: http.IncomingHttpHeaders; body: string; json: any }[] = []229 failNext = 0230 server = http.createServer((req, res) => {231 let body = ""232 req.on("data", d => (body += d))233 req.on("end", () => {234 if (this.failNext > 0) { this.failNext--; res.writeHead(500).end(); return }235 this.hits.push({ headers: req.headers, body, json: JSON.parse(body) })236 res.writeHead(204).end()237 })238 })239 port = 0240 async start() { await new Promise<void>(r => this.server.listen(0, "127.0.0.1", () => r())); this.port = (this.server.address() as any).port }241 get url() { return `http://127.0.0.1:${this.port}/hook` }242 stop() { this.server.close() }243}244