Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr SMS Gateway8 * File : backend/src/admin-cli.ts9 * Module : backend10 * 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// Commandes opérateur, à lancer sur le nœud qui héberge la passerelle (voir docs/DEPLOYMENT.md).43import { createApiKey, SCOPES } from "./auth/apikeys.ts"44import { config, initConfig } from "./config.ts"45import { audit, connect, migrate, setSetting, sql } from "./db.ts"46import { applyRetention } from "./messages/service.ts"47import { newId, randomToken, sha256hex } from "./util.ts"4849const [cmd, ...args] = process.argv.slice(2)50const flag = (name: string, d?: string) => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : d }5152async function main() {53 initConfig(); connect(); await migrate()54 switch (cmd) {55 case "enroll": {56 // Lien à usage unique pour enregistrer une clé d'accès (passkey) d'administrateur. Crée le compte s'il n'existe pas.57 const handle = (flag("handle") ?? "").toLowerCase()58 if (!/^[a-z0-9_.-]{2,32}$/.test(handle)) throw new Error("usage : enroll --handle <identifiant> [--name \"Nom affiché\"] [--ttl minutes]")59 let [u] = await sql`select id from users where handle = ${handle}`60 if (!u) [u] = await sql`insert into users(id, handle, display_name) values (${newId("usr")}, ${handle}, ${flag("name") ?? handle}) returning id`61 const ttl = Math.min(1440, Math.max(1, Number(flag("ttl", "30")))), token = randomToken(32)62 await sql`delete from enrollment_tokens where user_id = ${u.id} and used_at is null`63 await sql`insert into enrollment_tokens(token_hash, user_id, expires_at) values (${sha256hex(token)}, ${u.id}, now() + make_interval(mins => ${ttl}))`64 await audit({ actorType: "cli", action: "enrollment_link.issued", targetType: "user", targetId: u.id, detail: { ttl } })65 console.log(`Lien d'enrôlement pour « ${handle} » (valide ${ttl} min, usage unique) :\n\n ${config.origin}/enroll#${token}\n`)66 break67 }68 case "status": {69 const [s] = await sql`select (select count(*)::int from users) as admins, (select count(*)::int from passkeys) as passkeys, (select count(*)::int from devices where revoked_at is null) as devices,70 (select count(*)::int from devices where online) as online, (select count(*)::int from sim_profiles where active and enabled) as sims_enabled, (select count(*)::int from applications) as applications,71 (select count(*)::int from messages) as messages, (select count(*)::int from message_queue) as queued, (select value from system_settings where key = 'kill_switch') as kill_switch,72 (select value from system_settings where key = 'send_mode') as send_mode`73 console.log(JSON.stringify(s, null, 2))74 break75 }76 case "kill-switch": {77 const on = args[0] === "on"78 if (!["on", "off"].includes(args[0])) throw new Error("usage : kill-switch on|off")79 await setSetting("kill_switch", on)80 await audit({ actorType: "cli", action: on ? "kill_switch.activated" : "kill_switch.released" })81 console.log(`arrêt d'urgence ${on ? "ACTIVÉ" : "levé"} (pris en compte par le serveur en moins de 5 s ; les appareils sont avisés à leur prochaine synchronisation de configuration)`)82 break83 }84 case "create-key": {85 // Dépannage sans tableau de bord : crée l'application au besoin et une clé API.86 const name = flag("app"); if (!name) throw new Error(`usage : create-key --app <nom> [--scopes a,b] (scopes : ${SCOPES.join(", ")})`)87 let [a] = await sql`select id from applications where name = ${name}`88 if (!a) [a] = await sql`insert into applications(id, name) values (${newId("app")}, ${name}) returning id`89 const k = await createApiKey(a.id, flag("name") ?? "cli", (flag("scopes") ?? "messages:send,messages:read").split(","))90 await audit({ actorType: "cli", action: "api_key.created", targetType: "api_key", targetId: k.id, detail: { application: name } })91 console.log(`clé API (affichée une seule fois) :\n\n ${k.key}\n`)92 break93 }94 case "retention": console.log(JSON.stringify(await applyRetention())); break95 case "migrate": console.log("migrations à jour"); break96 default: console.log("usage : admin-cli <enroll --handle x | status | kill-switch on|off | create-key --app nom [--scopes …] | retention | migrate>")97 }98 await sql.end()99}100main().catch(async e => { console.error(String(e?.message ?? e)); try { await sql.end() } catch {} ; process.exit(1) })101