SPB Git

Repository Public

index.ts 19.6 KB 261 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr SMS Gateway8 * File             : sdk/typescript/src/index.ts9 * Module           : sdk10 * 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 */4142// Client TypeScript de MacLustr SMS Gateway. Fonctionne sous Node ≥ 20, Bun, Deno et dans tout environnement doté de fetch + WebCrypto.4344export const DEFAULT_BASE_URL = "https://sms.spboucher.ai"45export type MessageStatus = "held" | "queued" | "dispatched" | "accepted" | "submitting" | "submitted" | "delivered" | "failed" | "expired" | "cancelled" | "unknown" | "received"46/** Statuts dont un message ne sort plus. « submitted » (remis au réseau) n'en fait pas partie. */47export const FINAL_STATUSES: readonly MessageStatus[] = ["delivered", "failed", "expired", "cancelled", "unknown"]48export type WebhookEventName = "sms.received" | "sms.submitted" | "sms.delivered" | "sms.failed" | "sms.unknown" | "device.online" | "device.offline" | "sim.unavailable"4950export interface MessageEvent { type: string; from: string | null; to: string | null; source: string; detail: Record<string, unknown>; at: string | null }51export interface Message {52  id: string; direction: "outbound" | "inbound"; status: MessageStatus; to: string | null; from: string | null; text: string | null; text_purged: boolean53  device_id: string | null; sim_id: string | null; application_id: string | null; conversation_id: string | null54  encoding: "gsm7" | "ucs2"; segments: number; characters: number; error: { code: string; detail: string | null } | null55  created_at: string | null; expires_at: string | null; dispatched_at: string | null; accepted_at: string | null; submitted_at: string | null56  delivered_at: string | null; finalized_at: string | null; received_at: string | null57  events?: MessageEvent[]58  /** true si l'API a renvoyé un message déjà créé avec la même Idempotency-Key (aucun second envoi). */59  replayed?: boolean60}61export interface Sim {62  id: string; device_id: string; subscription_id: number; slot_index: number | null; carrier_name: string; display_name: string; label: string63  type: "physical" | "esim" | "unknown"; number: string | null; number_source: "manual" | "reported" | null; state: string; signal_level: number | null64  roaming: boolean | null; active: boolean; send_enabled: boolean; daily_limit: number; updated_at: string | null65}66export interface Device {67  id: string; name: string; manufacturer: string; model: string; android_version: string; app_version: string; online: boolean; enabled: boolean68  maintenance: boolean; available: boolean; last_seen_at: string | null; battery_pct: number | null; charging: boolean | null; network: string | null69  gateway_state: string | null; sims: Sim[]70}71export interface PhoneNumber { number: string; sim_id: string; device_id: string; carrier_name: string; source: string; label: string; send_enabled: boolean; active: boolean }72export interface Conversation { id: string; sim_id: string; device_id: string; number: string | null; peer: string; last_message_at: string | null; last_direction: string | null; inbound_count: number; outbound_count: number; unread: number }73export interface Webhook { id: string; url: string; description: string; events: WebhookEventName[]; enabled: boolean; failure_streak: number; created_at: string | null; /** Présent uniquement à la création. */ secret?: string }74export type VerificationStatus = "pending" | "approved" | "failed" | "expired" | "cancelled"75/** Vérification d'un numéro par code. Le code lui-même n'apparaît jamais dans l'API. */76export interface Verification { id: string; to: string; status: VerificationStatus; attempts: number; attempts_remaining: number; created_at: string | null; expires_at: string | null; approved_at: string | null; message_id: string | null; message_status?: MessageStatus | null }77/** `valid` vaut true une seule fois, quand le bon code est saisi. Ne se fier qu'à ce champ. */78export interface VerificationCheck extends Verification { valid: boolean }79export interface StartVerificationParams { to: string; brand?: string; locale?: "fr" | "en"; ttlSeconds?: number; codeLength?: number; simId?: string; from?: string }80export interface Page<T> { data: T[]; has_more: boolean; next_cursor: string | null }81export interface Usage { application_id: string; quota: { daily: number; used_today: number; rate_per_minute: number }; from: string; to: string; totals: Record<string, number>; days: Record<string, unknown>[] }82export interface Queue { pending: number; in_flight: number; held: number; oldest_pending_at: string | null; items: Record<string, unknown>[] }83export interface Health { status: "ok" | "degraded"; version: string; time: string }84export interface WebhookEvent<D = Record<string, any>> { event: WebhookEventName | "webhook.test"; id: string; created_at: string; data: D }8586export interface SendParams { to: string; text: string; deviceId?: string; simId?: string; from?: string; ttlSeconds?: number; deliveryReport?: boolean; idempotencyKey?: string }87export interface ListMessagesParams { status?: string; to?: string; deviceId?: string; simId?: string; createdAfter?: string; createdBefore?: string; limit?: number; cursor?: string }88export interface InboxParams { from?: string; simId?: string; createdAfter?: string; limit?: number; cursor?: string }89export interface ClientOptions { apiKey?: string; baseUrl?: string; timeoutMs?: number; maxRetries?: number; retryDelayMs?: number; fetch?: typeof fetch; sleep?: (ms: number) => Promise<void> }9091/** Erreur renvoyée par l'API (ou échec réseau : status = 0, code = "network_error"). */92export class MacLustrSMSError extends Error {93  constructor(public status: number, public code: string, message: string, public details?: unknown, retryAfter?: number | null) { super(`${code} (${status}) : ${message}`); this.name = "MacLustrSMSError"; this.apiMessage = message; this.retryAfter = retryAfter ?? null }94  apiMessage: string95  /** Réponses 429 : secondes à attendre avant de réessayer (en-tête Retry-After), null si le serveur ne l'indique pas. */96  retryAfter: number | null97}98export class MacLustrSMSTimeout extends MacLustrSMSError {99  constructor(public lastMessage: Message, timeoutMs: number) { super(0, "wait_timeout", `statut « ${lastMessage.status} » après ${timeoutMs} ms`); this.name = "MacLustrSMSTimeout" }100}101export class WebhookVerificationError extends Error { constructor(m: string) { super(m); this.name = "WebhookVerificationError" } }102103const env = (k: string): string | undefined => (globalThis as any).process?.env?.[k]104const enc = encodeURIComponent105const hex = (b: ArrayBuffer) => [...new Uint8Array(b)].map(x => x.toString(16).padStart(2, "0")).join("")106function timingSafeEqual(a: string, b: string) {107  if (a.length !== b.length) return false108  let d = 0109  for (let i = 0; i < a.length; i++) d |= a.charCodeAt(i) ^ b.charCodeAt(i)110  return d === 0111}112113/**114 * Vérifie une livraison de webhook et renvoie l'événement décodé.115 * `body` = corps BRUT reçu (avant JSON.parse) ; `timestamp` = en-tête X-MacLustr-Timestamp ; `signature` = en-tête X-MacLustr-Signature (« v1=<hex> »).116 * Dédupliquez aussi sur `event.id` : une livraison peut être retentée.117 */118export async function verifyWebhook<D = Record<string, any>>(p: { secret: string; timestamp: string | number | null | undefined; body: string | Uint8Array; signature: string | null | undefined; toleranceSeconds?: number; now?: number }): Promise<WebhookEvent<D>> {119  const ts = Number(String(p.timestamp ?? "").trim())120  if (!Number.isInteger(ts) || !String(p.timestamp ?? "").trim()) throw new WebhookVerificationError("horodatage absent ou invalide")121  const tol = p.toleranceSeconds ?? 300122  if (tol && Math.abs((p.now ?? Date.now() / 1000) - ts) > tol) throw new WebhookVerificationError("horodatage hors tolérance (rejeu possible)")123  const te = new TextEncoder()124  const raw = typeof p.body === "string" ? te.encode(p.body) : p.body125  const data = new Uint8Array([...te.encode(`${ts}.`), ...raw])126  const key = await crypto.subtle.importKey("raw", te.encode(p.secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"])127  const expected = hex(await crypto.subtle.sign("HMAC", key, data))128  const given = String(p.signature ?? "").split(",").map(s => s.trim()).filter(s => s.startsWith("v1=")).map(s => s.slice(3))129  if (!given.some(g => timingSafeEqual(expected, g))) throw new WebhookVerificationError("signature invalide")130  try { return JSON.parse(new TextDecoder().decode(raw)) } catch { throw new WebhookVerificationError("corps JSON invalide") }131}132133/**134 * Client de l'API https://sms.spboucher.ai/v1.135 * Réessais : uniquement sur échec de connexion, réponse 5xx ou 429. Un envoi porte toujours une Idempotency-Key,136 * réutilisée à l'identique par les réessais : le serveur ne crée jamais deux messages pour un même appel.137 */138export class MacLustrSMS {139  readonly baseUrl: string140  private apiKey: string; private timeoutMs: number; private maxRetries: number; private retryDelayMs: number141  private fetchImpl: typeof fetch; private sleep: (ms: number) => Promise<void>142143  constructor(o: ClientOptions = {}) {144    this.apiKey = o.apiKey ?? env("MACLUSTR_SMS_API_KEY") ?? ""145    if (!this.apiKey) throw new Error("clé API manquante : passez { apiKey } ou définissez MACLUSTR_SMS_API_KEY")146    this.baseUrl = (o.baseUrl ?? env("MACLUSTR_SMS_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "")147    this.timeoutMs = o.timeoutMs ?? 15_000; this.maxRetries = o.maxRetries ?? 3; this.retryDelayMs = o.retryDelayMs ?? 500148    this.fetchImpl = o.fetch ?? ((...a) => fetch(...a)); this.sleep = o.sleep ?? (ms => new Promise(r => setTimeout(r, ms)))149  }150151  private async request<T>(method: string, path: string, o: { query?: Record<string, unknown>; body?: unknown; headers?: Record<string, string>; auth?: boolean; /** false : opération non idempotente, jamais réessayée */ retry?: boolean } = {}): Promise<{ json: T; headers: Headers }> {152    const qs = new URLSearchParams()153    for (const [k, v] of Object.entries(o.query ?? {})) if (v !== undefined && v !== null) qs.set(k, String(v))154    const url = this.baseUrl + path + (qs.size ? `?${qs}` : "")155    const headers: Record<string, string> = { accept: "application/json", ...(o.auth === false ? {} : { authorization: `Bearer ${this.apiKey}` }), ...(o.body !== undefined ? { "content-type": "application/json" } : {}), ...(o.headers ?? {}) }156    for (let attempt = 0; ; attempt++) {157      let err: MacLustrSMSError, retryAfter: number | null = null158      try {159        const res = await this.fetchImpl(url, { method, headers, body: o.body === undefined ? undefined : JSON.stringify(o.body), signal: AbortSignal.timeout(this.timeoutMs) })160        const text = await res.text()161        let json: any = null162        try { json = text ? JSON.parse(text) : null } catch {}163        if (res.ok) return { json, headers: res.headers }164        const e = json?.error ?? {}165        const ra = Number(res.headers.get("retry-after"))166        retryAfter = res.headers.get("retry-after") && Number.isFinite(ra) ? ra * 1000 : null167        err = new MacLustrSMSError(res.status, e.code ?? "http_error", e.message ?? `HTTP ${res.status}`, e.details, res.status === 429 && retryAfter !== null ? retryAfter / 1000 : null)168        if (res.status !== 429 && res.status < 500) throw err169      } catch (e: any) {170        if (e instanceof MacLustrSMSError) { if (e.status !== 429 && e.status < 500 && e.status !== 0) throw e; err = e }171        else err = new MacLustrSMSError(0, "network_error", String(e?.cause?.message ?? e?.message ?? e))172      }173      if (o.retry === false || attempt >= this.maxRetries) throw err174      await this.sleep(Math.min(retryAfter ?? this.retryDelayMs * 2 ** attempt * (err.status === 429 ? 4 : 1), 30_000))175    }176  }177  private async *iterate<T>(path: string, query: Record<string, unknown>): AsyncGenerator<T> {178    const q = { ...query }179    for (;;) {180      const { json } = await this.request<Page<T>>("GET", path, { query: q })181      yield* json.data182      if (!json.has_more || !json.next_cursor) return183      q.cursor = json.next_cursor184    }185  }186  private static mq = (p: ListMessagesParams) => ({ status: p.status, to: p.to, device_id: p.deviceId, sim_id: p.simId, created_after: p.createdAfter, created_before: p.createdBefore, limit: p.limit, cursor: p.cursor })187  private static iq = (p: InboxParams) => ({ from: p.from, sim_id: p.simId, created_after: p.createdAfter, limit: p.limit, cursor: p.cursor })188189  /** Met un SMS en file. Statut initial « queued » (ou « held » si l'application exige une approbation humaine). */190  async send(p: SendParams): Promise<Message> {191    const body: Record<string, unknown> = { to: p.to, text: p.text }192    if (p.deviceId !== undefined) body.device_id = p.deviceId193    if (p.simId !== undefined) body.sim_id = p.simId194    if (p.from !== undefined) body.from = p.from195    if (p.ttlSeconds !== undefined) body.ttl_seconds = p.ttlSeconds196    if (p.deliveryReport !== undefined) body.delivery_report = p.deliveryReport197    const { json, headers } = await this.request<Message>("POST", "/v1/messages", { body, headers: { "idempotency-key": p.idempotencyKey ?? crypto.randomUUID() } })198    return { ...json, replayed: headers.get("idempotent-replayed") === "true" }199  }200  async getMessage(id: string): Promise<Message> { return (await this.request<Message>("GET", `/v1/messages/${enc(id)}`)).json }201  async listMessages(p: ListMessagesParams = {}): Promise<Page<Message>> { return (await this.request<Page<Message>>("GET", "/v1/messages", { query: MacLustrSMS.mq(p) })).json }202  /** Parcourt tout l'historique, page après page. */203  iterMessages(p: ListMessagesParams = {}): AsyncGenerator<Message> { return this.iterate<Message>("/v1/messages", MacLustrSMS.mq(p)) }204  /** Annule un message pas encore transmis à l'appareil (sinon erreur 409 `not_cancellable`). */205  async cancel(id: string): Promise<Message> { return (await this.request<Message>("POST", `/v1/messages/${enc(id)}/cancel`, { body: {} })).json }206  /**207   * Attend que le message soit remis au réseau (`until: "submitted"`, défaut) ou dans un statut final (`until: "final"`).208   * « submitted » ne signifie pas « livré » ; « unknown » = issue ambiguë : ne renvoyez pas à l'aveugle.209   */210  async wait(id: string, o: { timeoutMs?: number; until?: "submitted" | "final"; intervalMs?: number } = {}): Promise<Message> {211    const timeout = o.timeoutMs ?? 60_000, interval = o.intervalMs ?? 1000, deadline = Date.now() + timeout212    for (;;) {213      const m = await this.getMessage(id)214      if (FINAL_STATUSES.includes(m.status) || ((o.until ?? "submitted") === "submitted" && m.status === "submitted")) return m215      if (Date.now() + interval > deadline) throw new MacLustrSMSTimeout(m, timeout)216      await this.sleep(interval)217    }218  }219220  async inbox(p: InboxParams = {}): Promise<Page<Message>> { return (await this.request<Page<Message>>("GET", "/v1/inbox", { query: MacLustrSMS.iq(p) })).json }221  iterInbox(p: InboxParams = {}): AsyncGenerator<Message> { return this.iterate<Message>("/v1/inbox", MacLustrSMS.iq(p)) }222  async conversations(p: { simId?: string; limit?: number; cursor?: string } = {}): Promise<Page<Conversation>> { return (await this.request<Page<Conversation>>("GET", "/v1/conversations", { query: { sim_id: p.simId, limit: p.limit, cursor: p.cursor } })).json }223  async conversationMessages(id: string, p: { limit?: number; cursor?: string } = {}): Promise<Page<Message>> { return (await this.request<Page<Message>>("GET", `/v1/conversations/${enc(id)}/messages`, { query: p })).json }224225  async devices(): Promise<Device[]> { return (await this.request<{ data: Device[] }>("GET", "/v1/devices")).json.data }226  async device(id: string): Promise<Device> { return (await this.request<Device>("GET", `/v1/devices/${enc(id)}`)).json }227  async sims(deviceId: string): Promise<Sim[]> { return (await this.request<{ data: Sim[] }>("GET", `/v1/devices/${enc(deviceId)}/sims`)).json.data }228  async numbers(): Promise<PhoneNumber[]> { return (await this.request<{ data: PhoneNumber[] }>("GET", "/v1/numbers")).json.data }229230  /** Crée un webhook. Conservez `secret` : il n'est renvoyé qu'ici. */231  async createWebhook(p: { url: string; events: WebhookEventName[]; description?: string }): Promise<Webhook> { return (await this.request<Webhook>("POST", "/v1/webhooks", { body: p })).json }232  async listWebhooks(): Promise<Webhook[]> { return (await this.request<{ data: Webhook[] }>("GET", "/v1/webhooks")).json.data }233  async deleteWebhook(id: string): Promise<boolean> { return !!(await this.request<{ deleted: boolean }>("DELETE", `/v1/webhooks/${enc(id)}`)).json?.deleted }234235  /**236   * Envoie un code de vérification par SMS (scope `verify:manage`). Conservez `id` dans la session serveur de l'utilisateur.237   * Jamais réessayée automatiquement : cette route n'a pas d'Idempotency-Key, un réessai aveugle pourrait envoyer deux codes.238   * Sur 429 (`verification_too_soon`, `verification_rate_limited`), l'erreur porte `retryAfter` (secondes).239   */240  async startVerification(p: StartVerificationParams): Promise<Verification> {241    const body: Record<string, unknown> = { to: p.to }242    if (p.brand !== undefined) body.brand = p.brand243    if (p.locale !== undefined) body.locale = p.locale244    if (p.ttlSeconds !== undefined) body.ttl_seconds = p.ttlSeconds245    if (p.codeLength !== undefined) body.code_length = p.codeLength246    if (p.simId !== undefined) body.sim_id = p.simId247    if (p.from !== undefined) body.from = p.from248    return (await this.request<Verification>("POST", "/v1/verifications", { body, retry: false })).json249  }250  /** Vérifie le code saisi. `valid` vaut true une seule fois. Jamais réessayée (un essai serait consommé deux fois). */251  async checkVerification(id: string, code: string | number): Promise<VerificationCheck> { return (await this.request<VerificationCheck>("POST", `/v1/verifications/${enc(id)}/check`, { body: { code: String(code) }, retry: false })).json }252  async getVerification(id: string): Promise<Verification> { return (await this.request<Verification>("GET", `/v1/verifications/${enc(id)}`)).json }253254  async usage(p: { from?: string; to?: string } = {}): Promise<Usage> { return (await this.request<Usage>("GET", "/v1/usage", { query: p })).json }255  async queue(): Promise<Queue> { return (await this.request<Queue>("GET", "/v1/queue")).json }256  async health(): Promise<Health> { return (await this.request<Health>("GET", "/v1/health", { auth: false })).json }257258  static verifyWebhook = verifyWebhook259}260export default MacLustrSMS261
Files main
Menu

Theme