SPB Git

Repository Public

gateway.test.ts 54.8 KB 865 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr SMS Gateway8 * File             : backend/tests/gateway.test.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// Tests d'intégration de la passerelle. Voir harness.ts : le téléphone est simulé, tout le reste est réel.43import assert from "node:assert/strict"44import crypto from "node:crypto"45import { after, before, describe, test } from "node:test"46import { Authenticator, call, cli, cookieOf, FakeDevice, ORIGIN, resetDatabase, sleep, sql, startServer, stopServer, until, WebhookSink } from "./harness.ts"4748const TO = "+14185550123", TO2 = "+14185550199", OTHER = "+15145550111"49let admin = "", key = "", appId = ""50const dev = new FakeDevice()51const sink = new WebhookSink()52const auth = new Authenticator()5354const status = async (id: string) => (await sql`select status from messages where id = ${id}`)[0]?.status as string55const waitStatus = (id: string, s: string) => until(async () => (await status(id)) === s, `message ${id} → ${s}`)56const send = (body: any, k = key, headers: Record<string, string> = {}) => call("POST", "/v1/messages", { key: k, body, headers })57async function newApp(name: string, extra: any = {}, scopes = ["messages:send", "messages:read", "messages:cancel", "inbox:read", "devices:read", "numbers:read", "webhooks:manage", "usage:read", "queue:read"]) {58  const a = await call("POST", "/api/admin/applications", { cookie: admin, body: { name, rate_per_minute: 600, daily_quota: 10000, ...extra } })59  assert.equal(a.status, 201, JSON.stringify(a.body))60  const k = await call("POST", `/api/admin/applications/${a.body.id}/keys`, { cookie: admin, body: { name: "test", scopes } })61  assert.equal(k.status, 201)62  return { id: a.body.id as string, key: k.body.key as string, keyId: k.body.id as string }63}64async function pairNew(d: FakeDevice, name = "Appareil") {65  const c = await call("POST", "/api/admin/pairing-codes", { cookie: admin, body: { name } })66  assert.equal(c.status, 200)67  const r = await d.pair(c.body.code, name)68  assert.equal(r.status, 201, JSON.stringify(r.body))69  return c.body70}7172before(async () => {73  await resetDatabase()74  await startServer()75  await sink.start()76})77after(async () => {78  await dev.close()79  sink.stop()80  await stopServer()81  await sql.end()82})8384describe("administration", () => {85  test("santé et description OpenAPI publiques, sans détail sensible", async () => {86    const h = await call("GET", "/v1/health")87    assert.equal(h.status, 200)88    assert.deepEqual(Object.keys(h.body).sort(), ["status", "time", "version"])89    const o = await call("GET", "/v1/openapi.json")90    assert.equal(o.body.openapi, "3.1.0")91    for (const p of ["/v1/messages", "/v1/messages/{id}", "/v1/inbox", "/v1/conversations", "/v1/devices", "/v1/devices/{id}", "/v1/devices/{id}/sims", "/v1/numbers", "/v1/webhooks", "/v1/usage", "/v1/health", "/v1/queue", "/v1/messages/{id}/cancel"])92      assert.ok(o.body.paths[p], `chemin documenté : ${p}`)93  })9495  test("les routes d'administration exigent une session", async () => {96    for (const p of ["/api/admin/overview", "/api/admin/messages", "/api/admin/devices", "/api/admin/settings", "/api/admin/android/download", "/api/admin/audit-logs"])97      assert.equal((await call("GET", p)).status, 401, p)98    assert.equal((await call("POST", "/api/admin/pairing-codes", { body: {} })).status, 403) // en-tête anti-CSRF absent99  })100101  test("enrôlement par lien à usage unique puis connexion par clé d'accès", async () => {102    const out = cli("enroll", "--handle", "simon", "--name", "Simon-Pierre")103    const token = /enroll#(\S+)/.exec(out)![1]104    assert.equal((await call("POST", "/api/auth/enroll/options", { body: { token: "x".repeat(40) } })).status, 403)105    const o = await call("POST", "/api/auth/enroll/options", { body: { token } })106    assert.equal(o.status, 200)107    assert.equal(o.body.options.authenticatorSelection.userVerification, "required")108    const v = await call("POST", "/api/auth/enroll/verify", { body: { token, challenge_id: o.body.challenge_id, response: auth.create(o.body.options) } })109    assert.equal(v.status, 200, JSON.stringify(v.body))110    assert.ok(cookieOf(v).startsWith("mlsms_session="))111    // le lien ne sert qu'une fois112    assert.equal((await call("POST", "/api/auth/enroll/options", { body: { token } })).status, 403)113114    const lo = await call("POST", "/api/auth/login/options", { body: {} })115    const lv = await call("POST", "/api/auth/login/verify", { body: { challenge_id: lo.body.challenge_id, response: auth.get(lo.body.options) } })116    assert.equal(lv.status, 200, JSON.stringify(lv.body))117    admin = cookieOf(lv)118    const setCookie = lv.headers.getSetCookie()[0]119    assert.match(setCookie, /HttpOnly/i); assert.match(setCookie, /SameSite=Strict/i)120    assert.equal((await call("GET", "/api/auth/me", { cookie: admin })).body.user.handle, "simon")121    // un défi ne se rejoue pas122    assert.equal((await call("POST", "/api/auth/login/verify", { body: { challenge_id: lo.body.challenge_id, response: auth.get(lo.body.options) } })).status, 400)123  })124125  test("protection CSRF : origine étrangère et en-tête manquant refusés", async () => {126    assert.equal((await call("POST", "/api/admin/pairing-codes", { cookie: admin, body: {}, headers: { origin: "https://evil.example" } })).status, 403)127    assert.equal((await call("POST", "/api/admin/pairing-codes", { cookie: admin, body: {}, headers: { "x-requested-with": "autre" } })).status, 403)128  })129})130131describe("clés API et permissions", () => {132  test("création d'application et de clé ; la clé n'est stockée que hachée", async () => {133    const a = await newApp("tests")134    appId = a.id; key = a.key135    assert.match(key, /^mlsk_/)136    const [row] = await sql`select key_hash, prefix from api_keys where id = ${a.keyId}`137    assert.equal(row.key_hash, crypto.createHash("sha256").update(key).digest("hex"))138    assert.ok(!JSON.stringify(await sql`select * from api_keys`).includes(key))139  })140  test("authentification obligatoire, scopes appliqués, clé révoquée refusée", async () => {141    assert.equal((await call("GET", "/v1/messages")).status, 401)142    assert.equal((await call("GET", "/v1/messages", { key: "mlsk_" + "a".repeat(43) })).body.error.code, "invalid_api_key")143    const ro = await newApp("lecture-seule", {}, ["messages:read"])144    const r = await send({ to: TO, text: "x" }, ro.key)145    assert.equal(r.status, 403); assert.equal(r.body.error.code, "insufficient_scope")146    assert.equal((await call("GET", "/v1/devices", { key: ro.key })).status, 403)147    assert.equal((await call("POST", `/api/admin/keys/${ro.keyId}/revoke`, { cookie: admin, body: {} })).status, 200)148    assert.equal((await call("GET", "/v1/messages", { key: ro.key })).status, 401)149  })150  test("rotation : nouvelle clé valide, ancienne limitée à 24 h", async () => {151    const a = await newApp("rotation")152    const r = await call("POST", `/api/admin/keys/${a.keyId}/rotate`, { cookie: admin, body: {} })153    assert.equal(r.status, 200)154    assert.equal((await call("GET", "/v1/messages", { key: r.body.key })).status, 200)155    const [old] = await sql`select expires_at from api_keys where id = ${a.keyId}`156    assert.ok(new Date(old.expires_at).getTime() - Date.now() <= 24 * 3600_000 + 1000)157  })158})159160describe("association et authentification de l'appareil", () => {161  test("code invalide, clé publique invalide, puis association ; le code ne sert qu'une fois", async () => {162    assert.equal((await dev.pair("AAAA-BBBB-CCCC")).body.error.code, "pairing_code_invalid")163    const c = await call("POST", "/api/admin/pairing-codes", { cookie: admin, body: { name: "Pixel test" } })164    assert.match(c.body.code, /^[A-Z2-9]{4}-[A-Z2-9]{4}-[A-Z2-9]{4}$/)165    assert.ok(c.body.uri.startsWith("maclustr-sms://pair?server=") && c.body.qr_svg.includes("<svg"))166    const bad = await call("POST", "/v1/device/pair", { body: { code: c.body.code, public_key: Buffer.alloc(91, 1).toString("base64") } })167    assert.equal(bad.status, 400)168    const r = await dev.pair(c.body.code.toLowerCase().replace(/-/g, ""), "Pixel test")   // casse et tirets indifférents169    assert.equal(r.status, 201)170    assert.equal(r.body.device_id, "android-01")171    assert.ok(r.body.ws_url.endsWith("/ws/device"))172    assert.equal((await new FakeDevice().pair(c.body.code)).status, 404)173    // code expiré174    const c2 = await call("POST", "/api/admin/pairing-codes", { cookie: admin, body: {} })175    await sql`update pairing_codes set expires_at = now() - interval '1 second' where used_at is null`176    assert.equal((await new FakeDevice().pair(c2.body.code)).status, 404)177  })178179  test("signature invalide, nonce rejoué et appareil inconnu sont refusés", async () => {180    const intruder = new FakeDevice(); intruder.deviceId = dev.deviceId          // même identifiant, autre clé181    await assert.rejects(intruder.connect())182    assert.equal(intruder.closeCode, 4401)183    // rejeu : un device.hello valide capturé sur une autre connexion (autre nonce) ne passe pas184    const oldNonce = crypto.randomBytes(32).toString("base64url"), signed_at = new Date().toISOString()185    const replay = new FakeDevice(); replay.deviceId = dev.deviceId186    await assert.rejects(replay.connect({ hello: () => ({ device_id: dev.deviceId, nonce: oldNonce, signed_at, signature: dev.sign(`maclustr-sms-device-auth-v1\n${dev.deviceId}\n${oldNonce}\n${signed_at}`) }) }))187    assert.equal(replay.closeCode, 4401)188    // horloge hors tolérance189    const late = new FakeDevice(); late.deviceId = dev.deviceId190    await assert.rejects(late.connect({ hello: n => { const t = new Date(Date.now() - 3600_000).toISOString(); return { device_id: dev.deviceId, nonce: n, signed_at: t, signature: dev.sign(`maclustr-sms-device-auth-v1\n${dev.deviceId}\n${n}\n${t}`) } } }))191    assert.equal(late.closeCode, 4401)192    const ghost = new FakeDevice(); ghost.deviceId = "android-99"193    await assert.rejects(ghost.connect())194  })195196  test("connexion authentifiée : état, inventaire SIM, configuration", async () => {197    await dev.connect()198    await until(() => dev.outbox.length === 0, "événements initiaux acquittés")199    const d = await call("GET", "/api/admin/devices", { cookie: admin })200    const me = d.body.data.find((x: any) => x.id === dev.deviceId)201    assert.equal(me.online, true); assert.equal(me.battery_pct, 87); assert.equal(me.sims.length, 1)202    assert.equal(me.sims[0].id, "sim-1"); assert.equal(me.sims[0].number, "+14185550124"); assert.equal(me.sims[0].type, "physical")203    assert.equal(me.sims[0].send_enabled, false, "une nouvelle SIM n'envoie pas avant activation")204    await until(() => dev.config?.sims?.length === 1, "configuration avec SIM")205    assert.equal(dev.config.gateway_enabled, true)206  })207208  test("une SIM non activée refuse l'envoi ; activation par l'administrateur", async () => {209    await call("POST", "/api/admin/allowed-recipients", { cookie: admin, body: { number: TO, label: "essai" } })210    const r = await send({ to: TO, text: "avant activation" })211    assert.equal(r.status, 422); assert.equal(r.body.error.code, "no_sender_available")212    assert.equal((await call("PATCH", "/api/admin/sims/sim-1", { cookie: admin, body: { send_enabled: true, daily_limit: 1000 } })).status, 200)213    await until(() => dev.config?.sims?.[0]?.enabled === true, "configuration poussée à l'appareil")214  })215})216217describe("envoi", () => {218  test("validation des entrées", async () => {219    for (const [body, code] of [[{ to: "12345", text: "x" }, "invalid_phone_number"], [{ to: TO, text: "   " }, "empty_text"], [{ to: TO, text: "😀".repeat(400) }, "text_too_long"]] as const) {220      const r = await send(body)221      assert.equal(r.status, 422, JSON.stringify(r.body)); assert.equal(r.body.error.code, code)222    }223    assert.equal((await send({ to: TO })).status, 400)224    assert.equal((await send({ to: TO, text: "x", admin: true })).status, 400, "champ inconnu refusé")225    assert.equal((await send({ to: TO, text: "x" }, key, { "idempotency-key": "é" })).status, 400)226    const inj = await send({ to: "+14185550123'; drop table messages;--", text: "x" })227    assert.ok([400, 422].includes(inj.status))228    assert.equal((await sql`select count(*)::int as n from messages`)[0].n >= 0, true, "la table existe toujours")229    assert.equal((await call("GET", "/v1/messages?status=queued'%20or%201=1--", { key })).body.data.length, 0)230    assert.equal((await call("GET", "/v1/messages?cursor=zzz", { key })).status, 400)231  })232233  test("mode liste autorisée : destinataire hors liste refusé", async () => {234    const r = await send({ to: OTHER, text: "x" })235    assert.equal(r.status, 403); assert.equal(r.body.error.code, "recipient_not_allowed")236  })237238  test("parcours complet : queued → dispatched → accepted → submitting → submitted → delivered, webhooks signés", async () => {239    const wh = await call("POST", "/v1/webhooks", { key, body: { url: sink.url, events: ["sms.submitted", "sms.delivered", "sms.failed", "sms.unknown", "sms.received"] } })240    assert.equal(wh.status, 201, JSON.stringify(wh.body))241    const secret = wh.body.secret242    assert.match(secret, /^whsec_/)243    assert.equal((await call("GET", "/v1/webhooks", { key })).body.data[0].secret, undefined, "le secret n'est montré qu'à la création")244245    const r = await send({ to: "(418) 555-0123", text: "Bonjour depuis MacLustr !" }, key, { "idempotency-key": "e2e-1" })246    assert.equal(r.status, 201, JSON.stringify(r.body))247    assert.equal(r.body.status, "queued"); assert.equal(r.body.to, TO); assert.equal(r.body.device_id, "android-01"); assert.equal(r.body.sim_id, "sim-1")248    assert.equal(r.body.from, "+14185550124"); assert.equal(r.body.segments, 1); assert.equal(r.body.encoding, "gsm7")249    await waitStatus(r.body.id, "DELIVERED")250    assert.deepEqual(dev.modem.map(m => [m.to, m.text, m.subscription_id]), [[TO, "Bonjour depuis MacLustr !", 1]])251252    const g = await call("GET", `/v1/messages/${r.body.id}`, { key })253    assert.equal(g.body.status, "delivered")254    assert.deepEqual(g.body.events.filter((e: any) => !e.detail.ignored).map((e: any) => e.to), ["queued", "dispatched", "accepted", "submitting", "submitted", "delivered"])255    assert.ok(g.body.submitted_at && g.body.delivered_at)256    assert.equal((await sql`select count(*)::int as n from message_queue where message_id = ${r.body.id}`)[0].n, 0)257258    await until(() => sink.hits.length >= 2, "webhooks submitted + delivered")259    assert.deepEqual(sink.hits.map(h => h.json.event), ["sms.submitted", "sms.delivered"])260    for (const h of sink.hits) {261      const ts = h.headers["x-maclustr-timestamp"] as string262      assert.equal(h.headers["x-maclustr-signature"], "v1=" + crypto.createHmac("sha256", secret).update(`${ts}.${h.body}`).digest("hex"))263      assert.ok(Math.abs(Date.now() / 1000 - Number(ts)) < 30)264      assert.equal(h.json.data.id, r.body.id)265      assert.equal(h.json.data.text, undefined, "les événements de statut ne transportent pas le contenu")266    }267  })268269  test("le contenu est chiffré au repos et absent des journaux d'événements", async () => {270    const r = await send({ to: TO, text: "code secret 918273" })271    await waitStatus(r.body.id, "DELIVERED")272    const [m] = await sql`select text_enc from messages where id = ${r.body.id}`273    assert.ok(!Buffer.from(m.text_enc).toString("latin1").includes("918273"))274    const dump = JSON.stringify(await sql`select * from message_events where message_id = ${r.body.id}`) + JSON.stringify(await sql`select * from audit_logs`)275    assert.ok(!dump.includes("918273"))276    const enc = await sql`select payload_enc from webhook_deliveries where payload_enc is not null`277    assert.ok(enc.every(e => !Buffer.from(e.payload_enc).toString("latin1").includes("918273")))278  })279280  test("idempotence : même clé = même message, un seul envoi ; corps différent = conflit ; requêtes concurrentes", async () => {281    const before = dev.modem.length282    const a = await send({ to: TO, text: "idem" }, key, { "idempotency-key": "idem-1" })283    const b = await send({ to: TO, text: "idem" }, key, { "idempotency-key": "idem-1" })284    assert.equal(a.status, 201); assert.equal(b.status, 200)285    assert.equal(b.body.id, a.body.id); assert.equal(b.headers.get("idempotent-replayed"), "true")286    const c = await send({ to: TO, text: "autre texte" }, key, { "idempotency-key": "idem-1" })287    assert.equal(c.status, 409); assert.equal(c.body.error.code, "idempotency_conflict")288    const many = await Promise.all(Array.from({ length: 8 }, () => send({ to: TO, text: "concurrent" }, key, { "idempotency-key": "idem-2" })))289    assert.equal(new Set(many.map(m => m.body.id)).size, 1, JSON.stringify(many.map(m => m.body)))290    assert.equal(many.filter(m => m.status === 201).length, 1)291    await waitStatus(a.body.id, "DELIVERED"); await waitStatus(many[0].body.id, "DELIVERED")292    assert.equal(dev.modem.length - before, 2, "exactement deux remises au modem")293    // une autre application peut réutiliser la même clé d'idempotence sans collision294    const other = await newApp("autre-app")295    const d = await send({ to: TO, text: "idem" }, other.key, { "idempotency-key": "idem-1" })296    assert.equal(d.status, 201); assert.notEqual(d.body.id, a.body.id)297    await waitStatus(d.body.id, "DELIVERED")298  })299300  test("cloisonnement : une application ne voit pas les messages d'une autre", async () => {301    const mine = await send({ to: TO, text: "privé" })302    const other = await newApp("curieuse")303    assert.equal((await call("GET", `/v1/messages/${mine.body.id}`, { key: other.key })).status, 404)304    assert.equal((await call("POST", `/v1/messages/${mine.body.id}/cancel`, { key: other.key, body: {} })).status, 404)305    assert.equal((await call("GET", "/v1/messages", { key: other.key })).body.data.length, 0)306    await waitStatus(mine.body.id, "DELIVERED")307  })308309  test("SMS multiparties et Unicode : estimation des segments", async () => {310    const long = await send({ to: TO, text: "a".repeat(200) })311    assert.equal(long.body.segments, 2); assert.equal(long.body.encoding, "gsm7")312    const uni = await send({ to: TO, text: "Ça va ? 😀 " + "é".repeat(70) })313    assert.equal(uni.body.encoding, "ucs2"); assert.equal(uni.body.segments, 2)314    const euro = await send({ to: TO, text: "€".repeat(81) })          // caractères d'extension GSM : 2 septets chacun315    assert.equal(euro.body.encoding, "gsm7"); assert.equal(euro.body.segments, 2)316    await waitStatus(long.body.id, "DELIVERED"); await waitStatus(uni.body.id, "DELIVERED"); await waitStatus(euro.body.id, "DELIVERED")317    const [d] = await sql`select count(*)::int as n from message_segments where message_id = ${long.body.id} and status = 'delivered'`318    assert.equal(d.n, 2, "un rapport de livraison par partie")319  })320321  test("soumis sans rapport de livraison : reste « submitted », jamais « delivered »", async () => {322    dev.deliver = false323    const r = await send({ to: TO, text: "sans accusé" })324    await waitStatus(r.body.id, "SUBMITTED")325    await sleep(300)326    assert.equal(await status(r.body.id), "SUBMITTED")327    dev.deliver = true328  })329330  test("échec rapporté par l'appareil → failed avec code d'erreur, webhook sms.failed", async () => {331    sink.hits = []; dev.mode = "fail"332    const r = await send({ to: TO, text: "échec" })333    await waitStatus(r.body.id, "FAILED")334    const g = await call("GET", `/v1/messages/${r.body.id}`, { key })335    assert.equal(g.body.error.code, "no_service"); assert.equal(g.body.error.detail, "RESULT_ERROR_NO_SERVICE")336    await until(() => sink.hits.some(h => h.json.event === "sms.failed"), "webhook sms.failed")337    dev.mode = "ok"338  })339340  test("annulation : possible avant transmission, refusée après", async () => {341    await dev.close()342    await until(async () => !(await sql`select online from devices where id = 'android-01'`)[0].online, "appareil hors ligne")343    const r = await send({ to: TO, text: "à annuler" })344    assert.equal(r.body.status, "queued")345    assert.equal((await call("GET", "/v1/queue", { key })).body.pending, 1)346    const c = await call("POST", `/v1/messages/${r.body.id}/cancel`, { key, body: {} })347    assert.equal(c.status, 200); assert.equal(c.body.status, "cancelled")348    assert.equal((await call("POST", `/v1/messages/${r.body.id}/cancel`, { key, body: {} })).status, 409)349    await dev.connect()350    await sleep(300)351    assert.ok(!dev.modem.some(m => m.text === "à annuler"), "un message annulé n'est jamais transmis")352    const d = await send({ to: TO, text: "déjà parti" })353    await waitStatus(d.body.id, "DELIVERED")354    const c2 = await call("POST", `/v1/messages/${d.body.id}/cancel`, { key, body: {} })355    assert.equal(c2.status, 409); assert.equal(c2.body.error.code, "not_cancellable")356  })357})358359describe("robustesse", () => {360  test("file persistante : survit à l'arrêt brutal du serveur, livrée à la reconnexion", async () => {361    await dev.close()362    const r = await send({ to: TO, text: "persiste" })363    assert.equal(r.body.status, "queued")364    await stopServer("SIGKILL")365    await startServer()366    assert.equal(await status(r.body.id), "QUEUED")367    assert.equal((await sql`select online from devices where id = 'android-01'`)[0].online, false, "aucun appareil n'est en ligne après un redémarrage")368    await dev.connect()369    await waitStatus(r.body.id, "DELIVERED")370    assert.equal(dev.modem.filter(m => m.text === "persiste").length, 1)371  })372373  test("coupure après acceptation : la même commande est reproposée, l'appareil ne l'envoie qu'une fois", async () => {374    dev.mode = "accept_only"375    const r = await send({ to: TO, text: "reprise" })376    await waitStatus(r.body.id, "ACCEPTED")377    const first = dev.frames.filter(f => f.type === "sms.send.request" && f.data.message_id === r.body.id)378    await dev.close()379    dev.mode = "ok"380    await dev.connect()381    await waitStatus(r.body.id, "DELIVERED")382    const all = dev.frames.filter(f => f.type === "sms.send.request" && f.data.message_id === r.body.id)383    assert.equal(all.length, 2)384    assert.equal(all[1].data.command_id, first[0].data.command_id, "même command_id : jamais de seconde commande pour un même message")385    assert.equal(dev.modem.filter(m => m.text === "reprise").length, 1)386  })387388  test("événements perdus pendant la coupure : renvoyés depuis la boîte d'envoi de l'appareil, traités une seule fois", async () => {389    const r = await send({ to: TO, text: "boîte d'envoi" })390    await waitStatus(r.body.id, "DELIVERED")391    const before = (await sql`select count(*)::int as n from message_events where message_id = ${r.body.id}`)[0].n392    // l'appareil rejoue un événement déjà acquitté (même id) : aucun effet393    const [ev] = await sql`select event_id from device_events where device_id = 'android-01' and type = 'sms.send.submitted' order by received_at desc limit 1`394    const cmd = dev.frames.filter(f => f.type === "sms.send.request" && f.data.message_id === r.body.id)[0].data395    dev.emit("sms.send.submitted", { command_id: cmd.command_id, message_id: r.body.id, parts: 1 }, ev.event_id)396    await until(() => dev.outbox.length === 0, "rejeu acquitté")397    assert.equal((await sql`select count(*)::int as n from message_events where message_id = ${r.body.id}`)[0].n, before)398    // événement en retard, dans le désordre (nouvel id) : consigné mais sans recul d'état399    dev.emit("sms.send.accepted", { command_id: cmd.command_id, message_id: r.body.id })400    await until(() => dev.outbox.length === 0, "événement tardif acquitté")401    assert.equal(await status(r.body.id), "DELIVERED")402    const [ign] = await sql`select detail from message_events where message_id = ${r.body.id} order by id desc limit 1`403    assert.equal(ign.detail.ignored, true)404  })405406  test("interruption pendant la remise au modem → unknown, jamais de renvoi automatique", async () => {407    sink.hits = []; dev.mode = "stall_in_submitting"408    const r = await send({ to: TO, text: "ambigu" })409    await waitStatus(r.body.id, "SUBMITTING")410    await dev.close()                      // l'appareil « meurt » entre l'appel au modem et le résultat411    dev.mode = "ok"412    await dev.connect()                    // à la reprise, son journal dit « submitting » → il déclare l'issue inconnue413    await waitStatus(r.body.id, "UNKNOWN")414    assert.equal(dev.modem.filter(m => m.text === "ambigu").length, 1, "aucune seconde remise au modem")415    assert.equal((await sql`select count(*)::int as n from message_queue where message_id = ${r.body.id}`)[0].n, 0, "retiré de la file : plus jamais proposé")416    await dev.close(); await dev.connect(); await sleep(400)417    assert.equal(dev.frames.filter(f => f.type === "sms.send.request" && f.data.message_id === r.body.id).length, 2)418    assert.equal(dev.modem.filter(m => m.text === "ambigu").length, 1)419    const g = await call("GET", `/v1/messages/${r.body.id}`, { key })420    assert.equal(g.body.status, "unknown"); assert.equal(g.body.error.code, "unknown_outcome")421    await until(() => sink.hits.some(h => h.json.event === "sms.unknown"), "webhook sms.unknown")422    // preuve tardive : un rapport de livraison peut encore lever l'ambiguïté423    const cmd = dev.frames.find(f => f.type === "sms.send.request" && f.data.message_id === r.body.id).data424    dev.emit("sms.delivery.confirmed", { command_id: cmd.command_id, message_id: r.body.id, part: 1, parts: 1, status: "delivered" })425    await waitStatus(r.body.id, "DELIVERED")426  })427428  test("expiration : jamais transmis après le délai ; l'appareil refuse aussi une commande périmée", async () => {429    await dev.close()430    const r = await send({ to: TO, text: "trop tard", ttl_seconds: 60 })431    await sql`update messages set expires_at = now() - interval '1 second' where id = ${r.body.id}`432    await dev.connect(); await sleep(300)433    assert.ok(!dev.modem.some(m => m.text === "trop tard"))434    await stopServer(); await startServer()      // le balayage s'exécute au démarrage435    await waitStatus(r.body.id, "EXPIRED")436    await dev.connect()437    // commande transmise puis périmée avant traitement côté appareil438    dev.mode = "accept_only"439    const s = await send({ to: TO, text: "périmé sur l'appareil" })440    await waitStatus(s.body.id, "ACCEPTED")441    await sql`update messages set expires_at = now() - interval '1 second' where id = ${s.body.id}`442    await dev.close(); dev.mode = "ok"; await dev.connect()443    await waitStatus(s.body.id, "EXPIRED")444    assert.ok(!dev.modem.some(m => m.text === "périmé sur l'appareil"))445  })446447  test("un appareil ne peut pas agir sur les commandes d'un autre", async () => {448    const d2 = new FakeDevice()449    await pairNew(d2, "Second appareil")450    assert.equal(d2.deviceId, "android-02")451    d2.sims = [{ ...d2.sims[0], number: "+14185550125", carrier_name: "Autre" }]452    await d2.connect()453    await until(() => d2.outbox.length === 0, "inventaire SIM acquitté")454    dev.mode = "accept_only"455    const r = await send({ to: TO, text: "protégé", sim_id: "sim-1" })456    await waitStatus(r.body.id, "ACCEPTED")457    const cmd = dev.frames.find(f => f.type === "sms.send.request" && f.data.message_id === r.body.id).data458    d2.emit("sms.send.failed", { command_id: cmd.command_id, message_id: r.body.id, code: "generic_failure", definitive: true })459    await until(() => d2.outbox.length === 0, "événement acquitté")460    assert.equal(await status(r.body.id), "ACCEPTED")461    dev.mode = "ok"; dev.process(cmd)462    await waitStatus(r.body.id, "DELIVERED")463    await d2.close()464  })465466  test("heartbeat : réponse du serveur ; connexion muette coupée par le chien de garde", async () => {467    dev.heartbeat()468    await until(() => dev.frames.some(f => f.type === "server.heartbeat"), "server.heartbeat")469    const mute = new FakeDevice(); await pairNew(mute, "Muet"); await mute.connect({ status: false })470    await until(() => mute.closeCode !== null, "fermeture par le chien de garde", 20_000)471    await until(async () => !(await sql`select online from devices where id = ${mute.deviceId}`)[0].online, "appareil marqué hors ligne")472    await call("POST", `/api/admin/devices/${mute.deviceId}/revoke`, { cookie: admin, body: {} })473    await assert.rejects(mute.connect())474    assert.equal(mute.closeCode, 4403, "appareil révoqué")475    // le chien de garde a pu couper l'appareil principal resté silencieux : il se reconnecte476    if (!dev.authenticated) await dev.connect()477  })478479  test("nouvelle session du même appareil : l'ancienne est fermée (4409)", async () => {480    const twin = new FakeDevice(); twin.keys = dev.keys; twin.deviceId = dev.deviceId481    await twin.connect()482    await until(() => dev.closeCode === 4409, "ancienne session remplacée")483    await twin.close()484    await dev.connect()485  })486})487488describe("réception", () => {489  test("SMS entrant : boîte de réception, conversation, webhook avec contenu ; rejeu sans doublon", async () => {490    sink.hits = []491    const id = dev.receive(TO, "Réponse du destinataire 😀")492    await until(() => dev.outbox.length === 0, "sms.received acquitté")493    dev.receive(TO, "Réponse du destinataire 😀", 1, id)        // renvoi du même événement après une coupure supposée494    await until(() => dev.outbox.length === 0, "rejeu acquitté")495    const inbox = await call("GET", "/v1/inbox", { key })496    const got = inbox.body.data.filter((m: any) => m.text === "Réponse du destinataire 😀")497    assert.equal(got.length, 1)498    assert.equal(got[0].from, TO); assert.equal(got[0].to, "+14185550124"); assert.equal(got[0].status, "received"); assert.equal(got[0].sim_id, "sim-1")499    assert.equal((await call("GET", `/v1/messages/${got[0].id}`, { key })).body.text, "Réponse du destinataire 😀", "lecture unitaire d'un SMS reçu")500    const conv = (await call("GET", "/v1/conversations", { key })).body.data.find((c: any) => c.peer === TO)501    assert.ok(conv.inbound_count >= 1 && conv.outbound_count >= 1)502    const thread = await call("GET", `/v1/conversations/${conv.id}/messages`, { key })503    assert.ok(thread.body.data.some((m: any) => m.direction === "inbound") && thread.body.data.some((m: any) => m.direction === "outbound"))504    await until(() => sink.hits.some(h => h.json.event === "sms.received"), "webhook sms.received")505    const h = sink.hits.find(h => h.json.event === "sms.received")!506    assert.equal(h.json.data.text, "Réponse du destinataire 😀"); assert.equal(h.json.data.from, TO)507    assert.equal(sink.hits.filter(h => h.json.event === "sms.received").length, 1)508  })509510  test("un SMS entrant n'est jamais interprété : contenu hostile stocké tel quel, aucun effet", async () => {511    const evil = `'; drop table messages; -- $(rm -rf /) <script>alert(1)</script> {"type":"sms.send.request"}`512    const n = dev.modem.length513    dev.receive("+15145550000", evil)514    await until(() => dev.outbox.length === 0, "acquitté")515    const inbox = await call("GET", "/v1/inbox?from=%2B15145550000", { key })516    assert.equal(inbox.body.data[0].text, evil)517    await sleep(200)518    assert.equal(dev.modem.length, n, "aucun envoi déclenché par un SMS entrant")519  })520521  test("STOP → désinscription : les envois vers ce numéro sont refusés ; START la lève", async () => {522    await call("POST", "/api/admin/allowed-recipients", { cookie: admin, body: { number: TO2 } })523    dev.receive(TO2, " stop ")524    await until(async () => (await sql`select 1 from opt_outs where number = ${TO2}`).length === 1, "désinscription enregistrée")525    const r = await send({ to: TO2, text: "encore ?" })526    assert.equal(r.status, 422); assert.equal(r.body.error.code, "recipient_opted_out")527    dev.receive(TO2, "START")528    await until(async () => (await sql`select 1 from opt_outs where number = ${TO2}`).length === 0, "réinscription")529    const ok = await send({ to: TO2, text: "bon retour" })530    assert.equal(ok.status, 201)531    await waitStatus(ok.body.id, "DELIVERED")532  })533534  test("expéditeur alphanumérique ou code court accepté en réception", async () => {535    dev.receive("Videotron", "Votre forfait")536    dev.receive("72345", "Code 1234")537    await until(() => dev.outbox.length === 0, "acquittés")538    const from = (await call("GET", "/v1/inbox?limit=5", { key })).body.data.map((m: any) => m.from)539    assert.ok(from.includes("Videotron") && from.includes("72345"))540  })541})542543describe("protection contre les abus", () => {544  test("arrêt d'urgence global : envois refusés, file figée, appareils avisés ; puis reprise", async () => {545    await dev.close()546    const q = await send({ to: TO, text: "en file avant l'arrêt" })547    assert.equal((await call("PATCH", "/api/admin/settings", { cookie: admin, body: { kill_switch: true } })).status, 200)548    const r = await send({ to: TO, text: "x" })549    assert.equal(r.status, 503); assert.equal(r.body.error.code, "kill_switch_active")550    await dev.connect(); await sleep(400)551    assert.equal(dev.config.gateway_enabled, false)552    assert.equal(await status(q.body.id), "QUEUED", "rien n'est transmis pendant l'arrêt")553    await call("PATCH", "/api/admin/settings", { cookie: admin, body: { kill_switch: false } })554    await waitStatus(q.body.id, "DELIVERED")555    assert.equal(dev.config.gateway_enabled, true)556    const logs = await call("GET", "/api/admin/audit-logs?action=kill_switch", { cookie: admin })557    assert.deepEqual(logs.body.data.map((l: any) => l.action), ["kill_switch.released", "kill_switch.activated"])558    assert.equal(logs.body.data[0].actor, "simon")559  })560561  test("limite de débit par application", async () => {562    const a = await newApp("bavarde", { rate_per_minute: 4 })563    const rs = []564    for (let i = 0; i < 6; i++) rs.push((await call("GET", "/v1/usage", { key: a.key })).status)565    assert.ok(rs.includes(429), rs.join(","))566    assert.equal(rs[0], 200)567    const limited = await call("GET", "/v1/usage", { key: a.key })568    assert.equal(limited.status, 429); assert.equal(limited.headers.get("retry-after"), "15")569  })570571  test("quota journalier par application et limite journalière par SIM", async () => {572    const a = await newApp("quota", { daily_quota: 2 })573    assert.equal((await send({ to: TO, text: "1" }, a.key)).status, 201)574    assert.equal((await send({ to: TO, text: "2" }, a.key)).status, 201)575    const r = await send({ to: TO, text: "3" }, a.key)576    assert.equal(r.status, 429); assert.equal(r.body.error.code, "quota_exceeded")577    const u = await call("GET", "/v1/usage", { key: a.key })578    assert.equal(u.body.quota.used_today, 2); assert.equal(u.body.totals.outbound_created, 2)579580    const [{ n }] = await sql`select coalesce(sum(value), 0)::int as n from usage_metrics where sim_id = 'sim-1' and metric = 'outbound_created'`581    await call("PATCH", "/api/admin/sims/sim-1", { cookie: admin, body: { daily_limit: n } })582    const s = await send({ to: TO, text: "au-delà" })583    assert.equal(s.status, 429); assert.equal(s.body.error.code, "sim_limit_exceeded")584    await call("PATCH", "/api/admin/sims/sim-1", { cookie: admin, body: { daily_limit: 1000 } })585  })586587  test("consentement exigé par application", async () => {588    const a = await newApp("marketing", { require_consent: true })589    const r = await send({ to: TO, text: "promo" }, a.key)590    assert.equal(r.status, 403); assert.equal(r.body.error.code, "consent_required")591    await call("POST", "/api/admin/consents", { cookie: admin, body: { number: TO, application_id: a.id, source: "formulaire" } })592    assert.equal((await send({ to: TO, text: "promo" }, a.key)).status, 201)593  })594595  test("agent IA : approbation humaine avant tout envoi", async () => {596    const a = await call("POST", "/api/admin/applications", { cookie: admin, body: { name: "agent-ia", kind: "agent" } })597    assert.equal(a.body.approval_required, true); assert.equal(a.body.daily_quota, 20)598    const k = await call("POST", `/api/admin/applications/${a.body.id}/keys`, { cookie: admin, body: { scopes: ["messages:send", "messages:read"] } })599    const r = await send({ to: TO, text: "proposé par un agent" }, k.body.key)600    assert.equal(r.status, 201); assert.equal(r.body.status, "held")601    await sleep(300)602    assert.ok(!dev.modem.some(m => m.text === "proposé par un agent"))603    assert.equal((await call("POST", `/api/admin/messages/${r.body.id}/approve`, { cookie: admin, body: {} })).status, 200)604    await waitStatus(r.body.id, "DELIVERED")605  })606607  test("webhooks : destinations privées refusées (SSRF), nouvelles tentatives contrôlées", async () => {608    for (const url of ["http://example.com/h", "https://10.0.0.5/h", "https://localhost/h", "https://192.168.2.80:8000/x", "https://[::1]/h", "https://user:pw@example.com/h", "ftp://example.com/h", "https://metadata.internal/h"]) {609      const r = await call("POST", "/v1/webhooks", { key, body: { url, events: ["sms.received"] } })610      assert.equal(r.status, 422, url)611    }612    assert.equal((await call("POST", "/v1/webhooks", { key, body: { url: sink.url, events: ["sms.nimporte"] } })).status, 422)613    sink.hits = []; sink.failNext = 2614    const r = await send({ to: TO, text: "avec reprises" })615    await waitStatus(r.body.id, "DELIVERED")616    await until(() => sink.hits.filter(h => h.json.data.id === r.body.id).length >= 2, "livraisons après échecs", 15_000)617    const d = await sql`select attempts, status from webhook_deliveries where attempts > 1`618    assert.ok(d.length >= 1 && d.every(x => x.status === "delivered"))619    const ids = sink.hits.map(h => h.headers["x-maclustr-delivery"])620    assert.equal(new Set(ids).size, ids.length, "une livraison réussie n'est pas rejouée")621  })622})623624describe("multi-appareils et routage", () => {625  const d3 = new FakeDevice()626  test("deux SIM disponibles : l'expéditeur n'est jamais choisi au hasard", async () => {627    await pairNew(d3, "Troisième")628    d3.sims = [{ ...d3.sims[0], number: "+14185550177", carrier_name: "Opérateur B", is_embedded: true as any }]629    await d3.connect()630    await until(() => d3.outbox.length === 0, "inventaire SIM acquitté")631    const sims = (await call("GET", "/api/admin/sims", { cookie: admin })).body.data632    const simB = sims.find((s: any) => s.number === "+14185550177")633    assert.equal(simB.type, "esim")634    await call("PATCH", `/api/admin/sims/${simB.id}`, { cookie: admin, body: { send_enabled: true } })635    const fresh = "+14185550142"636    await call("POST", "/api/admin/allowed-recipients", { cookie: admin, body: { number: fresh } })637    const amb = await send({ to: fresh, text: "qui envoie ?" })638    assert.equal(amb.status, 422); assert.equal(amb.body.error.code, "sender_required")639    // choix explicite par numéro expéditeur, par SIM, par appareil640    const byFrom = await send({ to: fresh, text: "depuis B", from: "+14185550177" })641    assert.equal(byFrom.body.sim_id, simB.id); assert.equal(byFrom.body.device_id, d3.deviceId)642    await waitStatus(byFrom.body.id, "DELIVERED")643    assert.equal(d3.modem.at(-1)!.text, "depuis B")644    // conversation existante : même expéditeur sans le redemander645    const sticky = await send({ to: fresh, text: "suite" })646    assert.equal(sticky.body.sim_id, simB.id)647    // conversation historique avec sim-1 : reste sur sim-1648    assert.equal((await send({ to: TO, text: "fidèle" })).body.sim_id, "sim-1")649    assert.equal((await send({ to: fresh, text: "x", sim_id: "sim-1", from: "+14185550177" })).body.error.code, "sender_mismatch")650    assert.equal((await send({ to: fresh, text: "x", device_id: "android-01", sim_id: simB.id })).body.error.code, "sim_device_mismatch")651    assert.equal((await send({ to: fresh, text: "x", from: "+14185559999" })).body.error.code, "sender_not_found")652653    // application limitée à une SIM654    const lim = await newApp("limitée", { allowed_sim_ids: ["sim-1"] })655    const refused = await send({ to: fresh, text: "x", sim_id: simB.id }, lim.key)656    assert.equal(refused.status, 403); assert.equal(refused.body.error.code, "sim_not_permitted")657    assert.equal((await call("GET", "/v1/devices", { key: lim.key })).body.data.length, 1)658    assert.deepEqual((await call("GET", "/v1/numbers", { key: lim.key })).body.data.map((n: any) => n.number), ["+14185550124"])659    d3.receive("+15145550333", "pour B seulement")660    await until(() => d3.outbox.length === 0, "acquitté")661    assert.ok(!(await call("GET", "/v1/inbox", { key: lim.key })).body.data.some((m: any) => m.text === "pour B seulement"), "réception cloisonnée par SIM")662    const [hidden] = await sql`select id from messages where direction = 'inbound' and from_number = '+15145550333'`663    assert.equal((await call("GET", `/v1/messages/${hidden.id}`, { key: lim.key })).status, 404, "lecture unitaire cloisonnée par SIM")664    assert.equal((await call("GET", `/v1/messages/${hidden.id}`, { key })).status, 200)665  })666667  test("appareil hors ligne : le message attend, il n'est pas rerouté vers une autre SIM", async () => {668    await d3.close()669    const r = await send({ to: "+14185550142", text: "attend B" })670    await sleep(400)671    assert.equal(await status(r.body.id), "QUEUED")672    assert.ok(!dev.modem.some(m => m.text === "attend B"))673    await d3.connect()674    await waitStatus(r.body.id, "DELIVERED")675  })676677  test("SIM retirée : incident, webhook sim.unavailable, envois refusés", async () => {678    const wh = await call("POST", "/api/admin/webhooks", { cookie: admin, body: { url: sink.url, events: ["sim.unavailable", "device.offline", "device.online"] } })679    assert.equal(wh.status, 201)680    sink.hits = []681    d3.emit("device.sim.updated", { sims: [] })682    await until(() => sink.hits.some(h => h.json.event === "sim.unavailable"), "webhook sim.unavailable")683    const r = await send({ to: "+14185550142", text: "x", from: "+14185550177" })684    assert.equal(r.status, 422); assert.equal(r.body.error.code, "sim_unavailable")685    await d3.close()686    await until(() => sink.hits.some(h => h.json.event === "device.offline"), "webhook device.offline")687    const d = await call("GET", `/api/admin/devices/${d3.deviceId}`, { cookie: admin })688    assert.ok(d.body.incidents.some((i: any) => i.kind === "sim.unavailable") && d.body.incidents.some((i: any) => i.kind === "device.offline"))689  })690691  test("autorisation SMS absente sur le téléphone : signalée, la file attend ; identifiants jamais réattribués", async () => {692    dev.emit("device.status", dev.status({ permissions: { send_sms: false, receive_sms: false, read_phone_state: true, post_notifications: true } }))693    await until(() => dev.outbox.length === 0, "statut acquitté")694    const d = (await call("GET", "/api/admin/devices", { cookie: admin })).body.data.find((x: any) => x.id === "android-01")695    assert.equal(d.sms_permissions_missing, true); assert.equal(d.available, false)696    const r = await send({ to: TO, text: "sans autorisation" })697    await sleep(400)698    assert.equal(await status(r.body.id), "QUEUED")699    dev.emit("device.status", dev.status())700    await waitStatus(r.body.id, "DELIVERED")701    const g = await call("GET", `/v1/messages/${r.body.id}`, { key })702    assert.ok(Date.parse(g.body.submitted_at) >= Date.parse(g.body.created_at), "horodatages à l'horloge du serveur")703    // un appareil supprimé ne libère pas son identifiant704    const tmp = new FakeDevice(); await pairNew(tmp, "Jetable")705    const gone = tmp.deviceId706    await sql`delete from devices where id = ${gone}`707    const next = new FakeDevice(); await pairNew(next, "Suivant")708    assert.notEqual(next.deviceId, gone); assert.ok(Number(next.deviceId.slice(8)) > Number(gone.slice(8)))709    await sql`delete from devices where id = ${next.deviceId}`710  })711712  test("mode maintenance d'un appareil : la file attend", async () => {713    await call("PATCH", "/api/admin/devices/android-01", { cookie: admin, body: { maintenance: true } })714    await until(() => dev.config?.maintenance === true, "configuration poussée")715    const r = await send({ to: TO, text: "pendant la maintenance" })716    await sleep(400)717    assert.equal(await status(r.body.id), "QUEUED")718    await call("PATCH", "/api/admin/devices/android-01", { cookie: admin, body: { maintenance: false } })719    await waitStatus(r.body.id, "DELIVERED")720  })721})722723describe("vérification de numéro par code (authentification par SMS)", () => {724  let vkey = "", vapp = ""725  const start = (body: any, k = vkey) => call("POST", "/v1/verifications", { key: k, body })726  const check = (id: string, code: string, k = vkey) => call("POST", `/v1/verifications/${id}/check`, { key: k, body: { code } })727  const codeFor = (to: string) => /(\d{6,8})/.exec(dev.modem.filter(m => m.to === to).at(-1)!.text)![1]728  const fresh = async (n: string) => { await call("POST", "/api/admin/allowed-recipients", { cookie: admin, body: { number: n } }); return n }729730  test("scope dédié ; le code part par SMS, n'est jamais renvoyé ni stocké ni relisible", async () => {731    assert.equal((await start({ to: TO }, key)).body.error.code, "insufficient_scope")732    const a = await newApp("Mon App", {}, ["verify:manage", "messages:read"])733    vkey = a.key; vapp = a.id734    const to = await fresh("+14185550161")735    const r = await start({ to, sim_id: "sim-1" })736    assert.equal(r.status, 201, JSON.stringify(r.body))737    assert.equal(r.body.status, "pending"); assert.equal(r.body.attempts_remaining, 5)738    assert.ok(!/\d{6}/.test(JSON.stringify({ ...r.body, id: "", message_id: "", to: "", created_at: "", expires_at: "" })), "aucun code dans la réponse")739    await waitStatus(r.body.message_id, "DELIVERED")740    const sms = dev.modem.at(-1)!741    assert.match(sms.text, /^Mon App : votre code de vérification est \d{6}\. Il expire dans 10 min\. Ne le partagez avec personne\.$/)742    const code = codeFor(to)743    // ni l'API, ni le tableau de bord, ni la base ne redonnent le code744    assert.equal((await call("GET", `/v1/messages/${r.body.message_id}`, { key: vkey })).body.text, null)745    const adm = await call("GET", `/api/admin/messages/${r.body.message_id}`, { cookie: admin })746    assert.equal(adm.body.text, null); assert.equal(adm.body.sensitive, true)747    assert.ok(!JSON.stringify(await sql`select * from verifications`).includes(code))748    assert.equal((await call("GET", `/v1/verifications/${r.body.id}`, { key: vkey })).body.message_status, "delivered")749750    // réessai réseau avec la même Idempotency-Key : même vérification, aucun second SMS, pas de refus « trop tôt »751    const idem = await fresh("+14185550166"), before = dev.modem.length752    const i1 = await call("POST", "/v1/verifications", { key: vkey, body: { to: idem, sim_id: "sim-1" }, headers: { "idempotency-key": "connexion-42" } })753    const i2 = await call("POST", "/v1/verifications", { key: vkey, body: { to: idem, sim_id: "sim-1" }, headers: { "idempotency-key": "connexion-42" } })754    assert.equal(i1.status, 201); assert.equal(i2.status, 200); assert.equal(i2.body.id, i1.body.id); assert.equal(i2.headers.get("idempotent-replayed"), "true")755    await waitStatus(i1.body.message_id, "DELIVERED")756    assert.equal(dev.modem.length - before, 1)757    assert.equal((await call("POST", "/v1/verifications", { key: vkey, body: { to, sim_id: "sim-1" }, headers: { "idempotency-key": "connexion-42" } })).status, 409)758759    const bad = await check(r.body.id, "000000")760    assert.equal(bad.body.valid, code === "000000"); if (code !== "000000") assert.equal(bad.body.attempts_remaining, 4)761    const ok = await check(r.body.id, ` ${code.slice(0, 3)} ${code.slice(3)} `)          // espaces tolérés762    assert.equal(ok.body.valid, true); assert.equal(ok.body.status, "approved")763    const again = await check(r.body.id, code)764    assert.equal(again.body.valid, false, "usage unique")765    assert.equal((await sql`select text_enc from messages where id = ${r.body.message_id}`)[0].text_enc, null, "texte du SMS effacé après usage")766    assert.equal((await check(r.body.id, code, key)).status, 403)767    const other = await newApp("Autre vérif", {}, ["verify:manage"])768    assert.equal((await check(r.body.id, code, other.key)).status, 404, "cloisonné par application")769  })770771  test("cinq essais au plus, puis échec définitif même avec le bon code", async () => {772    const to = await fresh("+14185550162")773    const r = await start({ to, sim_id: "sim-1", locale: "en", brand: "Lou-Ka" })774    await waitStatus(r.body.message_id, "DELIVERED")775    assert.match(dev.modem.at(-1)!.text, /^Lou-Ka: your verification code is \d{6}\./)776    const code = codeFor(to), wrong = code === "111111" ? "222222" : "111111"777    for (let i = 0; i < 4; i++) assert.equal((await check(r.body.id, wrong)).body.status, "pending")778    const last = await check(r.body.id, wrong)779    assert.equal(last.body.status, "failed"); assert.equal(last.body.attempts_remaining, 0)780    assert.equal((await check(r.body.id, code)).body.valid, false)781  })782783  test("expiration, renvoi (l'ancien code est annulé), limites par numéro", async () => {784    const to = await fresh("+14185550163")785    const a = await start({ to, sim_id: "sim-1" })786    await waitStatus(a.body.message_id, "DELIVERED")787    const codeA = codeFor(to)788    const soon = await start({ to, sim_id: "sim-1" })789    assert.equal(soon.status, 429); assert.equal(soon.body.error.code, "verification_too_soon"); assert.ok(Number(soon.headers.get("retry-after")) <= 30)790    await sql`update verifications set created_at = created_at - interval '2 minutes' where to_number = ${to}`791    const b = await start({ to, sim_id: "sim-1" })792    assert.equal(b.status, 201)793    await waitStatus(b.body.message_id, "DELIVERED")794    assert.equal((await check(a.body.id, codeA)).body.status, "cancelled", "un seul code valide à la fois")795    await sql`update verifications set expires_at = now() - interval '1 second' where id = ${b.body.id}`796    const exp = await check(b.body.id, codeFor(to))797    assert.equal(exp.body.valid, false); assert.equal(exp.body.status, "expired")798    for (let i = 0; i < 3; i++) { await sql`update verifications set created_at = created_at - interval '2 minutes' where to_number = ${to}`; assert.equal((await start({ to, sim_id: "sim-1" })).status, 201) }799    await sql`update verifications set created_at = created_at - interval '2 minutes' where to_number = ${to}`800    const cap = await start({ to, sim_id: "sim-1" })801    assert.equal(cap.status, 429); assert.equal(cap.body.error.code, "verification_rate_limited")802  })803804  test("mêmes garde-fous que tout envoi : liste autorisée, désinscription, arrêt d'urgence ; rien n'est créé en cas de refus", async () => {805    const n = (await sql`select count(*)::int as n from verifications`)[0].n806    assert.equal((await start({ to: "+14185550164", sim_id: "sim-1" })).body.error.code, "recipient_not_allowed")807    assert.equal((await start({ to: "12345", sim_id: "sim-1" })).status, 422)808    const to = await fresh("+14185550165")809    await call("POST", "/api/admin/opt-outs", { cookie: admin, body: { number: to } })810    assert.equal((await start({ to, sim_id: "sim-1" })).body.error.code, "recipient_opted_out")811    assert.equal((await sql`select count(*)::int as n from verifications`)[0].n, n)812    void vapp813  })814})815816describe("tableau de bord et exploitation", () => {817  test("vue d'ensemble, file, statistiques, journal d'audit, diagnostic", async () => {818    const o = await call("GET", "/api/admin/overview", { cookie: admin })819    assert.equal(o.status, 200)820    assert.equal(o.body.database.ok, true); assert.ok(o.body.devices.online >= 1); assert.ok(o.body.messages.sent_today > 10)821    assert.ok(o.body.messages.median_submit_latency_s >= 0)822    const an = await call("GET", "/api/admin/analytics", { cookie: admin })823    assert.ok(an.body.totals.outbound_created > 10 && an.body.totals.inbound >= 4 && an.body.by_application.length > 1)824    const audit = await call("GET", "/api/admin/audit-logs?limit=500", { cookie: admin })825    const actions = new Set(audit.body.data.map((l: any) => l.action))826    for (const a of ["admin.login", "application.created", "api_key.created", "api_key.revoked", "pairing_code.created", "device.paired", "device.revoked", "sim.updated", "settings.updated", "message.approved"]) assert.ok(actions.has(a) || a === "settings.updated", a)827    const dg = await call("POST", "/api/admin/devices/android-01/diagnostic", { cookie: admin, body: {} })828    await until(async () => (await sql`select completed_at from device_diagnostics where id = ${dg.body.request_id}`)[0].completed_at, "diagnostic complété")829  })830831  test("console d'envoi (administrateur) et pagination de l'historique", async () => {832    const r = await call("POST", "/api/admin/messages", { cookie: admin, body: { to: TO, text: "depuis la console" } })833    assert.equal(r.status, 201)834    await waitStatus(r.body.id, "DELIVERED")835    const p1 = await call("GET", "/api/admin/messages?limit=5", { cookie: admin })836    assert.equal(p1.body.data.length, 5); assert.equal(p1.body.has_more, true)837    const p2 = await call("GET", `/api/admin/messages?limit=5&cursor=${p1.body.next_cursor}`, { cookie: admin })838    assert.equal(new Set([...p1.body.data, ...p2.body.data].map((m: any) => m.id)).size, 10)839    const f = await call("GET", "/api/admin/messages?status=failed,expired&direction=outbound", { cookie: admin })840    assert.ok(f.body.data.length >= 2 && f.body.data.every((m: any) => ["failed", "expired"].includes(m.status)))841  })842843  test("rétention : le contenu ancien est effacé, les métadonnées restent", async () => {844    const [m] = await sql`select id from messages where status = 'DELIVERED' and text_enc is not null order by created_at limit 1`845    await sql`update messages set created_at = now() - interval '200 days' where id = ${m.id}`846    cli("retention")847    const [after] = await sql`select text_enc, status from messages where id = ${m.id}`848    assert.equal(after.text_enc, null); assert.equal(after.status, "DELIVERED")849    const g = await call("GET", `/api/admin/messages/${m.id}`, { cookie: admin })850    assert.equal(g.body.text, null); assert.equal(g.body.text_purged, true)851  })852853  test("téléchargement de l'APK : authentifié, lien temporaire à jeton", async () => {854    assert.equal((await call("GET", "/api/admin/android/download")).status, 401)855    assert.equal((await call("GET", "/dl/" + "x".repeat(32))).status, 404)856    assert.equal((await call("GET", "/api/admin/android", { cookie: admin })).body.available, false)   // aucun APK dans ce banc d'essai857  })858859  test("déconnexion : la session est détruite", async () => {860    assert.equal((await call("POST", "/api/auth/logout", { cookie: admin, body: {} })).status, 200)861    assert.equal((await call("GET", "/api/admin/overview", { cookie: admin })).status, 401)862  })863})864void ORIGIN; void appId865
Files main
Menu

Theme