Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr SMS Gateway8 * File : backend/src/routing/router.ts9 * Module : routing10 * 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 { getSetting, type Tx } from "../db.ts"43import { forbidden, unprocessable } from "../util.ts"4445export interface Route { simId: string; deviceId: string; subscriptionId: number; fromNumber: string | null }46export interface RouteRequest { deviceId?: string | null; simId?: string | null; from?: string | null; to: string; allowedSimIds: string[] | null }4748/**49 * Choix de l'expéditeur. Règles, dans l'ordre :50 * 1. `sim_id` ou `from` explicite : utilisé tel quel, erreur s'il n'est pas disponible (jamais de repli silencieux) ;51 * 2. conversation existante avec ce destinataire : même SIM que la dernière fois (le numéro expéditeur ne change pas) ;52 * 3. SIM par défaut du système ; 4. l'unique SIM autorisée s'il n'y en a qu'une ; sinon erreur `sender_required`.53 * Le message est lié à cette SIM à la création. Si l'appareil est hors ligne, il attend dans la file : il n'est jamais rerouté.54 */55export async function resolveRoute(tx: Tx, req: RouteRequest): Promise<Route> {56 const sims = await tx`57 select s.id, s.device_id, s.subscription_id, s.enabled, s.active, s.state, coalesce(s.manual_number, s.reported_number) as number,58 d.enabled as device_enabled, d.revoked_at59 from sim_profiles s join devices d on d.id = s.device_id`60 const permitted = (s: any) => !req.allowedSimIds || req.allowedSimIds.includes(s.id)61 const check = (s: any): Route => {62 if (!permitted(s)) throw forbidden("sim_not_permitted", "cette application n'est pas autorisée à utiliser cette SIM")63 if (s.revoked_at || !s.device_enabled) throw unprocessable("device_unavailable", "l'appareil de cette SIM est désactivé ou révoqué")64 if (!s.enabled) throw unprocessable("sim_disabled", "l'envoi n'est pas activé sur cette SIM")65 if (!s.active) throw unprocessable("sim_unavailable", "cette SIM n'est plus présente dans l'appareil")66 return { simId: s.id, deviceId: s.device_id, subscriptionId: s.subscription_id, fromNumber: s.number }67 }68 const inDevice = (s: any) => !req.deviceId || s.device_id === req.deviceId6970 if (req.simId) {71 const s = sims.find(x => x.id === req.simId)72 if (!s) throw unprocessable("sim_not_found", "SIM inconnue")73 if (!inDevice(s)) throw unprocessable("sim_device_mismatch", "cette SIM n'appartient pas à l'appareil demandé")74 if (req.from && s.number !== req.from) throw unprocessable("sender_mismatch", "le numéro expéditeur demandé ne correspond pas à cette SIM")75 return check(s)76 }77 if (req.from) {78 const s = sims.find(x => x.number === req.from && inDevice(x))79 if (!s) throw unprocessable("sender_not_found", "aucune SIM ne correspond au numéro expéditeur demandé")80 return check(s)81 }82 const usable = sims.filter(s => inDevice(s) && permitted(s) && s.enabled && s.active && s.device_enabled && !s.revoked_at)83 if (!usable.length) throw unprocessable("no_sender_available", "aucune SIM activée n'est disponible pour cet envoi")8485 const [conv] = await tx`select sim_id from conversations where peer = ${req.to} order by last_message_at desc limit 1`86 if (conv) {87 const s = usable.find(x => x.id === conv.sim_id)88 if (s) return check(s)89 // La SIM de la conversation n'est plus utilisable : on ne change pas d'expéditeur sans demande explicite.90 if (usable.length > 1 || sims.some(x => x.id === conv.sim_id))91 throw unprocessable("sender_required", "la SIM habituelle de cette conversation n'est pas disponible : précisez sim_id ou from pour changer d'expéditeur")92 }93 const def = await getSetting<string | null>("default_sim_id", null)94 if (def) { const s = usable.find(x => x.id === def); if (s) return check(s) }95 if (usable.length === 1) return check(usable[0])96 throw unprocessable("sender_required", "plusieurs SIM sont disponibles : précisez sim_id ou from, ou définissez une SIM par défaut")97}98