Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr SMS Gateway8 * File : backend/src/devices/registry.ts9 * Module : devices10 * 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 { createPublicKey, randomInt, verify } from "node:crypto"43import QRCode from "qrcode"44import { config } from "../config.ts"45import { audit, getSetting, sql, type Tx } from "../db.ts"46import { tryE164 } from "../security/phone.ts"47import { ApiError, bad, iso, newId, sha256hex } from "../util.ts"48import { enqueueEvent } from "../webhooks/service.ts"4950const ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"51const PAIRING_TTL_MIN = 1052export const normalizeCode = (c: string) => String(c ?? "").toUpperCase().replace(/[^A-Z0-9]/g, "")5354export async function createPairingCode(adminId: string, nameHint = "") {55 let raw = ""56 for (let i = 0; i < 12; i++) raw += ALPHABET[randomInt(ALPHABET.length)]57 const code = `${raw.slice(0, 4)}-${raw.slice(4, 8)}-${raw.slice(8)}`58 const [r] = await sql`insert into pairing_codes(code_hash, created_by, name_hint, expires_at)59 values (${sha256hex(raw)}, ${adminId}, ${nameHint}, now() + make_interval(mins => ${PAIRING_TTL_MIN})) returning expires_at`60 const uri = `maclustr-sms://pair?server=${encodeURIComponent(config.origin)}&code=${code}`61 return { code, uri, server: config.origin, expires_at: iso(r.expires_at), qr_svg: await QRCode.toString(uri, { type: "svg", margin: 1, errorCorrectionLevel: "M" }) }62}6364export function checkPublicKey(spkiB64: string) {65 try {66 const key = createPublicKey({ key: Buffer.from(spkiB64, "base64"), format: "der", type: "spki" })67 const d = key.asymmetricKeyDetails68 if (key.asymmetricKeyType !== "ec" || d?.namedCurve !== "prime256v1") throw new Error()69 return key70 } catch { throw bad("invalid_request", "public_key : clé ECDSA P-256 au format SPKI DER (base64) attendue") }71}72export function verifySignature(spkiB64: string, data: string, signatureB64: string): boolean {73 try { return verify("sha256", Buffer.from(data, "utf8"), checkPublicKey(spkiB64), Buffer.from(signatureB64, "base64")) } catch { return false }74}7576export interface PairBody { code: string; public_key: string; name?: string; manufacturer?: string; model?: string; android_version?: string; sdk_int?: number; app_version?: string; app_build?: number }77const clip = (s: unknown, n = 80) => String(s ?? "").replace(/[\u0000-\u001f]/g, " ").trim().slice(0, n)7879/** Association : consomme le code à usage unique et enregistre la clé publique de l'appareil. */80export async function pairDevice(b: PairBody, ip: string | null) {81 checkPublicKey(b.public_key)82 const hash = sha256hex(normalizeCode(b.code))83 return sql.begin(async tx => {84 const [c] = await tx`update pairing_codes set used_at = now() where code_hash = ${hash} and used_at is null and expires_at > now() returning *`85 if (!c) throw new ApiError(404, "pairing_code_invalid", "code d'association inconnu, expiré ou déjà utilisé")86 const [n] = await tx`select nextval('device_number_seq')::int as n`87 const id = `android-${String(n.n).padStart(2, "0")}`88 const name = clip(b.name) || c.name_hint || id89 await tx`insert into devices(id, name, manufacturer, model, android_version, sdk_int, app_version, app_build)90 values (${id}, ${name}, ${clip(b.manufacturer)}, ${clip(b.model)}, ${clip(b.android_version, 20)}, ${Number.isInteger(b.sdk_int) ? b.sdk_int! : null}, ${clip(b.app_version, 20)}, ${Number.isInteger(b.app_build) ? b.app_build! : null})`91 await tx`insert into device_credentials(id, device_id, public_key) values (${newId("cred")}, ${id}, ${b.public_key})`92 await tx`update pairing_codes set device_id = ${id} where code_hash = ${hash}`93 await audit({ actorType: "device", actorId: id, action: "device.paired", targetType: "device", targetId: id, detail: { model: clip(b.model), paired_by: c.created_by }, ip }, tx)94 return { device_id: id, name, ws_url: config.origin.replace(/^http/, "ws") + "/ws/device", server_time: new Date().toISOString() }95 })96}9798export async function incident(tx: Tx, deviceId: string, kind: string, detail: Record<string, unknown> = {}) {99 await tx`insert into device_incidents(device_id, kind, detail) values (${deviceId}, ${kind}, ${tx.json(detail as any)})`100}101102export interface SimReport { subscription_id: number; slot_index?: number | null; carrier_name?: string | null; display_name?: string | null; is_embedded?: boolean | null; number?: string | null; country_iso?: string | null; mcc_mnc?: string | null; state?: string | null; signal_level?: number | null; roaming?: boolean | null; is_default_sms?: boolean | null }103104/** Remplace l'inventaire SIM de l'appareil par la liste rapportée. Une nouvelle SIM n'est jamais autorisée à envoyer avant activation par un administrateur. */105export async function updateSims(tx: Tx, deviceId: string, sims: SimReport[]) {106 await tx`select pg_advisory_xact_lock(7405002)`107 const before = await tx`select * from sim_profiles where device_id = ${deviceId}`108 const seen = new Set<number>()109 for (const s of sims) {110 if (!Number.isInteger(s.subscription_id) || seen.has(s.subscription_id)) continue111 seen.add(s.subscription_id)112 const number = tryE164(s.number, s.country_iso)113 const prev = before.find(p => p.subscription_id === s.subscription_id)114 const state = ["ready", "absent", "locked", "not_ready", "unknown"].includes(String(s.state)) ? s.state! : "unknown"115 if (prev) {116 await tx`update sim_profiles set slot_index = ${s.slot_index ?? null}, carrier_name = ${clip(s.carrier_name)}, display_name = ${clip(s.display_name)}, is_embedded = ${s.is_embedded ?? null},117 reported_number = ${number}, country_iso = ${clip(s.country_iso, 4) || null}, mcc_mnc = ${clip(s.mcc_mnc, 8) || null}, state = ${state},118 signal_level = ${Number.isInteger(s.signal_level) ? s.signal_level! : null}, roaming = ${s.roaming ?? null}, is_default_sms = ${s.is_default_sms ?? null}, active = true, updated_at = now()119 where id = ${prev.id}`120 if (prev.active && prev.state === "ready" && state !== "ready") await simUnavailable(tx, deviceId, prev, state)121 } else {122 const [n] = await tx`select nextval('sim_number_seq')::int as n`123 await tx`insert into sim_profiles(id, device_id, subscription_id, slot_index, carrier_name, display_name, is_embedded, reported_number, country_iso, mcc_mnc, state, signal_level, roaming, is_default_sms)124 values (${"sim-" + n.n}, ${deviceId}, ${s.subscription_id}, ${s.slot_index ?? null}, ${clip(s.carrier_name)}, ${clip(s.display_name)}, ${s.is_embedded ?? null}, ${number},125 ${clip(s.country_iso, 4) || null}, ${clip(s.mcc_mnc, 8) || null}, ${state}, ${Number.isInteger(s.signal_level) ? s.signal_level! : null}, ${s.roaming ?? null}, ${s.is_default_sms ?? null})`126 }127 }128 for (const p of before) if (p.active && !seen.has(p.subscription_id)) {129 await tx`update sim_profiles set active = false, state = 'absent', signal_level = null, updated_at = now() where id = ${p.id}`130 await simUnavailable(tx, deviceId, p, "absent")131 }132 await syncNumbers(tx)133}134async function simUnavailable(tx: Tx, deviceId: string, sim: any, state: string) {135 await incident(tx, deviceId, "sim.unavailable", { sim_id: sim.id, state })136 await enqueueEvent(tx, { type: "sim.unavailable", scope: "device", simId: sim.id, data: { device_id: deviceId, sim_id: sim.id, state, number: sim.manual_number ?? sim.reported_number } })137}138/** Table phone_numbers = vue matérialisée des numéros connus (manuel prioritaire sur rapporté). Un numéro n'appartient qu'à une SIM. */139export async function syncNumbers(tx: Tx) {140 await tx`delete from phone_numbers`141 await tx`insert into phone_numbers(number, sim_id, source, label)142 select distinct on (coalesce(manual_number, reported_number)) coalesce(manual_number, reported_number), id, case when manual_number is not null then 'manual' else 'reported' end, label143 from sim_profiles where coalesce(manual_number, reported_number) is not null order by coalesce(manual_number, reported_number), active desc, updated_at desc`144}145146export async function latestApp(): Promise<{ version: string; build: number; notes?: string; sha256?: string } | null> {147 try {148 const { readFileSync } = await import("node:fs")149 const { join } = await import("node:path")150 const j = JSON.parse(readFileSync(join(config.releasesDir, "android-release.json"), "utf8"))151 return { version: String(j.version), build: Number(j.build), notes: j.notes, sha256: j.sha256 }152 } catch { return null }153}154155export async function deviceConfig(deviceId: string) {156 const [d] = await sql`select * from devices where id = ${deviceId}`157 const sims = await sql`select subscription_id, id, enabled, coalesce(manual_number, reported_number) as number from sim_profiles where device_id = ${deviceId} and active order by subscription_id`158 return {159 gateway_enabled: !(await getSetting("kill_switch", false)) && d.enabled && !d.revoked_at,160 maintenance: d.maintenance, min_send_interval_ms: d.min_send_interval_ms, device_name: d.name,161 sims: sims.map(s => ({ subscription_id: s.subscription_id, sim_id: s.id, enabled: s.enabled, number: s.number })),162 latest_app: await latestApp(),163 }164}165166export const publicSim = (s: any) => ({167 id: s.id, device_id: s.device_id, subscription_id: s.subscription_id, slot_index: s.slot_index, carrier_name: s.carrier_name, display_name: s.display_name, label: s.label,168 type: s.is_embedded == null ? "unknown" : s.is_embedded ? "esim" : "physical", number: s.manual_number ?? s.reported_number, number_source: s.manual_number ? "manual" : s.reported_number ? "reported" : null,169 state: s.state, signal_level: s.signal_level, roaming: s.roaming, active: s.active, send_enabled: s.enabled, daily_limit: s.daily_limit, updated_at: iso(s.updated_at),170})171export const publicDevice = (d: any, sims: any[] = []) => ({172 id: d.id, name: d.name, manufacturer: d.manufacturer, model: d.model, android_version: d.android_version, app_version: d.app_version, app_build: d.app_build,173 online: d.online, enabled: d.enabled, maintenance: d.maintenance, revoked: !!d.revoked_at,174 available: d.online && d.enabled && !d.maintenance && !d.revoked_at && d.status?.gateway_state === "running" && d.status?.permissions?.send_sms !== false,175 sms_permissions_missing: !!d.status?.permissions && (d.status.permissions.send_sms === false || d.status.permissions.receive_sms === false),176 last_seen_at: iso(d.last_seen_at), battery_pct: d.status?.battery_pct ?? null, charging: d.status?.charging ?? null, battery_temp_c: d.status?.battery_temp_c ?? null,177 network: d.status?.network ?? null, gateway_state: d.status?.gateway_state ?? null, status: d.status ?? {},178 min_send_interval_ms: d.min_send_interval_ms, created_at: iso(d.created_at), sims: sims.filter(s => s.device_id === d.id).map(publicSim),179})180