SPB Git

Repository Public

service.ts 9.0 KB 170 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr SMS Gateway8 * File             : backend/src/webhooks/service.ts9 * Module           : webhooks10 * 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 http from "node:http"43import https from "node:https"44import { bus, changed, pokeWebhooks } from "../bus.ts"45import { sql, type Tx } from "../db.ts"46import { hmacHex, open, seal } from "../security/crypto.ts"47import { checkWebhookUrl, resolvePublic } from "../security/ssrf.ts"48import { iso, newId, randomToken, unprocessable } from "../util.ts"4950export const WEBHOOK_EVENTS = ["sms.received", "sms.submitted", "sms.delivered", "sms.failed", "sms.unknown", "device.online", "device.offline", "sim.unavailable"] as const51export type WebhookEvent = (typeof WEBHOOK_EVENTS)[number]52const BACKOFF_S = process.env.SMS_WEBHOOK_BACKOFF_S ? process.env.SMS_WEBHOOK_BACKOFF_S.split(",").map(Number) : [30, 120, 600, 1800, 7200, 21600] // 7 tentatives au total, puis abandon53const MAX_STREAK = 30                                        // échecs consécutifs avant désactivation automatique5455export async function createWebhook(a: { applicationId: string | null; url: string; events: string[]; description?: string }) {56  checkWebhookUrl(a.url)57  const events = [...new Set(a.events)]58  if (!events.length || events.some(e => !WEBHOOK_EVENTS.includes(e as WebhookEvent)))59    throw unprocessable("invalid_events", `événements acceptés : ${WEBHOOK_EVENTS.join(", ")}`)60  const id = newId("wh"), secret = "whsec_" + randomToken(32)61  await sql`insert into webhooks(id, application_id, url, description, events, secret_enc)62            values (${id}, ${a.applicationId}, ${a.url}, ${a.description ?? ""}, ${events}, ${seal(secret, "webhook-secret:" + id)})`63  const [w] = await sql`select * from webhooks where id = ${id}`64  return { ...publicWebhook(w), secret }65}66export const publicWebhook = (w: any) => ({67  id: w.id, application_id: w.application_id, url: w.url, description: w.description, events: w.events, enabled: w.enabled,68  failure_streak: w.failure_streak, disabled_reason: w.disabled_reason, created_at: iso(w.created_at),69})7071/**72 * Boîte d'envoi transactionnelle : l'événement est inscrit dans la même transaction que le changement d'état qui le cause.73 * Portée : événements de statut → webhooks de l'application du message + webhooks d'administration ;74 * sms.received → administration + applications autorisées sur la SIM ; événements d'appareil → tous les abonnés.75 */76export async function enqueueEvent(tx: Tx, ev: { type: WebhookEvent; data: Record<string, unknown>; applicationId?: string | null; simId?: string | null; scope: "message" | "inbound" | "device" }) {77  const hooks = await tx`78    select w.id from webhooks w left join applications a on a.id = w.application_id79    where w.enabled and ${ev.type} = any(w.events) and (w.application_id is null or a.enabled)80      and ${ev.scope === "message" ? tx`(w.application_id is null or w.application_id = ${ev.applicationId ?? ""})`81        : ev.scope === "inbound" ? tx`(w.application_id is null or a.allowed_sim_ids is null or ${ev.simId ?? ""} = any(a.allowed_sim_ids))`82        : tx`true`}`83  if (!hooks.length) return84  const eventId = newId("evt")85  const payload = JSON.stringify({ event: ev.type, id: eventId, created_at: new Date().toISOString(), data: ev.data })86  for (const h of hooks) {87    const id = newId("whd")88    await tx`insert into webhook_deliveries(id, webhook_id, event_id, event_type, payload_enc)89             values (${id}, ${h.id}, ${eventId}, ${ev.type}, ${seal(payload, "webhook-payload:" + id)})`90  }91}9293function post(u: URL, pinned: { address: string; family: number }, body: string, headers: Record<string, string>): Promise<number> {94  return new Promise((resolve, reject) => {95    const mod = u.protocol === "https:" ? https : http96    const req = mod.request(u, {97      method: "POST", headers: { ...headers, "content-length": Buffer.byteLength(body).toString() }, timeout: 10_000,98      // Connexion à l'adresse validée, pas à une seconde résolution (anti « DNS rebinding »).99      lookup: (_h: string, o: any, cb: any) => (o?.all ? cb(null, [pinned]) : cb(null, pinned.address, pinned.family)),100    }, res => { res.resume(); res.on("end", () => resolve(res.statusCode ?? 0)) })101    req.on("timeout", () => req.destroy(new Error("délai dépassé (10 s)")))102    req.on("error", reject)103    req.end(body)104  })105}106107async function deliverOne(d: any) {108  const [w] = await sql`select * from webhooks where id = ${d.webhook_id}`109  let code = 0, err: string | null = null110  try {111    if (!w?.enabled) throw new Error("webhook désactivé")112    const u = checkWebhookUrl(w.url)113    const pinned = await resolvePublic(u)114    const body = open(d.payload_enc, "webhook-payload:" + d.id)!115    const secret = open(w.secret_enc, "webhook-secret:" + w.id)!116    const ts = Math.floor(Date.now() / 1000).toString()117    code = await post(u, pinned, body, {118      "content-type": "application/json", "user-agent": "MacLustr-SMS-Webhooks/1",119      "x-maclustr-event": d.event_type, "x-maclustr-event-id": d.event_id, "x-maclustr-delivery": d.id,120      "x-maclustr-timestamp": ts, "x-maclustr-signature": "v1=" + hmacHex(secret, `${ts}.${body}`),121    })122    if (code < 200 || code >= 300) throw new Error(`réponse HTTP ${code}`) // les redirections ne sont pas suivies123  } catch (e: any) { err = String(e?.message ?? e).slice(0, 300) }124125  const attempts = d.attempts + 1126  if (!err) {127    await sql`update webhook_deliveries set status = 'delivered', attempts = ${attempts}, delivered_at = now(), last_status_code = ${code}, last_error = null where id = ${d.id}`128    await sql`update webhooks set failure_streak = 0 where id = ${d.webhook_id}`129  } else {130    const final = attempts > BACKOFF_S.length || !w?.enabled131    await sql`update webhook_deliveries set status = ${final ? "failed" : "pending"}, attempts = ${attempts}, last_status_code = ${code || null}, last_error = ${err},132              next_attempt_at = now() + make_interval(secs => ${final ? 0 : BACKOFF_S[attempts - 1]}) where id = ${d.id}`133    if (w?.enabled) {134      const [r] = await sql`update webhooks set failure_streak = failure_streak + 1 where id = ${w.id} returning failure_streak`135      if (r.failure_streak >= MAX_STREAK)136        await sql`update webhooks set enabled = false, disabled_reason = ${`désactivé après ${MAX_STREAK} échecs consécutifs`} where id = ${w.id}`137    }138  }139  changed("webhooks")140}141142let running = false, again = false143async function drain() {144  if (running) { again = true; return }145  running = true146  try {147    for (;;) {148      // Réservation : la prochaine tentative est repoussée avant l'appel, pour qu'un arrêt brutal ne livre pas deux fois en rafale.149      const due = await sql`150        update webhook_deliveries set next_attempt_at = now() + interval '60 seconds'151        where id in (select id from webhook_deliveries where status = 'pending' and next_attempt_at <= now() order by next_attempt_at limit 10 for update skip locked)152        returning *`153      if (!due.length) break154      await Promise.all(due.map(d => deliverOne(d).catch(() => {})))155    }156  } finally { running = false; if (again) { again = false; void drain() } }157}158159export function startWebhookWorker() {160  bus.on("webhooks", () => void drain().catch(() => {}))161  const t = setInterval(() => void drain().catch(() => {}), process.env.SMS_WEBHOOK_BACKOFF_S ? 300 : 5000)162  t.unref()163  return () => clearInterval(t)164}165export async function redeliver(id: string) {166  const r = await sql`update webhook_deliveries set status = 'pending', next_attempt_at = now() where id = ${id} and payload_enc is not null returning id`167  pokeWebhooks()168  return r.length > 0169}170
Files main
Menu

Theme