SPB Git

Repository Public

maclustr-sms.mjs 31.5 KB 464 lines javascript

1#!/usr/bin/env node2/**3 * =============================================================================4 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION5 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project          : MacLustr SMS Gateway9 * File             : cli/maclustr-sms.mjs10 * Module           : cli11 * Repository       : https://git.spboucher.ai/maclustr-sms12 * Project Website  : https://sms.spboucher.ai13 * Created          : 2026-11-3014 * Last Modified    : 2026-11-3015 *16 * Author           : Simon-Pierre Boucher17 * Position         : Professor of Finance18 * Institution      : Université du Québec en Outaouais (UQO)19 * Organization     : SP Boucher20 * Website          : https://spboucher.ai21 * Git              : https://git.spboucher.ai22 *23 * Preferred Contact: admin@spboucher.ai24 * Technical Contact: dev@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// maclustr-sms — ligne de commande de MacLustr SMS Gateway. Aucune dépendance (Node ≥ 20).44// La clé API n'est jamais acceptée en argument : variable MACLUSTR_SMS_API_KEY, sinon trousseau macOS (service « maclustr-sms »).45import { spawnSync } from "node:child_process"46import { randomUUID } from "node:crypto"47import os from "node:os"48import tls from "node:tls"4950const VERSION = "1.0.0"51const SERVICE = "maclustr-sms"52const FINAL = ["delivered", "failed", "expired", "cancelled", "unknown"]53const HELP = `maclustr-sms ${VERSION} — MacLustr SMS Gateway5455Usage : maclustr-sms <commande> [options]      (ajoutez --json pour une sortie exploitable par un programme ou un agent)5657  status                          santé du service, appareils, file, quota58  devices list                    appareils Android59  sims list [--device ID]         SIM et eSIM60  numbers                         numéros configurés61  send --to N --text T            envoyer un SMS62       [--sim ID] [--device ID] [--from N] [--ttl S] [--idempotency-key K] [--wait [S]] [--final]63  message <id>                    statut et journal d'un message64  messages [--status s1,s2] [--to N] [--limit n] [--all]65  cancel <id>                     annuler un message non transmis66  inbox [--from N] [--sim ID] [--limit n] [--all]67  conversations [--limit n]       conversations ;  conversations <id> : messages d'une conversation68  queue                           file d'attente de l'application69  usage [--from AAAA-MM-JJ] [--to AAAA-MM-JJ]70  webhooks list | add --url U --events e1,e2 [--description D] | rm <id>71  verify start --to N [--brand B] [--locale fr|en] [--ttl S]     envoyer un code de vérification72  verify check <id> --code C      contrôler le code saisi (sortie 0 si valide, 3 sinon)73  verify status <id>              état d'une vérification74  doctor                          diagnostic complet (réseau, TLS, clé, scopes, appareils, SIM, file)75  login | logout                  enregistre / efface la clé dans le trousseau macOS (lue sur l'entrée standard, sans écho)7677Environnement : MACLUSTR_SMS_API_KEY (clé), MACLUSTR_SMS_URL (défaut https://sms.spboucher.ai)78Codes de sortie : 0 succès · 1 erreur d'API ou de réseau · 2 usage · 3 message en échec · 4 issue inconnue · 5 délai dépassé`7980// ── arguments ────────────────────────────────────────────────────────────────81const BOOL = new Set(["json", "all", "final", "help", "version"])82function parseArgs(argv) {83  const pos = [], opt = {}84  for (let i = 0; i < argv.length; i++) {85    const a = argv[i]86    if (!a.startsWith("--")) { pos.push(a); continue }87    const eq = a.indexOf("=")88    const k = eq > 0 ? a.slice(2, eq) : a.slice(2)89    if (eq > 0) opt[k] = a.slice(eq + 1)90    else if (BOOL.has(k)) opt[k] = true91    else if (k === "wait") opt.wait = argv[i + 1] !== undefined && /^\d+(\.\d+)?$/.test(argv[i + 1]) ? argv[++i] : "60"92    else if (argv[i + 1] === undefined) usage(`option --${k} : valeur manquante`)93    else opt[k] = argv[++i]94  }95  return { pos, opt }96}97class CliError extends Error { constructor(exit, code, message, extra = {}) { super(message); this.exit = exit; this.code = code; this.extra = extra } }98function usage(msg) { throw new CliError(2, "usage", msg) }99100// ── clé et transport ─────────────────────────────────────────────────────────101function keychain(args, input) { return spawnSync("security", args, { encoding: "utf8", input }) }102function loadKey() {103  if (process.env.MACLUSTR_SMS_API_KEY) return { key: process.env.MACLUSTR_SMS_API_KEY.trim(), source: "MACLUSTR_SMS_API_KEY" }104  if (process.platform === "darwin" && process.env.MACLUSTR_SMS_NO_KEYCHAIN !== "1") {105    const r = keychain(["find-generic-password", "-s", SERVICE, "-w"])106    if (r.status === 0 && r.stdout.trim()) return { key: r.stdout.trim(), source: "trousseau macOS" }107  }108  return null109}110const BASE = (process.env.MACLUSTR_SMS_URL || "https://sms.spboucher.ai").replace(/\/+$/, "")111const sleep = ms => new Promise(r => setTimeout(r, ms))112let KEY = null113function needKey() {114  KEY ??= loadKey()115  if (!KEY) throw new CliError(1, "no_api_key", "aucune clé API : définissez MACLUSTR_SMS_API_KEY ou lancez « maclustr-sms login »")116  return KEY.key117}118/** Requête avec réessais (réseau, 5xx, 429). Les en-têtes — dont Idempotency-Key — sont identiques à chaque tentative. */119async function api(method, path, { query, body, headers = {}, auth = true, retries = 3, raw = false } = {}) {120  const qs = new URLSearchParams()121  for (const [k, v] of Object.entries(query ?? {})) if (v !== undefined && v !== null && v !== "") qs.set(k, String(v))122  const url = BASE + path + (qs.size ? `?${qs}` : "")123  const h = { accept: "application/json", "user-agent": `maclustr-sms-cli/${VERSION}`, ...(auth ? { authorization: `Bearer ${needKey()}` } : {}), ...(body !== undefined ? { "content-type": "application/json" } : {}), ...headers }124  for (let attempt = 0; ; attempt++) {125    let err, retryAfter = null126    try {127      const res = await fetch(url, { method, headers: h, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(15_000) })128      const text = await res.text()129      let json = null130      try { json = text ? JSON.parse(text) : null } catch {}131      if (raw) return { status: res.status, json, headers: res.headers }132      if (res.ok) return { status: res.status, json, headers: res.headers }133      const e = json?.error ?? {}134      const ra = Number(res.headers.get("retry-after"))135      retryAfter = res.headers.get("retry-after") && Number.isFinite(ra) ? ra * 1000 : null136      err = new CliError(1, e.code ?? "http_error", e.message ?? `HTTP ${res.status}`, { status: res.status, details: e.details, ...(res.status === 429 && retryAfter !== null ? { retry_after: retryAfter / 1000 } : {}) })137      if (res.status !== 429 && res.status < 500) throw err138    } catch (e) {139      if (e instanceof CliError) { if (e.extra.status !== 429 && e.extra.status < 500) throw e; err = e }140      else err = new CliError(1, "network_error", `${BASE} injoignable : ${e?.cause?.code ?? e?.cause?.message ?? e?.message ?? e}`, { status: 0 })141    }142    if (attempt >= retries) throw err143    await sleep(Math.min(retryAfter ?? 500 * 2 ** attempt * (err.extra.status === 429 ? 4 : 1), 30_000))144  }145}146async function pages(path, query, all) {147  const out = []148  let q = { ...query }, last149  do {150    last = (await api("GET", path, { query: q })).json151    out.push(...last.data)152    q = { ...q, cursor: last.next_cursor }153  } while (all && last.has_more && last.next_cursor)154  return { data: out, has_more: all ? false : last.has_more, next_cursor: all ? null : last.next_cursor }155}156157// ── affichage ────────────────────────────────────────────────────────────────158let JSON_OUT = false159const out = s => process.stdout.write(s + "\n")160const when = iso => (iso ? new Date(iso).toLocaleString("fr-CA", { dateStyle: "short", timeStyle: "medium" }) : "—")161const yes = b => (b ? "oui" : "non")162function table(rows, cols) {163  if (!rows.length) return out("(aucun résultat)")164  const cells = rows.map(r => cols.map(([, f]) => String(f(r) ?? "—")))165  const w = cols.map(([t], i) => Math.max(t.length, ...cells.map(c => [...c[i]].length)))166  const line = c => c.map((x, i) => x + " ".repeat(Math.max(w[i] - [...x].length, 0))).join("  ").trimEnd()167  out(line(cols.map(([t]) => t)))168  out(w.map(n => "─".repeat(n)).join("  "))169  for (const c of cells) out(line(c))170}171const clip = (s, n = 60) => { const t = String(s ?? "").replace(/\s+/g, " "); return [...t].length > n ? [...t].slice(0, n - 1).join("") + "…" : t }172const MSG_COLS = [["ID", m => m.id], ["STATUT", m => m.status + (m.error ? ` (${m.error.code})` : "")], ["DE", m => m.from], ["À", m => m.to], ["SIM", m => m.sim_id], ["CRÉÉ", m => when(m.created_at)], ["TEXTE", m => (m.text_purged ? "(contenu effacé)" : clip(m.text, 50))]]173function showMessage(m) {174  out(`${m.id}  ${m.status.toUpperCase()}${m.error ? `  — ${m.error.code}${m.error.detail ? ` : ${m.error.detail}` : ""}` : ""}`)175  out(`  ${m.direction === "inbound" ? "reçu de" : "à"} ${m.direction === "inbound" ? m.from : m.to}   expéditeur ${m.from ?? "—"}   ${m.device_id ?? "—"} / ${m.sim_id ?? "—"}   ${m.segments} segment(s), ${m.encoding}`)176  out(`  créé ${when(m.created_at)}${m.submitted_at ? `   remis au réseau ${when(m.submitted_at)}` : ""}${m.delivered_at ? `   livré ${when(m.delivered_at)}` : ""}`)177  if (m.text != null) out(`  texte : ${m.text}`)178  if (m.status === "submitted") out("  note : « submitted » = remis au réseau cellulaire ; la livraison n'est confirmée que par « delivered ».")179  if (m.status === "unknown") out("  note : issue inconnue (interruption pendant l'envoi). Le SMS est peut-être parti : ne pas renvoyer sans vérifier.")180  if (m.status === "held") out("  note : en attente d'approbation humaine dans le tableau de bord.")181  for (const e of m.events ?? []) if (!e.detail?.ignored) out(`    ${when(e.at)}  ${e.type.padEnd(22)} ${e.from ?? "·"} → ${e.to ?? "·"}  (${e.source})`)182}183184// ── commandes ────────────────────────────────────────────────────────────────185async function readSecret() {186  const stdin = process.stdin187  if (!stdin.isTTY) { let s = ""; for await (const c of stdin) s += c; return s.trim() }188  process.stderr.write("Clé API (saisie masquée) : ")189  stdin.setRawMode(true); stdin.resume(); stdin.setEncoding("utf8")190  return new Promise((resolve, reject) => {191    let s = ""192    const done = f => { stdin.setRawMode(false); stdin.pause(); stdin.off("data", on); process.stderr.write("\n"); f() }193    const on = d => { for (const ch of d) {194      if (ch === "\r" || ch === "\n" || ch === "\u0004") return done(() => resolve(s.trim()))195      if (ch === "\u0003") return done(() => reject(new CliError(2, "aborted", "annulé")))196      if (ch === "\u007f" || ch === "\b") s = s.slice(0, -1); else s += ch197    } }198    stdin.on("data", on)199  })200}201202const commands = {203  async status() {204    const health = (await api("GET", "/v1/health", { auth: false })).json205    const res = { url: BASE, health }206    const tryGet = async p => { try { return (await api("GET", p)).json } catch (e) { if (e.code === "insufficient_scope" || e.code === "no_api_key") return null; throw e } }207    const [devices, queue, usage] = [await tryGet("/v1/devices"), await tryGet("/v1/queue"), await tryGet("/v1/usage")]208    if (devices) res.devices = devices.data.map(d => ({ id: d.id, name: d.name, online: d.online, available: d.available, battery_pct: d.battery_pct, sims_enabled: d.sims.filter(s => s.send_enabled && s.active).length }))209    if (queue) res.queue = { pending: queue.pending, in_flight: queue.in_flight, held: queue.held }210    if (usage) res.quota = usage.quota211    if (JSON_OUT) return res212    out(`${BASE} — service ${health.status}, version ${health.version}`)213    if (devices) for (const d of res.devices) out(`  ${d.id}  ${d.name}  ${d.online ? (d.available ? "en ligne, disponible" : "en ligne, indisponible") : "HORS LIGNE"}  batterie ${d.battery_pct ?? "—"} %  ${d.sims_enabled} SIM activée(s)`)214    if (devices && !devices.data.length) out("  aucun appareil visible avec cette clé")215    if (queue) out(`  file : ${queue.pending} en attente, ${queue.in_flight} en cours, ${queue.held} à approuver`)216    if (usage) out(`  quota : ${usage.quota.used_today}/${usage.quota.daily} aujourd'hui, ${usage.quota.rate_per_minute} requêtes/min`)217  },218  async devices({ pos }) {219    if ((pos[0] ?? "list") !== "list") usage("usage : devices list")220    const { data } = (await api("GET", "/v1/devices")).json221    if (JSON_OUT) return data222    table(data, [["ID", d => d.id], ["NOM", d => d.name], ["MODÈLE", d => `${d.manufacturer} ${d.model}`.trim()], ["ANDROID", d => d.android_version], ["APP", d => d.app_version], ["EN LIGNE", d => yes(d.online)], ["DISPONIBLE", d => yes(d.available)], ["BATTERIE", d => (d.battery_pct == null ? "—" : `${d.battery_pct} %${d.charging ? " ⚡" : ""}`)], ["RÉSEAU", d => d.network], ["VU", d => when(d.last_seen_at)], ["SIM", d => d.sims.length]])223  },224  async sims({ pos, opt }) {225    if ((pos[0] ?? "list") !== "list") usage("usage : sims list [--device ID]")226    const { data } = (await api("GET", "/v1/devices")).json227    const sims = data.filter(d => !opt.device || d.id === opt.device).flatMap(d => d.sims)228    if (JSON_OUT) return sims229    table(sims, [["ID", s => s.id], ["APPAREIL", s => s.device_id], ["TYPE", s => ({ physical: "SIM", esim: "eSIM" })[s.type] ?? "?"], ["OPÉRATEUR", s => s.carrier_name], ["NUMÉRO", s => s.number], ["ÉTAT", s => s.state], ["SIGNAL", s => (s.signal_level == null ? "—" : `${s.signal_level}/4`)], ["PRÉSENTE", s => yes(s.active)], ["ENVOI", s => (s.send_enabled ? "activé" : "désactivé")], ["LIMITE/J", s => s.daily_limit]])230  },231  async numbers() {232    const { data } = (await api("GET", "/v1/numbers")).json233    if (JSON_OUT) return data234    table(data, [["NUMÉRO", n => n.number], ["SIM", n => n.sim_id], ["APPAREIL", n => n.device_id], ["OPÉRATEUR", n => n.carrier_name], ["SOURCE", n => n.source], ["ENVOI", n => (n.send_enabled ? "activé" : "désactivé")], ["LIBELLÉ", n => n.label]])235  },236  async send({ opt }) {237    if (!opt.to || !opt.text) usage("usage : send --to +14185550123 --text \"…\" [--sim ID] [--device ID] [--from N] [--ttl S] [--wait [S]] [--final]")238    const body = { to: opt.to, text: opt.text, ...(opt.sim ? { sim_id: opt.sim } : {}), ...(opt.device ? { device_id: opt.device } : {}), ...(opt.from ? { from: opt.from } : {}), ...(opt.ttl ? { ttl_seconds: Number(opt.ttl) } : {}) }239    const r = await api("POST", "/v1/messages", { body, headers: { "idempotency-key": opt["idempotency-key"] ?? randomUUID() } })240    let m = { ...r.json, replayed: r.headers.get("idempotent-replayed") === "true" }, timedOut = false241    if (opt.wait !== undefined) {242      const deadline = Date.now() + Number(opt.wait) * 1000243      for (;;) {244        if (FINAL.includes(m.status) || (!opt.final && m.status === "submitted")) break245        if (Date.now() + 500 > deadline) { timedOut = true; break }246        await sleep(500)247        m = { ...(await api("GET", `/v1/messages/${encodeURIComponent(m.id)}`)).json, replayed: m.replayed }248      }249    }250    const exit = timedOut ? 5 : ["failed", "expired", "cancelled"].includes(m.status) ? 3 : m.status === "unknown" ? 4 : 0251    if (JSON_OUT) return { __exit: exit, ...m, ...(timedOut ? { wait_timed_out: true } : {}) }252    if (m.replayed) out("(Idempotency-Key déjà utilisée : message existant renvoyé, aucun second envoi)")253    showMessage(m)254    if (timedOut) out(`  délai d'attente dépassé (${opt.wait} s) : suivre avec « maclustr-sms message ${m.id} »`)255    return { __exit: exit, __silent: true }256  },257  async message({ pos }) {258    if (!pos[0]) usage("usage : message <id>")259    const m = (await api("GET", `/v1/messages/${encodeURIComponent(pos[0])}`)).json260    if (JSON_OUT) return m261    showMessage(m)262  },263  async messages({ opt }) {264    const r = await pages("/v1/messages", { status: opt.status, to: opt.to, sim_id: opt.sim, device_id: opt.device, limit: opt.limit ?? 20, cursor: opt.cursor }, opt.all)265    if (JSON_OUT) return r266    table(r.data, MSG_COLS)267    if (r.has_more) out(`… suite : --cursor ${r.next_cursor}  (ou --all)`)268  },269  async cancel({ pos }) {270    if (!pos[0]) usage("usage : cancel <id>")271    const m = (await api("POST", `/v1/messages/${encodeURIComponent(pos[0])}/cancel`, { body: {} })).json272    if (JSON_OUT) return m273    out(`${m.id} annulé`)274  },275  async inbox({ opt }) {276    const r = await pages("/v1/inbox", { from: opt.from, sim_id: opt.sim, limit: opt.limit ?? 20, cursor: opt.cursor }, opt.all)277    if (JSON_OUT) return r278    table(r.data, [["ID", m => m.id], ["REÇU", m => when(m.received_at ?? m.created_at)], ["DE", m => m.from], ["VERS", m => m.to], ["SIM", m => m.sim_id], ["TEXTE", m => (m.text_purged ? "(contenu effacé)" : clip(m.text, 70))]])279    if (r.has_more) out(`… suite : --cursor ${r.next_cursor}  (ou --all)`)280  },281  async conversations({ pos, opt }) {282    if (pos[0]) {283      const r = await pages(`/v1/conversations/${encodeURIComponent(pos[0])}/messages`, { limit: opt.limit ?? 30, cursor: opt.cursor }, opt.all)284      if (JSON_OUT) return r285      for (const m of [...r.data].reverse()) out(`${when(m.received_at ?? m.created_at)}  ${m.direction === "inbound" ? "←" : "→"}  ${m.text_purged ? "(contenu effacé)" : m.text}${m.direction === "outbound" ? `   [${m.status}]` : ""}`)286      return287    }288    const r = await pages("/v1/conversations", { sim_id: opt.sim, limit: opt.limit ?? 20, cursor: opt.cursor }, opt.all)289    if (JSON_OUT) return r290    table(r.data, [["ID", c => c.id], ["CORRESPONDANT", c => c.peer], ["NUMÉRO", c => c.number], ["SIM", c => c.sim_id], ["DERNIER", c => when(c.last_message_at)], ["REÇUS", c => c.inbound_count], ["ENVOYÉS", c => c.outbound_count], ["NON LUS", c => c.unread]])291  },292  async queue() {293    const q = (await api("GET", "/v1/queue")).json294    if (JSON_OUT) return q295    out(`${q.pending} en attente, ${q.in_flight} en cours de transmission, ${q.held} à approuver${q.oldest_pending_at ? ` — plus ancien : ${when(q.oldest_pending_at)}` : ""}`)296    if (q.items.length) table(q.items, [["MESSAGE", i => i.message_id], ["STATUT", i => i.status], ["FILE", i => i.queue_state], ["À", i => i.to], ["APPAREIL", i => i.device_id], ["SIM", i => i.sim_id], ["CRÉÉ", i => when(i.created_at)], ["EXPIRE", i => when(i.expires_at)]])297  },298  async usage({ opt }) {299    const u = (await api("GET", "/v1/usage", { query: { from: opt.from, to: opt.to } })).json300    if (JSON_OUT) return u301    out(`Application ${u.application_id} — du ${u.from} au ${u.to}`)302    out(`Quota : ${u.quota.used_today}/${u.quota.daily} aujourd'hui · ${u.quota.rate_per_minute} requêtes/min`)303    const keys = [...new Set(u.days.flatMap(d => Object.keys(d).filter(k => k !== "day")))]304    table(u.days, [["JOUR", d => d.day], ...keys.map(k => [k.toUpperCase(), d => d[k] ?? 0])])305  },306  async webhooks({ pos, opt }) {307    const sub = pos[0] ?? "list"308    if (sub === "list") {309      const { data } = (await api("GET", "/v1/webhooks")).json310      if (JSON_OUT) return data311      return table(data, [["ID", w => w.id], ["URL", w => w.url], ["ÉVÉNEMENTS", w => w.events.join(",")], ["ACTIF", w => yes(w.enabled)], ["ÉCHECS", w => w.failure_streak], ["CRÉÉ", w => when(w.created_at)]])312    }313    if (sub === "add") {314      if (!opt.url || !opt.events) usage("usage : webhooks add --url https://… --events sms.received,sms.delivered [--description D]")315      const w = (await api("POST", "/v1/webhooks", { body: { url: opt.url, events: opt.events.split(",").map(s => s.trim()).filter(Boolean), ...(opt.description ? { description: opt.description } : {}) } })).json316      if (JSON_OUT) return w317      out(`webhook ${w.id} créé → ${w.url}`)318      out(`secret de signature (affiché une seule fois, à conserver) : ${w.secret}`)319      return320    }321    if (sub === "rm") {322      if (!pos[1]) usage("usage : webhooks rm <id>")323      const r = (await api("DELETE", `/v1/webhooks/${encodeURIComponent(pos[1])}`)).json324      if (JSON_OUT) return r325      return out(`webhook ${pos[1]} supprimé`)326    }327    usage("usage : webhooks list | add --url U --events e1,e2 | rm <id>")328  },329  async verify({ pos, opt }) {330    const sub = pos[0]331    const show = v => {332      out(`${v.id}  ${v.status.toUpperCase()}  ${v.to}   essais restants : ${v.attempts_remaining}   expire ${when(v.expires_at)}${v.message_status ? `   SMS : ${v.message_status}` : ""}`)333    }334    if (sub === "start") {335      if (!opt.to) usage("usage : verify start --to +14185550123 [--brand Nom] [--locale fr|en] [--ttl S] [--sim ID] [--from N]")336      // Jamais réessayée : sans clé d'idempotence, un réessai aveugle pourrait envoyer deux codes.337      const v = (await api("POST", "/v1/verifications", { retries: 0, body: { to: opt.to, ...(opt.brand ? { brand: opt.brand } : {}), ...(opt.locale ? { locale: opt.locale } : {}), ...(opt.ttl ? { ttl_seconds: Number(opt.ttl) } : {}), ...(opt.sim ? { sim_id: opt.sim } : {}), ...(opt.from ? { from: opt.from } : {}) } })).json338      if (JSON_OUT) return v339      show(v)340      return out(`  code envoyé par SMS ; contrôler la saisie avec : maclustr-sms verify check ${v.id} --code …`)341    }342    if (sub === "check") {343      if (!pos[1] || !opt.code) usage("usage : verify check <id> --code 123456")344      const v = (await api("POST", `/v1/verifications/${encodeURIComponent(pos[1])}/check`, { retries: 0, body: { code: String(opt.code) } })).json   // jamais réessayée : un essai serait consommé deux fois345      if (JSON_OUT) return { __exit: v.valid ? 0 : 3, ...v }346      out(v.valid ? `code VALIDE — ${v.id} approuvée` : `code REFUSÉ — ${v.id} : ${v.status}, essais restants : ${v.attempts_remaining}`)347      return { __exit: v.valid ? 0 : 3, __silent: true }348    }349    if (sub === "status") {350      if (!pos[1]) usage("usage : verify status <id>")351      const v = (await api("GET", `/v1/verifications/${encodeURIComponent(pos[1])}`)).json352      if (JSON_OUT) return v353      return show(v)354    }355    usage("usage : verify start --to N | verify check <id> --code C | verify status <id>")356  },357  async doctor() {358    const checks = []359    const add = (name, ok, detail, level = ok ? "ok" : "fail") => checks.push({ name, ok, level, detail })360    let reachable = false361    try {362      const t0 = Date.now()363      const h = (await api("GET", "/v1/health", { auth: false, retries: 0 })).json364      reachable = true365      add("service", h.status === "ok", `${BASE} répond en ${Date.now() - t0} ms — état ${h.status}, version ${h.version}`)366      const skew = Math.abs(Date.now() - Date.parse(h.time)) / 1000367      add("horloge", skew < 120, `écart avec le serveur : ${skew.toFixed(1)} s`, skew < 120 ? "ok" : "warn")368    } catch (e) { add("service", false, e.message) }369    const u = new URL(BASE)370    if (u.protocol === "https:") {371      const cert = await new Promise(resolve => {372        const s = tls.connect({ host: u.hostname, port: Number(u.port || 443), servername: u.hostname, timeout: 8000 }, () => { const c = s.getPeerCertificate(); const r = { authorized: s.authorized, error: s.authorizationError, valid_to: c?.valid_to, protocol: s.getProtocol() }; s.end(); resolve(r) })373        s.on("error", e => resolve({ authorized: false, error: e.message })); s.on("timeout", () => { s.destroy(); resolve({ authorized: false, error: "délai dépassé" }) })374      })375      const days = cert.valid_to ? Math.floor((Date.parse(cert.valid_to) - Date.now()) / 86400_000) : null376      add("tls", !!cert.authorized && (days ?? 0) > 0, cert.authorized ? `certificat valide (${cert.protocol}), expire dans ${days} jours` : `certificat refusé : ${cert.error}`, cert.authorized && days < 14 ? "warn" : cert.authorized ? "ok" : "fail")377    } else add("tls", false, "URL en http:// — acceptable seulement pour un serveur de développement local", "warn")378    const key = loadKey()379    add("clé API", !!key, key ? `trouvée (${key.source}), préfixe ${key.key.slice(0, 9)}…` : "absente : MACLUSTR_SMS_API_KEY ou « maclustr-sms login »")380    let scopes = null381    if (key && reachable) {382      KEY = key383      // Scopes effectifs, observés par des requêtes sans effet (corps volontairement invalide pour l'envoi, identifiant inexistant pour l'annulation et la vérification : aucun SMS, aucun code).384      const probes = [["messages:read", "GET", "/v1/messages?limit=1"], ["messages:send", "POST", "/v1/messages", {}], ["messages:cancel", "POST", "/v1/messages/sms_doctor_probe/cancel", {}], ["inbox:read", "GET", "/v1/inbox?limit=1"],385        ["devices:read", "GET", "/v1/devices"], ["numbers:read", "GET", "/v1/numbers"], ["webhooks:manage", "GET", "/v1/webhooks"], ["usage:read", "GET", "/v1/usage"], ["queue:read", "GET", "/v1/queue"], ["verify:manage", "GET", "/v1/verifications/ver_doctor_probe"]]386      scopes = {}387      let valid = true, why = ""388      for (const [scope, method, path, body] of probes) {389        let r390        for (let i = 0; ; i++) { r = await api(method, path, { body, raw: true, retries: 0 }); if (r.status !== 429 || i >= 6) break; await sleep(3200) }   // limite de débit de l'application : on patiente391        const code = r.json?.error?.code392        if (r.status === 401 || code === "application_disabled") { valid = false; why = r.json?.error?.message ?? code; break }393        scopes[scope] = r.status === 429 ? null : code !== "insufficient_scope"394      }395      if (!valid) { add("authentification", false, why); scopes = null }396      else {397        const has = Object.entries(scopes).filter(([, v]) => v).map(([k]) => k), unknown = Object.entries(scopes).filter(([, v]) => v === null).map(([k]) => k)398        add("authentification", true, "clé acceptée par le serveur")399        add("scopes", has.length > 0, (has.length ? has.join(", ") : "aucun scope") + (unknown.length ? ` — non déterminés (limite de débit) : ${unknown.join(", ")}` : ""), has.length ? "ok" : "fail")400      }401    }402    if (scopes?.["devices:read"]) {403      const { data } = (await api("GET", "/v1/devices")).json404      const online = data.filter(d => d.online), avail = data.filter(d => d.available)405      add("appareils", avail.length > 0, data.length ? `${data.length} appareil(s), ${online.length} en ligne, ${avail.length} disponible(s)` + data.filter(d => !d.available).map(d => ` — ${d.id} : ${!d.online ? "hors ligne" : d.maintenance ? "maintenance" : !d.enabled ? "désactivé" : `passerelle ${d.gateway_state ?? "?"}`}`).join("") : "aucun appareil visible avec cette clé")406      for (const d of online) if (d.battery_pct != null && d.battery_pct < 20 && !d.charging) add(`batterie ${d.id}`, false, `${d.battery_pct} % et non branché`, "warn")407      const sims = data.flatMap(d => d.sims), usable = sims.filter(s => s.send_enabled && s.active && s.state === "ready")408      add("sim", usable.length > 0, `${sims.length} SIM, ${usable.length} prête(s) à envoyer` + sims.filter(s => !usable.includes(s)).map(s => ` — ${s.id} : ${!s.active ? "absente" : s.state !== "ready" ? `état ${s.state}` : "envoi non activé"}`).join(""))409      for (const s of usable) if (!s.number) add(`numéro ${s.id}`, false, "numéro inconnu : à saisir dans le tableau de bord", "warn")410    }411    if (scopes?.["queue:read"]) {412      const q = (await api("GET", "/v1/queue")).json413      const age = q.oldest_pending_at ? (Date.now() - Date.parse(q.oldest_pending_at)) / 1000 : 0414      add("file", age < 300, `${q.pending} en attente, ${q.in_flight} en cours, ${q.held} à approuver` + (age >= 300 ? ` — le plus ancien attend depuis ${Math.round(age / 60)} min` : ""), age < 300 ? "ok" : "warn")415    }416    if (scopes?.["usage:read"]) {417      const { quota } = (await api("GET", "/v1/usage")).json418      add("quota", quota.used_today < quota.daily, `${quota.used_today}/${quota.daily} envois aujourd'hui`, quota.used_today < quota.daily ? "ok" : "warn")419    }420    const failed = checks.some(c => c.level === "fail")421    if (JSON_OUT) return { __exit: failed ? 1 : 0, ok: !failed, url: BASE, scopes, checks }422    for (const c of checks) out(`${c.level === "ok" ? "✓" : c.level === "warn" ? "!" : "✗"} ${c.name.padEnd(18)} ${c.detail}`)423    out(failed ? "\nDiagnostic : au moins un contrôle bloquant a échoué." : "\nDiagnostic : rien de bloquant.")424    return { __exit: failed ? 1 : 0, __silent: true }425  },426  async login() {427    if (process.platform !== "darwin") throw new CliError(1, "unsupported", "le trousseau n'est géré que sous macOS : utilisez MACLUSTR_SMS_API_KEY")428    const key = await readSecret()429    if (!/^mlsk_[A-Za-z0-9_-]{20,80}$/.test(key)) throw new CliError(2, "invalid_key", "clé inattendue (format mlsk_…)")430    // Passée à « security » par son entrée standard (mode interactif) : la clé n'apparaît dans aucune liste de processus.431    const r = keychain(["-i"], `add-generic-password -U -s ${SERVICE} -a ${os.userInfo().username} -l "MacLustr SMS API key" -w ${key}\n`)432    if (r.status !== 0 || /error|SecKeychain/i.test(r.stderr + r.stdout)) throw new CliError(1, "keychain_error", (r.stderr || r.stdout).trim() || "échec de l'écriture dans le trousseau")433    if (JSON_OUT) return { stored: true }434    out("clé enregistrée dans le trousseau macOS (service « maclustr-sms »)")435  },436  async logout() {437    const r = keychain(["delete-generic-password", "-s", SERVICE])438    if (JSON_OUT) return { removed: r.status === 0 }439    out(r.status === 0 ? "clé effacée du trousseau" : "aucune clé dans le trousseau")440  },441}442443async function main() {444  const argv = process.argv.slice(2)445  JSON_OUT = argv.includes("--json")446  const { pos, opt } = parseArgs(argv)447  if (opt.version) return out(VERSION)448  const cmd = pos.shift()449  if (!cmd || opt.help || cmd === "help") { out(HELP); return }450  const leaked = argv.find(a => /mlsk_[A-Za-z0-9_-]{20,}/.test(a))451  if (leaked) usage("une clé API ne se passe jamais en argument (elle resterait dans l'historique du shell) : MACLUSTR_SMS_API_KEY ou « maclustr-sms login »")452  if (!commands[cmd]) usage(`commande inconnue : ${cmd} (voir maclustr-sms --help)`)453  const r = await commands[cmd]({ pos, opt })454  const exit = r?.__exit ?? 0455  if (JSON_OUT && r !== undefined && !r?.__silent) { const { __exit, ...rest } = Array.isArray(r) ? { data: r } : r; out(JSON.stringify(Array.isArray(r) ? r : rest, null, 2)) }456  process.exitCode = exit457}458main().catch(e => {459  const exit = e instanceof CliError ? e.exit : 1460  if (JSON_OUT) out(JSON.stringify({ error: { code: e.code ?? "internal", message: e.message, ...(e.extra?.status !== undefined ? { status: e.extra.status } : {}), ...(e.extra?.details ? { details: e.extra.details } : {}), ...(e.extra?.retry_after !== undefined ? { retry_after: e.extra.retry_after } : {}) } }, null, 2))461  else process.stderr.write(`erreur${e.code ? ` (${e.code})` : ""} : ${e.message}${e.extra?.retry_after !== undefined ? ` (réessayer dans ${e.extra.retry_after} s)` : ""}\n`)462  process.exitCode = exit463})464
Files main
Menu

Theme