Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr SMS Gateway8 * File : backend/src/websocket/hub.ts9 * Module : websocket10 * 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 */4142import type { IncomingMessage } from "node:http"43import { randomBytes } from "node:crypto"44import { WebSocket, WebSocketServer } from "ws"45import { z } from "zod"46import { bus, changed, poke, pokeWebhooks } from "../bus.ts"47import { config } from "../config.ts"48import { sql, type Tx } from "../db.ts"49import { deviceConfig, incident, updateSims, verifySignature } from "../devices/registry.ts"50import { recordInbound, transition } from "../messages/service.ts"51import { limiter } from "../security/ratelimit.ts"52import { newId, ulid } from "../util.ts"53import { enqueueEvent } from "../webhooks/service.ts"5455const Envelope = z.object({ type: z.string().min(1).max(64), id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/), ts: z.string().max(40), data: z.record(z.string(), z.unknown()).default({}) })56const Hello = z.object({ device_id: z.string().max(40), nonce: z.string().max(100), signed_at: z.string().max(40), signature: z.string().max(400), protocol: z.number().int().optional(), app_version: z.string().max(20).optional(), app_build: z.number().int().optional() })57const Cmd = z.object({ command_id: z.string().max(64), message_id: z.string().max(64).optional() })58const NO_ACK = new Set(["ack", "device.hello", "device.heartbeat"])59const MAX_FRAME = 64 * 102460export const AUTH_STRING = (deviceId: string, nonce: string, signedAt: string) => `maclustr-sms-device-auth-v1\n${deviceId}\n${nonce}\n${signedAt}`6162interface Conn { ws: WebSocket; ip: string | null; nonce: string; deviceId: string | null; sessionId: string | null; lastFrame: number; chain: Promise<void>; lastSeenWrite: number }63const sessions = new Map<string, Conn>() // device_id → connexion authentifiée64let log: { info: Function; warn: Function; error: Function } = console6566const frame = (type: string, data: Record<string, unknown> = {}) => JSON.stringify({ type, id: ulid(), ts: new Date().toISOString(), data })67function send(c: Conn, type: string, data: Record<string, unknown> = {}): boolean {68 if (c.ws.readyState !== WebSocket.OPEN) return false69 try { c.ws.send(frame(type, data)); return true } catch { return false }70}71function fail(c: Conn, wsCode: number, code: string, message: string) { send(c, "error", { code, message }); c.ws.close(wsCode, code) }7273export const isConnected = (deviceId: string) => sessions.has(deviceId)74export const connectedDevices = () => [...sessions.keys()]75/** Envoie une commande à un appareil connecté. false = non remise (elle sera reproposée à la reconnexion si elle est persistante). */76export function sendToDevice(deviceId: string, type: string, data: Record<string, unknown>): boolean {77 const c = sessions.get(deviceId)78 return c ? send(c, type, data) : false79}80export async function pushConfig(deviceId?: string) {81 for (const id of deviceId ? [deviceId] : connectedDevices()) if (sessions.has(id)) sendToDevice(id, "device.config.updated", await deviceConfig(id))82}83export function disconnectDevice(deviceId: string, wsCode: number, code: string) { const c = sessions.get(deviceId); if (c) fail(c, wsCode, code, code) }8485async function authenticate(c: Conn, data: unknown) {86 const h = Hello.safeParse(data)87 if (!h.success) return fail(c, 4400, "invalid_frame", "device.hello invalide")88 const { device_id, nonce, signed_at, signature } = h.data89 // Anti-rejeu : le nonce doit être celui émis sur CETTE connexion, et l'horodatage proche de l'horloge du serveur.90 if (nonce !== c.nonce) return fail(c, 4401, "nonce_mismatch", "nonce inattendu")91 const skew = Math.abs(Date.now() - Date.parse(signed_at))92 if (!Number.isFinite(skew) || skew > 5 * 60_000) return fail(c, 4401, "clock_skew", "horodatage hors tolérance (5 min) : vérifiez l'horloge de l'appareil")93 const [d] = await sql`select * from devices where id = ${device_id}`94 if (!d) return fail(c, 4401, "device_unknown", "appareil inconnu")95 if (d.revoked_at) return fail(c, 4403, "device_revoked", "cet appareil a été révoqué")96 const creds = await sql`select public_key from device_credentials where device_id = ${device_id} and revoked_at is null`97 if (!creds.some(k => verifySignature(k.public_key, AUTH_STRING(device_id, nonce, signed_at), signature))) return fail(c, 4401, "bad_signature", "signature invalide")98 c.nonce = "" // usage unique99100 const old = sessions.get(device_id)101 if (old && old !== c) { old.deviceId = null; fail(old, 4409, "session_replaced", "nouvelle session ouverte pour cet appareil") ; await closeSession(old.sessionId, 4409, "session_replaced") }102 c.deviceId = device_id103 c.sessionId = newId("ses")104 sessions.set(device_id, c)105 await sql.begin(async tx => {106 await tx`insert into device_sessions(id, device_id, ip, app_version) values (${c.sessionId}, ${device_id}, ${c.ip}, ${h.data.app_version ?? null})`107 await tx`update devices set online = true, last_seen_at = now(), app_version = coalesce(${h.data.app_version ?? null}, app_version), app_build = coalesce(${h.data.app_build ?? null}, app_build) where id = ${device_id}`108 if (!d.online) {109 await incident(tx, device_id, "device.online")110 await enqueueEvent(tx, { type: "device.online", scope: "device", data: { device_id, name: d.name } })111 }112 })113 const cfg = await deviceConfig(device_id)114 send(c, "device.authenticated", { device_id, session_id: c.sessionId, server_time: new Date().toISOString(), heartbeat_interval_s: config.heartbeatIntervalS, config: cfg })115 send(c, "device.config.updated", cfg)116 log.info({ device_id, session_id: c.sessionId }, "appareil authentifié")117 bus.emit("device.connected", device_id)118 changed("devices"); pokeWebhooks()119}120121async function closeSession(sessionId: string | null, code: number, reason: string) {122 if (sessionId) await sql`update device_sessions set disconnected_at = now(), close_code = ${code}, close_reason = ${reason.slice(0, 100)} where id = ${sessionId} and disconnected_at is null`123}124125async function messageFor(tx: Tx, deviceId: string, data: unknown) {126 const p = Cmd.safeParse(data)127 if (!p.success) return null128 // Un appareil ne peut agir que sur ses propres commandes.129 const [m] = await tx`select id, segments from messages where command_id = ${p.data.command_id} and device_id = ${deviceId}`130 return m ?? null131}132const when = (v: unknown) => (typeof v === "string" && Number.isFinite(Date.parse(v)) ? new Date(v) : null)133const int = (v: unknown) => (Number.isInteger(v) ? (v as number) : null)134135/** Traite un événement d'appareil dans une transaction ; l'accusé de réception n'est émis qu'après validation. */136async function handleEvent(tx: Tx, deviceId: string, type: string, eventId: string, data: Record<string, unknown>) {137 const src = { source: "device" as const, type }138 switch (type) {139 case "device.status": {140 const clean = JSON.parse(JSON.stringify(data).slice(0, 4000))141 await tx`update devices set status = ${tx.json(clean)}, last_status_at = now(), last_seen_at = now(),142 app_version = coalesce(${typeof data.app_version === "string" ? data.app_version.slice(0, 20) : null}, app_version), app_build = coalesce(${int(data.app_build)}, app_build),143 android_version = coalesce(${typeof data.android_version === "string" ? data.android_version.slice(0, 20) : null}, android_version) where id = ${deviceId}`144 return145 }146 case "device.sim.updated":147 if (Array.isArray(data.sims)) await updateSims(tx, deviceId, data.sims.slice(0, 16) as any)148 return149 case "sms.received":150 if (typeof data.from === "string" && typeof data.text === "string" && Number.isInteger(data.subscription_id)) await recordInbound(tx, deviceId, eventId, data as any)151 return152 case "device.diagnostic":153 if (typeof data.request_id === "string") await tx`update device_diagnostics set completed_at = now(), checks = ${tx.json((Array.isArray(data.checks) ? data.checks.slice(0, 50) : []) as any)} where id = ${data.request_id} and device_id = ${deviceId}`154 return155 }156 const m = await messageFor(tx, deviceId, data)157 if (!m) return158 switch (type) {159 case "sms.send.accepted": await transition(tx, m.id, "ACCEPTED", src); return160 case "sms.send.submitting": {161 const parts = int(data.parts)162 if (parts && parts > 0 && parts !== m.segments) await tx`update messages set segments = ${parts} where id = ${m.id}`163 await transition(tx, m.id, "SUBMITTING", { ...src, detail: { parts } }); return164 }165 case "sms.send.submitted": await transition(tx, m.id, "SUBMITTED", { ...src, partsSent: int(data.parts), detail: { parts: int(data.parts), device_time: when(data.submitted_at)?.toISOString() ?? null } }); return166 case "sms.send.failed": {167 const code = typeof data.code === "string" ? data.code.slice(0, 40) : "internal"168 const detail = { android_result_code: int(data.android_result_code), parts: int(data.parts), parts_sent: int(data.parts_sent), definitive: data.definitive === true }169 await transition(tx, m.id, code === "expired" ? "EXPIRED" : "FAILED", { ...src, errorCode: code, errorDetail: typeof data.detail === "string" ? data.detail.slice(0, 200) : null, partsSent: int(data.parts_sent), detail })170 return171 }172 case "sms.send.unknown":173 await transition(tx, m.id, "UNKNOWN", { ...src, errorCode: "unknown_outcome", errorDetail: typeof data.reason === "string" ? data.reason.slice(0, 60) : null, detail: { reason: data.reason } })174 return175 case "sms.delivery.confirmed": {176 const part = int(data.part) ?? 1, status = data.status === "delivered" ? "delivered" : data.status === "failed" ? "failed" : "pending"177 await tx`insert into message_segments(message_id, part, status, pdu_status) values (${m.id}, ${part}, ${status}, ${int(data.pdu_status)})178 on conflict (message_id, part) do update set status = case when message_segments.status = 'delivered' then 'delivered' else excluded.status end, pdu_status = excluded.pdu_status, updated_at = now()`179 const total = int(data.parts) ?? m.segments180 const [c] = await tx`select count(*) filter (where status = 'delivered')::int as ok, count(*) filter (where status = 'failed')::int as ko from message_segments where message_id = ${m.id}`181 if (c.ok >= total) await transition(tx, m.id, "DELIVERED", { ...src, detail: { parts: total, device_time: when(data.delivered_at)?.toISOString() ?? null } })182 else if (status === "failed") await transition(tx, m.id, "FAILED", { ...src, errorCode: "delivery_failed", errorDetail: `rapport de livraison négatif (partie ${part})`, detail: { part, pdu_status: int(data.pdu_status) } })183 return184 }185 }186}187188async function onFrame(c: Conn, raw: string) {189 let env: z.infer<typeof Envelope>190 try { env = Envelope.parse(JSON.parse(raw)) } catch { return fail(c, 4400, "invalid_frame", "trame invalide") }191 c.lastFrame = Date.now()192 if (!c.deviceId) {193 if (env.type !== "device.hello") return fail(c, 4401, "not_authenticated", "device.hello attendu")194 return authenticate(c, env.data)195 }196 const deviceId = c.deviceId197 // Garde-fou : un appareil compromis ou défaillant ne peut pas inonder la base (20 trames/s soutenues, rafale de 300).198 if (!limiter.take("device-frames:" + deviceId, 1200, 300)) return fail(c, 4429, "rate_limited", "trop de trames")199 if (env.type === "ack") return200 if (env.type === "device.heartbeat") {201 send(c, "server.heartbeat", { server_time: new Date().toISOString() })202 if (Date.now() - c.lastSeenWrite > 20_000) { c.lastSeenWrite = Date.now(); await sql`update devices set last_seen_at = now() where id = ${deviceId}` }203 return204 }205 if (NO_ACK.has(env.type)) return206 await sql.begin(async tx => {207 // Déduplication : un événement rejoué (même id) est acquitté sans être retraité.208 const fresh = await tx`insert into device_events(device_id, event_id, type) values (${deviceId}, ${env.id}, ${env.type}) on conflict do nothing returning 1`209 if (fresh.length) await handleEvent(tx, deviceId, env.type, env.id, env.data)210 })211 send(c, "ack", { ack: env.id })212 if (env.type.startsWith("sms.")) { changed("messages"); pokeWebhooks(); poke(deviceId) } else changed("devices")213 // L'inventaire SIM a changé : l'appareil reçoit la correspondance subscription_id → sim_id à jour.214 if (env.type === "device.sim.updated") { await pushConfig(deviceId); pokeWebhooks(); poke(deviceId) }215}216217async function onClose(c: Conn, code: number, reason: string) {218 const deviceId = c.deviceId219 if (!deviceId) return220 if (sessions.get(deviceId) !== c) return221 sessions.delete(deviceId)222 await sql.begin(async tx => {223 await tx`update device_sessions set disconnected_at = now(), close_code = ${code}, close_reason = ${reason.slice(0, 100)} where id = ${c.sessionId} and disconnected_at is null`224 const [d] = await tx`update devices set online = false where id = ${deviceId} returning name`225 await incident(tx, deviceId, "device.offline", { close_code: code })226 await enqueueEvent(tx, { type: "device.offline", scope: "device", data: { device_id: deviceId, name: d?.name } })227 }).catch(e => log.error(e))228 log.info({ device_id: deviceId, code }, "appareil déconnecté")229 changed("devices"); pokeWebhooks()230}231232export async function startHub(logger: typeof log) {233 log = logger234 // Après un redémarrage du serveur, plus aucune session n'est vivante.235 await sql`update devices set online = false where online`236 await sql`update device_sessions set disconnected_at = now(), close_reason = 'server_restart' where disconnected_at is null`237 const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME })238 wss.on("connection", (ws: WebSocket, _req: IncomingMessage, ip: string | null) => {239 const c: Conn = { ws, ip, nonce: randomBytes(32).toString("base64url"), deviceId: null, sessionId: null, lastFrame: Date.now(), chain: Promise.resolve(), lastSeenWrite: 0 }240 send(c, "server.hello", { nonce: c.nonce, server_time: new Date().toISOString(), protocol: 1 })241 const authTimer = setTimeout(() => { if (!c.deviceId) fail(c, 4401, "auth_timeout", "authentification non reçue en 10 s") }, 10_000)242 ws.on("message", (buf, isBinary) => {243 if (isBinary) return fail(c, 4400, "invalid_frame", "trames texte seulement")244 // Traitement strictement séquentiel par connexion : l'ordre des événements d'un appareil est préservé.245 c.chain = c.chain.then(() => onFrame(c, buf.toString())).catch(e => { log.error({ err: String(e?.message ?? e), device_id: c.deviceId }, "erreur de traitement d'une trame") })246 })247 ws.on("close", (code, reason) => { clearTimeout(authTimer); void onClose(c, code, reason.toString()) })248 ws.on("error", () => {})249 })250 // Chien de garde : sans trame pendant 2,5 intervalles de heartbeat, la connexion est considérée perdue.251 const dog = setInterval(() => {252 const limit = config.heartbeatIntervalS * 2500253 for (const ws of wss.clients) { const c = [...sessions.values()].find(s => s.ws === ws); if (c && Date.now() - c.lastFrame > limit) ws.terminate() }254 }, 10_000)255 dog.unref()256 return { wss, stop: () => { clearInterval(dog); for (const ws of wss.clients) ws.close(1001, "server_shutdown"); wss.close() } }257}258