SPB Git

Repository Public

mock-gateway.mjs 12.1 KB 182 lines javascript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr SMS Gateway8 * File             : android/tests/mock-gateway.mjs9 * Module           : android10 * 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// Development stand-in for the gateway, implementing docs/PROTOCOL.md v1 for emulator trials of the Android app.43// It verifies real ECDSA P-256 signatures. It is NOT the backend and proves nothing about cellular delivery.44//45//   node mock-gateway.mjs [port=8799]         state is kept in ./mock-state.json46//   emulator → http://10.0.2.2:<port>47//48// Control interface (localhost only):49//   GET  /ctl/state                     devices, connection, pairing code50//   GET  /ctl/log                       every frame received from the device (with duplicate counts)51//   POST /ctl/code                      new one-time pairing code52//   POST /ctl/send    {to,text,subscription_id,command_id?,expires_in_s?,delivery_report?}53//   POST /ctl/resend  {command_id}      same command again (the device must not send twice)54//   POST /ctl/config  {gateway_enabled?,maintenance?,min_send_interval_ms?,latest_app?}55//   POST /ctl/diag                      device.diagnostic.request56//   POST /ctl/drop                      close the socket (reconnection test)57//   POST /ctl/noack   {on:true|false}   stop acknowledging device events (outbox retention test)58//   POST /ctl/revoke                    revoke the device (close 4403)59import http from "node:http"60import crypto from "node:crypto"61import fs from "node:fs"62import { WebSocketServer } from "ws"6364const PORT = Number(process.argv[2] || 8799)65const STATE = new URL("./mock-state.json", import.meta.url)66const state = fs.existsSync(STATE) ? JSON.parse(fs.readFileSync(STATE, "utf8")) : { devices: {}, commands: {}, seq: 0 }67const save = () => fs.writeFileSync(STATE, JSON.stringify(state, null, 1))68const ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"69const newCode = () => Array.from({ length: 3 }, () => Array.from(crypto.randomBytes(4), b => ALPHABET[b % 32]).join("")).join("-")70let pairingCode = newCode()71const config = { gateway_enabled: true, maintenance: false, min_send_interval_ms: 3000, latest_app: { version: "1.0.0", build: 1, notes: "", sha256: "" } }72const log = []            // { at, type, id, data, dup }73const seen = new Map()    // event id -> count74let socket = null, socketDevice = null, noAck = false75const now = () => new Date().toISOString()76const id = p => p + "_" + crypto.randomBytes(9).toString("base64url")77const frame = (type, data = {}) => JSON.stringify({ type, id: id("srv"), ts: now(), data })78const NO_ACK = new Set(["ack", "server.hello", "device.hello", "device.authenticated", "device.heartbeat", "error"])7980function verify(publicKeyB64, message, signatureB64) {81  try {82    const key = crypto.createPublicKey({ key: Buffer.from(publicKeyB64, "base64"), format: "der", type: "spki" })83    if (key.asymmetricKeyType !== "ec" || key.asymmetricKeyDetails?.namedCurve !== "prime256v1") return false84    return crypto.verify("sha256", Buffer.from(message, "utf8"), { key, dsaEncoding: "der" }, Buffer.from(signatureB64, "base64"))85  } catch { return false }86}87const fresh = iso => Math.abs(Date.now() - Date.parse(iso)) < 5 * 60_00088const body = req => new Promise(r => { let b = ""; req.on("data", c => b += c); req.on("end", () => { try { r(b ? JSON.parse(b) : {}) } catch { r(null) } }) })89const json = (res, code, o) => { res.writeHead(code, { "content-type": "application/json" }); res.end(JSON.stringify(o)) }90const err = (res, status, code, message) => json(res, status, { error: { code, message } })91const simConfig = d => (d.sims || []).map((s, i) => ({ subscription_id: s.subscription_id, sim_id: `sim-${i + 1}`, enabled: true, number: s.number }))92const deviceConfig = d => ({ ...config, device_name: d.name, sims: simConfig(d) })9394const server = http.createServer(async (req, res) => {95  const url = new URL(req.url, "http://x")96  const local = ["127.0.0.1", "::1", "::ffff:127.0.0.1"].includes(req.socket.remoteAddress)97  if (req.method === "POST" && url.pathname === "/v1/device/pair") {98    const b = await body(req)99    if (!b || typeof b.code !== "string" || typeof b.public_key !== "string" || typeof b.name !== "string") return err(res, 400, "invalid_request", "champs manquants")100    if (b.code !== pairingCode) return err(res, 404, "pairing_code_invalid", "code inconnu, expiré ou déjà utilisé")101    try { crypto.createPublicKey({ key: Buffer.from(b.public_key, "base64"), format: "der", type: "spki" }) } catch { return err(res, 400, "invalid_request", "clé publique illisible") }102    pairingCode = newCode()                                   // one-time103    const deviceId = `android-${String(Object.keys(state.devices).length + 1).padStart(2, "0")}`104    state.devices[deviceId] = { name: b.name, public_key: b.public_key, model: b.model, revoked: false, sims: [] }; save()105    console.log(`[pair] ${deviceId} ${b.manufacturer} ${b.model} Android ${b.android_version} app ${b.app_version}`)106    return json(res, 201, { device_id: deviceId, name: b.name, ws_url: `ws://${req.headers.host}/ws/device`, server_time: now() })107  }108  if (req.method === "POST" && url.pathname === "/v1/device/app-download") {109    const b = await body(req); const d = b && state.devices[b.device_id]110    if (!d || !fresh(b.signed_at) || !verify(d.public_key, `maclustr-sms-device-app-download-v1\n${b.device_id}\n${b.signed_at}`, b.signature)) return err(res, 401, "unauthorized", "signature invalide")111    return json(res, 200, { url: `http://${req.headers.host}/dl/${id("tok")}`, version: config.latest_app.version, build: config.latest_app.build, sha256: "", expires_at: new Date(Date.now() + 600000).toISOString() })112  }113  if (!url.pathname.startsWith("/ctl/") || !local) return err(res, 404, "not_found", "")114  const b = req.method === "POST" ? (await body(req)) || {} : {}115  const deviceId = socketDevice || Object.keys(state.devices).at(-1)116  switch (url.pathname) {117    case "/ctl/state": return json(res, 200, { pairing_code: pairingCode, connected: socketDevice, devices: state.devices, commands: state.commands, config, noAck })118    case "/ctl/log": return json(res, 200, log)119    case "/ctl/code": pairingCode = newCode(); return json(res, 200, { pairing_code: pairingCode, uri: `maclustr-sms://pair?server=${encodeURIComponent(`http://10.0.2.2:${PORT}`)}&code=${pairingCode}` })120    case "/ctl/send": {121      const cmd = { command_id: b.command_id || id("cmd"), message_id: b.message_id || id("sms"), to: b.to, text: b.text, subscription_id: b.subscription_id ?? 1,122        expires_at: new Date(Date.now() + (b.expires_in_s ?? 600) * 1000).toISOString(), delivery_report: b.delivery_report ?? true }123      state.commands[cmd.command_id] = cmd; save()124      const sent = socket ? (socket.send(frame("sms.send.request", cmd)), true) : false125      return json(res, 200, { ...cmd, written_to_socket: sent })126    }127    case "/ctl/resend": {128      const cmd = state.commands[b.command_id]; if (!cmd) return err(res, 404, "not_found", "commande inconnue")129      const sent = socket ? (socket.send(frame("sms.send.request", cmd)), true) : false130      return json(res, 200, { ...cmd, written_to_socket: sent })131    }132    case "/ctl/config": Object.assign(config, b); if (socket && deviceId) socket.send(frame("device.config.updated", deviceConfig(state.devices[deviceId]))); return json(res, 200, config)133    case "/ctl/diag": if (socket) socket.send(frame("device.diagnostic.request", { request_id: id("diag") })); return json(res, 200, { sent: !!socket })134    case "/ctl/drop": socket?.terminate(); return json(res, 200, { dropped: true })135    case "/ctl/noack": noAck = !!b.on; return json(res, 200, { noAck })136    case "/ctl/revoke": if (deviceId) { state.devices[deviceId].revoked = true; save(); socket?.send(frame("error", { code: "device_revoked", message: "appareil révoqué" })); socket?.close(4403, "revoked") } return json(res, 200, { revoked: deviceId })137  }138  err(res, 404, "not_found", "")139})140141const wss = new WebSocketServer({ server, path: "/ws/device" })142wss.on("connection", ws => {143  const nonce = crypto.randomBytes(32).toString("base64url")144  let device = null145  const timer = setTimeout(() => { if (!device) ws.close(4401, "hello timeout") }, 10_000)146  ws.send(frame("server.hello", { nonce, server_time: now(), protocol: 1 }))147  ws.on("message", raw => {148    let m; try { m = JSON.parse(raw.toString()) } catch { return ws.close(4400, "invalid frame") }149    if (typeof m?.type !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(m.id ?? "") || typeof (m.data ?? {}) !== "object") return ws.close(4400, "invalid frame")150    const d = m.data ?? {}151    if (!device) {152      if (m.type !== "device.hello") return ws.close(4401, "hello expected")153      const rec = state.devices[d.device_id]154      if (!rec) { ws.send(frame("error", { code: "device_unknown", message: "appareil inconnu" })); return ws.close(4401, "unknown") }155      if (rec.revoked) { ws.send(frame("error", { code: "device_revoked", message: "appareil révoqué" })); return ws.close(4403, "revoked") }156      const ok = d.nonce === nonce && fresh(d.signed_at) && verify(rec.public_key, `maclustr-sms-device-auth-v1\n${d.device_id}\n${d.nonce}\n${d.signed_at}`, d.signature)157      if (!ok) { ws.send(frame("error", { code: "bad_signature", message: "signature refusée" })); console.log("[auth] REFUSED", d.device_id); return ws.close(4401, "bad signature") }158      device = d.device_id; clearTimeout(timer)159      if (socket && socket !== ws) socket.close(4409, "replaced")160      socket = ws; socketDevice = device161      console.log(`[auth] ${device} authenticated (ECDSA signature verified)`)162      ws.send(frame("device.authenticated", { device_id: device, session_id: id("ses"), server_time: now(), heartbeat_interval_s: 10, config: deviceConfig(rec) }))163      ws.send(frame("device.config.updated", deviceConfig(rec)))164      return165    }166    const n = (seen.get(m.id) || 0) + 1; seen.set(m.id, n)167    if (m.type === "device.heartbeat") return ws.send(frame("server.heartbeat", {}))168    log.push({ at: now(), type: m.type, id: m.id, data: d, dup: n > 1 })169    if (m.type !== "ack") console.log(`[rx] ${m.type}${n > 1 ? " (duplicate id, ignored)" : ""} ${m.type.startsWith("sms.") ? JSON.stringify({ ...d, text: d.text ? `<${d.text.length} car.>` : undefined }) : ""}`)170    if (m.type === "device.sim.updated" && n === 1) {171      state.devices[device].sims = d.sims; save()172      ws.send(frame("device.config.updated", deviceConfig(state.devices[device])))173    }174    if (!NO_ACK.has(m.type) && !noAck) ws.send(frame("ack", { ack: m.id }))175  })176  ws.on("close", (code) => { clearTimeout(timer); if (socket === ws) { socket = null; socketDevice = null; console.log(`[ws] closed ${code}`) } })177})178server.listen(PORT, "0.0.0.0", () => {179  console.log(`mock gateway on :${PORT}`)180  console.log(`pairing: maclustr-sms://pair?server=${encodeURIComponent(`http://10.0.2.2:${PORT}`)}&code=${pairingCode}`)181})182
Files main
Menu

Theme