Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr SMS Gateway8 * File : backend/src/messages/service.ts9 * Module : messages10 * 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 { bump, sentToday } from "../analytics/usage.ts"43import { changed, poke, pokeWebhooks } from "../bus.ts"44import { getSetting, sql, type Tx } from "../db.ts"45import { resolveRoute } from "../routing/router.ts"46import { open, seal } from "../security/crypto.ts"47import { MAX_SEGMENTS, normalizeRecipient, normalizeSender, segmentInfo, tryE164 } from "../security/phone.ts"48import { ApiError, conflict, forbidden, iso, newId, notFound, sha256hex, unprocessable } from "../util.ts"49import { enqueueEvent, type WebhookEvent } from "../webhooks/service.ts"50import { canTransition, CANCELLABLE, IN_QUEUE, type Status } from "./states.ts"5152export interface AppCtx { id: string; name: string; enabled: boolean; daily_quota: number; approval_required: boolean; require_consent: boolean; allowed_sim_ids: string[] | null }53export interface SendInput { to: string; text: string; device_id?: string | null; sim_id?: string | null; from?: string | null; ttl_seconds?: number | null; delivery_report?: boolean | null; sensitive?: boolean }54export interface Actor { app?: AppCtx; apiKeyId?: string; adminId?: string }5556const textCtx = (id: string) => "sms-text:" + id57const untilUtcMidnight = () => Math.ceil((new Date(new Date().toISOString().slice(0, 10) + "T00:00:00Z").getTime() + 86400_000 - Date.now()) / 1000)5859export function publicMessage(m: any, withText = true) {60 return {61 id: m.id, direction: m.direction, status: (m.status as string).toLowerCase(),62 to: m.to_number, from: m.from_number,63 // Un SMS sensible (code de vérification) n'est jamais relu : ni par l'API, ni par le tableau de bord, ni par un webhook.64 ...(withText ? { text: m.sensitive ? null : m.text_enc ? open(m.text_enc, textCtx(m.id)) : null } : {}),65 text_purged: !m.text_enc, sensitive: !!m.sensitive,66 device_id: m.device_id, sim_id: m.sim_id, application_id: m.application_id, conversation_id: m.conversation_id,67 encoding: m.encoding, segments: m.segments, characters: m.text_chars,68 error: m.error_code ? { code: m.error_code, detail: m.error_detail } : null,69 created_at: iso(m.created_at), expires_at: iso(m.expires_at), dispatched_at: iso(m.dispatched_at), accepted_at: iso(m.accepted_at),70 submitted_at: iso(m.submitted_at), delivered_at: iso(m.delivered_at), finalized_at: iso(m.finalized_at), received_at: iso(m.received_at),71 }72}7374async function touchConversation(tx: Tx, simId: string, peer: string, direction: "inbound" | "outbound"): Promise<string> {75 const id = newId("conv")76 const [c] = await tx`77 insert into conversations(id, sim_id, peer, last_direction, inbound_count, outbound_count, unread)78 values (${id}, ${simId}, ${peer}, ${direction}, ${direction === "inbound" ? 1 : 0}, ${direction === "outbound" ? 1 : 0}, ${direction === "inbound" ? 1 : 0})79 on conflict (sim_id, peer) do update set last_message_at = now(), last_direction = excluded.last_direction,80 inbound_count = conversations.inbound_count + excluded.inbound_count, outbound_count = conversations.outbound_count + excluded.outbound_count,81 unread = conversations.unread + excluded.unread82 returning id`83 return c.id84}8586/** Crée un SMS sortant : toutes les vérifications (arrêt d'urgence, désinscription, liste autorisée, consentement, quotas, routage) précèdent l'écriture. */87export async function createOutbound(input: SendInput, actor: Actor, idempotencyKey?: string | null): Promise<{ message: any; replayed: boolean }> {88 const app = actor.app ?? null89 const text = typeof input.text === "string" ? input.text : ""90 if (!text.trim()) throw unprocessable("empty_text", "le texte du message est vide")91 const seg = segmentInfo(text)92 if (seg.segments > MAX_SEGMENTS) throw unprocessable("text_too_long", `message trop long : ${seg.segments} segments (maximum ${MAX_SEGMENTS})`)93 const to = normalizeRecipient(input.to)94 const from = input.from ? normalizeRecipient(input.from) : null95 const requestHash = sha256hex(JSON.stringify([to, text, input.device_id ?? null, input.sim_id ?? null, from]))96 const minTtl = input.sensitive ? 30 : 609798 if (idempotencyKey != null) {99 if (!/^[\x21-\x7e]{1,128}$/.test(idempotencyKey)) throw new ApiError(400, "invalid_idempotency_key", "Idempotency-Key : 1 à 128 caractères ASCII imprimables")100 const [prev] = await sql`select * from messages where application_id is not distinct from ${app?.id ?? null} and idempotency_key = ${idempotencyKey}101 ${app ? sql`` : sql`and created_by = ${actor.adminId ?? ""}`}`102 if (prev) {103 if (prev.request_hash !== requestHash) throw conflict("idempotency_conflict", "cette Idempotency-Key a déjà servi pour une requête différente")104 return { message: prev, replayed: true }105 }106 }107108 if (await getSetting("kill_switch", false)) throw new ApiError(503, "kill_switch_active", "arrêt d'urgence actif : aucun envoi n'est accepté")109 if (app && !app.enabled) throw forbidden("application_disabled", "cette application est désactivée")110111 try {112 const message = await sql.begin(async tx => {113 const [out] = await tx`select 1 from opt_outs where number = ${to}`114 if (out) throw unprocessable("recipient_opted_out", "ce destinataire s'est désinscrit (STOP)")115 if ((await getSetting("send_mode", "allowlist")) !== "open") {116 const [ok] = await tx`select 1 from allowed_recipients where number = ${to}`117 if (!ok) throw forbidden("recipient_not_allowed", "mode liste autorisée : ce destinataire n'est pas dans la liste des destinataires autorisés")118 }119 if (app?.require_consent) {120 const [c] = await tx`select 1 from consents where number = ${to} and revoked_at is null and (application_id is null or application_id = ${app.id})`121 if (!c) throw forbidden("consent_required", "aucun consentement enregistré pour ce destinataire")122 }123 const route = await resolveRoute(tx, { deviceId: input.device_id, simId: input.sim_id, from, to, allowedSimIds: app?.allowed_sim_ids ?? null })124 // Verrou par SIM : sérialise le contrôle des quotas pour des requêtes concurrentes.125 const [sim] = await tx`select id, daily_limit from sim_profiles where id = ${route.simId} for update`126 if (app && (await sentToday(tx, { applicationId: app.id })) >= app.daily_quota) throw new ApiError(429, "quota_exceeded", "quota journalier de l'application atteint", undefined, untilUtcMidnight())127 if ((await sentToday(tx, { simId: sim.id })) >= sim.daily_limit) throw new ApiError(429, "sim_limit_exceeded", "limite journalière de cette SIM atteinte", undefined, untilUtcMidnight())128129 const id = newId("sms"), held = !!app?.approval_required130 const ttl = Math.min(Math.max(Number(input.ttl_seconds ?? (await getSetting("default_ttl_seconds", 3600))), minTtl), 86400)131 const convId = await touchConversation(tx, route.simId, to, "outbound")132 const [m] = await tx`133 insert into messages(id, direction, status, application_id, api_key_id, created_by, device_id, sim_id, conversation_id, from_number, to_number,134 text_enc, text_chars, encoding, segments, delivery_report, idempotency_key, request_hash, command_id, expires_at, sensitive)135 values (${id}, 'outbound', ${held ? "HELD" : "QUEUED"}, ${app?.id ?? null}, ${actor.apiKeyId ?? null}, ${actor.adminId ?? null}, ${route.deviceId}, ${route.simId}, ${convId},136 ${route.fromNumber}, ${to}, ${seal(text, textCtx(id))}, ${seg.chars}, ${seg.encoding}, ${seg.segments}, ${input.delivery_report !== false},137 ${idempotencyKey ?? null}, ${requestHash}, ${newId("cmd")}, now() + make_interval(secs => ${ttl}), ${!!input.sensitive})138 returning *`139 await tx`insert into message_events(message_id, type, to_status, source, detail)140 values (${id}, 'message.created', ${m.status}, ${app ? "api" : "admin"}, ${tx.json({ segments: seg.segments, encoding: seg.encoding, held })})`141 if (!held) await tx`insert into message_queue(message_id, device_id, sim_id) values (${id}, ${route.deviceId}, ${route.simId})`142 await bump(tx, "outbound_created", app?.id ?? null, route.simId)143 await bump(tx, "outbound_segments", app?.id ?? null, route.simId, seg.segments)144 return m145 })146 poke(message.device_id); changed("messages")147 return { message, replayed: false }148 } catch (e: any) {149 // Course entre deux requêtes portant la même Idempotency-Key : la seconde relit le message créé par la première.150 if (e?.code === "23505" && idempotencyKey != null && String(e.constraint_name ?? "").includes("idempotency")) {151 const [prev] = await sql`select * from messages where application_id is not distinct from ${app?.id ?? null} and idempotency_key = ${idempotencyKey}`152 if (prev && prev.request_hash === requestHash) return { message: prev, replayed: true }153 throw conflict("idempotency_conflict", "cette Idempotency-Key a déjà servi pour une requête différente")154 }155 throw e156 }157}158159const STATUS_WEBHOOK: Partial<Record<Status, WebhookEvent>> = { SUBMITTED: "sms.submitted", DELIVERED: "sms.delivered", FAILED: "sms.failed", EXPIRED: "sms.failed", UNKNOWN: "sms.unknown" }160const STATUS_METRIC = { SUBMITTED: "submitted", DELIVERED: "delivered", FAILED: "failed", EXPIRED: "expired", UNKNOWN: "unknown", CANCELLED: "cancelled" } as const161const STAMP: Partial<Record<Status, string>> = { DISPATCHED: "dispatched_at", ACCEPTED: "accepted_at", SUBMITTING: "submitting_at", SUBMITTED: "submitted_at", DELIVERED: "delivered_at" }162163export interface TransitionOpts { source: "api" | "admin" | "device" | "system"; type: string; detail?: Record<string, unknown>; errorCode?: string | null; errorDetail?: string | null; partsSent?: number | null; at?: Date | null }164165/**166 * Transition d'état unique et verrouillée. Une transition non permise (événement en retard, rejoué ou dans le désordre)167 * est consignée dans message_events mais ne modifie pas le message. Retourne true si l'état a changé.168 */169export async function transition(tx: Tx, messageId: string, to: Status, o: TransitionOpts): Promise<boolean> {170 const [m] = await tx`select * from messages where id = ${messageId} for update`171 if (!m || m.direction !== "outbound") return false172 const from = m.status as Status173 if (from === to || !canTransition(from, to)) {174 await tx`insert into message_events(message_id, type, from_status, to_status, source, detail)175 values (${messageId}, ${o.type}, ${from}, ${from}, ${o.source}, ${tx.json({ ...(o.detail ?? {}), ignored: true, wanted: to } as any)})`176 return false177 }178 const final = !IN_QUEUE.includes(to) && to !== "HELD" && to !== "SUBMITTED"179 const stamp = STAMP[to]180 await tx`update messages set status = ${to},181 error_code = ${o.errorCode ?? (to === "SUBMITTED" || to === "DELIVERED" ? null : m.error_code)},182 error_detail = ${o.errorDetail ?? (to === "SUBMITTED" || to === "DELIVERED" ? null : m.error_detail)},183 parts_sent = coalesce(${o.partsSent ?? null}, parts_sent),184 finalized_at = ${final || to === "DELIVERED" ? tx`now()` : tx`finalized_at`}185 ${stamp ? tx`, ${tx(stamp)} = coalesce(${o.at ?? null}, now())` : tx``}186 where id = ${messageId}`187 await tx`insert into message_events(message_id, type, from_status, to_status, source, detail)188 values (${messageId}, ${o.type}, ${from}, ${to}, ${o.source}, ${tx.json((o.detail ?? {}) as any)})`189 if (!IN_QUEUE.includes(to)) await tx`delete from message_queue where message_id = ${messageId}`190 const metric = (STATUS_METRIC as any)[to]191 if (metric) await bump(tx, metric, m.application_id, m.sim_id)192 const hook = STATUS_WEBHOOK[to]193 if (hook) {194 const [cur] = await tx`select * from messages where id = ${messageId}`195 await enqueueEvent(tx, { type: hook, scope: "message", applicationId: m.application_id, simId: m.sim_id, data: publicMessage(cur, false) })196 }197 return true198}199200export async function cancelMessage(id: string, source: "api" | "admin", scopeAppId?: string | null) {201 const res = await sql.begin(async tx => {202 const [m] = await tx`select * from messages where id = ${id} and direction = 'outbound' for update`203 if (!m || (scopeAppId !== undefined && m.application_id !== scopeAppId)) throw notFound("message")204 if (!CANCELLABLE.includes(m.status)) throw conflict("not_cancellable", `le message est déjà ${String(m.status).toLowerCase()} : seul un message non transmis à l'appareil peut être annulé`)205 await transition(tx, id, "CANCELLED", { source, type: "message.cancelled" })206 const [cur] = await tx`select * from messages where id = ${id}`207 return cur208 })209 changed("messages")210 return res211}212213export async function approveMessage(id: string) {214 const res = await sql.begin(async tx => {215 const [m] = await tx`select * from messages where id = ${id} for update`216 if (!m) throw notFound("message")217 if (m.status !== "HELD") throw conflict("not_held", "ce message n'attend pas d'approbation")218 if (await getSetting("kill_switch", false)) throw new ApiError(503, "kill_switch_active", "arrêt d'urgence actif")219 await transition(tx, id, "QUEUED", { source: "admin", type: "message.approved" })220 await tx`insert into message_queue(message_id, device_id, sim_id) values (${id}, ${m.device_id}, ${m.sim_id}) on conflict do nothing`221 return m222 })223 poke(res.device_id); changed("messages")224}225226/** SMS entrant remonté par un appareil. Donnée non fiable : stockée et relayée, jamais interprétée comme une commande. */227export async function recordInbound(tx: Tx, deviceId: string, eventId: string, d: { from: string; subscription_id: number; text: string; received_at?: string; parts?: number }) {228 const [sim] = await tx`select * from sim_profiles where device_id = ${deviceId} and subscription_id = ${d.subscription_id}`229 const from = normalizeSender(d.from, sim?.country_iso)230 const text = String(d.text ?? "").slice(0, 4000)231 const seg = segmentInfo(text)232 const id = newId("sms")233 const convId = sim ? await touchConversation(tx, sim.id, from, "inbound") : null234 const received = d.received_at && !Number.isNaN(Date.parse(d.received_at)) ? new Date(d.received_at) : new Date()235 const [m] = await tx`236 insert into messages(id, direction, status, device_id, sim_id, conversation_id, from_number, to_number, text_enc, text_chars, encoding, segments, device_event_id, received_at)237 values (${id}, 'inbound', 'RECEIVED', ${deviceId}, ${sim?.id ?? null}, ${convId}, ${from}, ${sim ? sim.manual_number ?? sim.reported_number : null},238 ${seal(text, textCtx(id))}, ${seg.chars}, ${seg.encoding}, ${Math.max(Number(d.parts) || seg.segments, 1)}, ${eventId}, ${received})239 on conflict (device_id, device_event_id) do nothing returning *`240 if (!m) return null241 await bump(tx, "inbound", null, sim?.id ?? null)242243 // Mots-clés de désinscription (LCAP) : effet limité à la liste d'exclusion, aucune autre action automatique.244 const word = text.trim().toUpperCase()245 const e164 = tryE164(from, sim?.country_iso)246 if (e164 && word.length <= 20) {247 if ((await getSetting<string[]>("opt_out_keywords", [])).includes(word))248 await tx`insert into opt_outs(number, source, keyword, message_id) values (${e164}, 'keyword', ${word}, ${id}) on conflict do nothing`249 else if ((await getSetting<string[]>("opt_in_keywords", [])).includes(word))250 await tx`delete from opt_outs where number = ${e164} and source = 'keyword'`251 }252 await enqueueEvent(tx, { type: "sms.received", scope: "inbound", simId: sim?.id ?? null, data: { ...publicMessage(m, false), text } })253 return m254}255256/** Balayage périodique : expirations et messages restés sans nouvelles de l'appareil. */257export async function sweep() {258 const n = await sql.begin(async tx => {259 let count = 0260 const due = await tx`select id from messages where status in ('HELD','QUEUED') and expires_at < now() limit 200`261 for (const r of due) if (await transition(tx, r.id, "EXPIRED", { source: "system", type: "message.expired", errorCode: "expired", errorDetail: "délai de validité dépassé avant la transmission à l'appareil" })) count++262 // Transmis à l'appareil, puis plus aucune nouvelle 24 h après l'expiration : l'issue est déclarée inconnue (jamais renvoyé).263 const silent = await tx`select id from messages where status in ('DISPATCHED','ACCEPTED','SUBMITTING') and expires_at < now() - interval '24 hours' limit 200`264 for (const r of silent) if (await transition(tx, r.id, "UNKNOWN", { source: "system", type: "message.unknown", errorCode: "device_silent", errorDetail: "aucune issue rapportée par l'appareil" })) count++265 return count266 })267 if (n) { changed("messages"); pokeWebhooks() }268 return n269}270271/** Politique de rétention : efface le contenu des SMS anciens, puis les enregistrements très anciens. */272export async function applyRetention() {273 const textDays = await getSetting("retention_days_text", 90), recDays = await getSetting("retention_days_records", 730)274 const a = await sql`update messages set text_enc = null where text_enc is not null and created_at < now() - make_interval(days => ${textDays})275 and status not in ('HELD','QUEUED','DISPATCHED','ACCEPTED','SUBMITTING')`276 await sql`update webhook_deliveries set payload_enc = null where payload_enc is not null and status <> 'pending' and created_at < now() - make_interval(days => ${Math.min(textDays, 30)})`277 const b = await sql`delete from messages where created_at < now() - make_interval(days => ${recDays}) and status not in ('HELD','QUEUED','DISPATCHED','ACCEPTED','SUBMITTING')`278 await sql`delete from device_events where received_at < now() - interval '90 days'`279 await sql`delete from webhook_deliveries where created_at < now() - make_interval(days => ${recDays})`280 await sql`delete from auth_challenges where expires_at < now()`281 await sql`delete from admin_sessions where expires_at < now()`282 return { texts_purged: a.count, messages_deleted: b.count }283}284