Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr SMS Gateway8 * File : backend/src/api/admin.ts9 * Module : api10 * 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 type { FastifyInstance } from "fastify"43import { z } from "zod"44import { usage } from "../analytics/usage.ts"45import { requireAdmin } from "../auth/admin.ts"46import { createApiKey, publicKey, SCOPES } from "../auth/apikeys.ts"47import { bus, changed, poke } from "../bus.ts"48import { audit, getSetting, setSetting, sql } from "../db.ts"49import { createPairingCode, publicDevice, publicSim, syncNumbers } from "../devices/registry.ts"50import { listConversations, listMessages, messageEvents } from "../messages/query.ts"51import { approveMessage, cancelMessage, createOutbound, publicMessage } from "../messages/service.ts"52import { queueSnapshot } from "../queue/dispatcher.ts"53import { normalizeRecipient } from "../security/phone.ts"54import { ApiError, clampLimit, conflict, iso, newId, notFound, unprocessable } from "../util.ts"55import { createWebhook, enqueueEvent, publicWebhook, redeliver, WEBHOOK_EVENTS } from "../webhooks/service.ts"56import { pokeWebhooks } from "../bus.ts"57import { disconnectDevice, pushConfig, sendToDevice } from "../websocket/hub.ts"58import { downloadToken, parse, releaseInfo, sendApk, SendBody, VERSION } from "./v1.ts"5960const P = (req: any) => req.params as Record<string, string>61const publicApp = (a: any) => ({ id: a.id, name: a.name, description: a.description, kind: a.kind, enabled: a.enabled, daily_quota: a.daily_quota, rate_per_minute: a.rate_per_minute,62 approval_required: a.approval_required, require_consent: a.require_consent, allowed_sim_ids: a.allowed_sim_ids, created_at: iso(a.created_at) })6364export function adminRoutes(app: FastifyInstance) {65 const A = "/api/admin"66 const log = (req: any, action: string, targetType?: string, targetId?: string | null, detail?: Record<string, unknown>) =>67 audit({ actorType: "admin", actorId: req.admin!.userId, action, targetType, targetId, detail, ip: req.ip })6869 // ── Vue d'ensemble ──────────────────────────────────────────────────────────70 app.get(`${A}/overview`, async req => {71 await requireAdmin(req)72 let dbOk = true73 const t0 = Date.now()74 try { await sql`select 1` } catch { dbOk = false }75 const dbMs = Date.now() - t076 const [d] = await sql`select count(*) filter (where online and revoked_at is null)::int as online, count(*) filter (where not online and revoked_at is null)::int as offline from devices`77 const [s] = await sql`select count(*) filter (where s.active)::int as active, count(*) filter (where s.active and s.enabled)::int as enabled from sim_profiles s join devices d on d.id = s.device_id where d.revoked_at is null`78 const [m] = await sql`79 select count(*) filter (where direction = 'outbound' and created_at >= date_trunc('day', now()))::int as sent_today,80 count(*) filter (where direction = 'inbound' and created_at >= date_trunc('day', now()))::int as received_today,81 count(*) filter (where direction = 'outbound' and status in ('SUBMITTED','DELIVERED'))::int as ok_24h,82 count(*) filter (where direction = 'outbound' and status = 'DELIVERED')::int as delivered_24h,83 count(*) filter (where direction = 'outbound' and status in ('FAILED','EXPIRED'))::int as failed_24h,84 count(*) filter (where direction = 'outbound' and status = 'UNKNOWN')::int as unknown_24h,85 percentile_cont(0.5) within group (order by extract(epoch from submitted_at - created_at)) filter (where submitted_at is not null) as median_s86 from messages where created_at > now() - interval '24 hours'`87 const q = await queueSnapshot()88 const done = m.ok_24h + m.failed_24h + m.unknown_24h89 return {90 version: VERSION, backend: { status: dbOk ? "ok" : "degraded", uptime_s: Math.round(process.uptime()), memory_mb: Math.round(process.memoryUsage().rss / 1048576) },91 database: { ok: dbOk, latency_ms: dbMs },92 devices: d, sims: s, kill_switch: await getSetting("kill_switch", false), send_mode: await getSetting("send_mode", "allowlist"),93 messages: { sent_today: m.sent_today, received_today: m.received_today, submitted_24h: m.ok_24h, delivered_24h: m.delivered_24h, failed_24h: m.failed_24h, unknown_24h: m.unknown_24h,94 failure_rate_24h: done ? m.failed_24h / done : null, delivery_confirmation_rate_24h: m.ok_24h ? m.delivered_24h / m.ok_24h : null, median_submit_latency_s: m.median_s == null ? null : Number(m.median_s) },95 queue: { pending: q.pending, in_flight: q.in_flight, held: q.held, oldest_pending_at: q.oldest_pending_at },96 }97 })9899 // Flux temps réel (SSE) : uniquement des signaux « quelque chose a changé », jamais de contenu.100 app.get(`${A}/events`, async (req, reply) => {101 await requireAdmin(req)102 reply.hijack()103 reply.raw.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive", "x-accel-buffering": "no" })104 reply.raw.write("retry: 3000\n\n")105 let pending = new Set<string>(), timer: NodeJS.Timeout | null = null106 const on = (topic: string) => { pending.add(topic); timer ??= setTimeout(() => { reply.raw.write(`data: ${JSON.stringify([...pending])}\n\n`); pending = new Set(); timer = null }, 250) }107 const ping = setInterval(() => reply.raw.write(": ping\n\n"), 25_000)108 bus.on("changed", on)109 req.raw.on("close", () => { bus.off("changed", on); clearInterval(ping); if (timer) clearTimeout(timer) })110 })111112 // ── Messages et console ─────────────────────────────────────────────────────113 app.get(`${A}/messages`, async req => { await requireAdmin(req); return listMessages(req.query as any, null) })114 app.get(`${A}/messages/:id`, async req => {115 await requireAdmin(req)116 const [m] = await sql`select * from messages where id = ${P(req).id}`117 if (!m) throw notFound("message")118 const segments = await sql`select part, status, pdu_status, updated_at from message_segments where message_id = ${m.id} order by part`119 return { ...publicMessage(m), events: await messageEvents(m.id), delivery_reports: segments.map(s => ({ part: s.part, status: s.status, pdu_status: s.pdu_status, at: iso(s.updated_at) })) }120 })121 app.post(`${A}/messages`, async (req, reply) => {122 const a = await requireAdmin(req)123 const body = parse(SendBody, req.body)124 const idem = req.headers["idempotency-key"]125 const { message } = await createOutbound(body, { adminId: a.userId }, typeof idem === "string" ? idem : null)126 await log(req, "message.sent_from_console", "message", message.id, { to: message.to_number, sim_id: message.sim_id })127 reply.code(201)128 return publicMessage(message)129 })130 app.post(`${A}/messages/:id/cancel`, async req => { await requireAdmin(req); const m = await cancelMessage(P(req).id, "admin"); await log(req, "message.cancelled", "message", m.id); return publicMessage(m) })131 app.post(`${A}/messages/:id/approve`, async req => { await requireAdmin(req); await approveMessage(P(req).id); await log(req, "message.approved", "message", P(req).id); return { ok: true } })132133 app.get(`${A}/conversations`, async req => { await requireAdmin(req); return listConversations(req.query as any, null) })134 app.get(`${A}/conversations/:id/messages`, async req => {135 await requireAdmin(req)136 await sql`update conversations set unread = 0 where id = ${P(req).id}`137 return listMessages({ ...(req.query as any), conversation_id: P(req).id }, null)138 })139 app.get(`${A}/queue`, async req => { await requireAdmin(req); return queueSnapshot() })140141 // ── Appareils et association ────────────────────────────────────────────────142 app.get(`${A}/devices`, async req => {143 await requireAdmin(req)144 const sims = await sql`select * from sim_profiles order by id`145 return { data: (await sql`select * from devices order by revoked_at nulls first, id`).map(d => publicDevice(d, sims)) }146 })147 app.get(`${A}/devices/:id`, async req => {148 await requireAdmin(req)149 const [d] = await sql`select * from devices where id = ${P(req).id}`150 if (!d) throw notFound("appareil")151 const sims = await sql`select * from sim_profiles where device_id = ${d.id} order by id`152 const incidents = await sql`select kind, detail, created_at from device_incidents where device_id = ${d.id} order by id desc limit 100`153 const sess = await sql`select id, connected_at, disconnected_at, ip, app_version, close_code, close_reason from device_sessions where device_id = ${d.id} order by connected_at desc limit 30`154 const diags = await sql`select id, requested_at, completed_at, checks from device_diagnostics where device_id = ${d.id} order by requested_at desc limit 5`155 return { ...publicDevice(d, sims), incidents: incidents.map(i => ({ kind: i.kind, detail: i.detail, at: iso(i.created_at) })),156 sessions: sess.map(s => ({ ...s, connected_at: iso(s.connected_at), disconnected_at: iso(s.disconnected_at) })),157 diagnostics: diags.map(g => ({ id: g.id, requested_at: iso(g.requested_at), completed_at: iso(g.completed_at), checks: g.checks })) }158 })159 app.patch(`${A}/devices/:id`, async req => {160 await requireAdmin(req)161 const b = parse(z.object({ name: z.string().min(1).max(80).optional(), enabled: z.boolean().optional(), maintenance: z.boolean().optional(), min_send_interval_ms: z.number().int().min(500).max(600_000).optional() }).strict(), req.body)162 const r = await sql`update devices set name = coalesce(${b.name ?? null}, name), enabled = coalesce(${b.enabled ?? null}, enabled), maintenance = coalesce(${b.maintenance ?? null}, maintenance),163 min_send_interval_ms = coalesce(${b.min_send_interval_ms ?? null}, min_send_interval_ms) where id = ${P(req).id} and revoked_at is null returning id`164 if (!r.length) throw notFound("appareil")165 await log(req, "device.updated", "device", P(req).id, b)166 await pushConfig(P(req).id); poke(P(req).id); changed("devices")167 return { ok: true }168 })169 app.post(`${A}/devices/:id/revoke`, async req => {170 await requireAdmin(req)171 const id = P(req).id172 const r = await sql.begin(async tx => {173 const r = await tx`update devices set revoked_at = now(), enabled = false, online = false where id = ${id} and revoked_at is null returning id`174 await tx`update device_credentials set revoked_at = now() where device_id = ${id} and revoked_at is null`175 await tx`update sim_profiles set enabled = false, active = false where device_id = ${id}`176 await syncNumbers(tx)177 return r178 })179 if (!r.length) throw notFound("appareil")180 await log(req, "device.revoked", "device", id)181 disconnectDevice(id, 4403, "device_revoked"); changed("devices")182 return { ok: true }183 })184 app.post(`${A}/devices/:id/diagnostic`, async req => {185 await requireAdmin(req)186 const id = newId("diag")187 await sql`insert into device_diagnostics(id, device_id) values (${id}, ${P(req).id})`188 if (!sendToDevice(P(req).id, "device.diagnostic.request", { request_id: id })) throw conflict("device_offline", "l'appareil n'est pas connecté")189 return { request_id: id }190 })191 app.post(`${A}/pairing-codes`, async req => {192 const a = await requireAdmin(req)193 const b = parse(z.object({ name: z.string().max(80).optional() }), req.body)194 const c = await createPairingCode(a.userId, b.name ?? "")195 await log(req, "pairing_code.created", "pairing_code", null, { name: b.name ?? "" })196 return c197 })198199 // ── SIM ─────────────────────────────────────────────────────────────────────200 app.get(`${A}/sims`, async req => {201 await requireAdmin(req)202 const rows = await sql`203 select s.*, d.name as device_name, d.online,204 (select coalesce(sum(value), 0)::int from usage_metrics u where u.sim_id = s.id and u.metric = 'outbound_created' and u.day = (now() at time zone 'utc')::date) as sent_today,205 (select coalesce(sum(value), 0)::int from usage_metrics u where u.sim_id = s.id and u.metric = 'outbound_created') as sent_total,206 (select coalesce(sum(value), 0)::int from usage_metrics u where u.sim_id = s.id and u.metric = 'inbound') as received_total207 from sim_profiles s join devices d on d.id = s.device_id where d.revoked_at is null order by s.id`208 return { data: rows.map(s => ({ ...publicSim(s), device_name: s.device_name, device_online: s.online, sent_today: s.sent_today, sent_total: s.sent_total, received_total: s.received_total })), default_sim_id: await getSetting("default_sim_id", null) }209 })210 app.patch(`${A}/sims/:id`, async req => {211 await requireAdmin(req)212 const b = parse(z.object({ send_enabled: z.boolean().optional(), label: z.string().max(80).optional(), manual_number: z.string().max(32).nullable().optional(), daily_limit: z.number().int().min(0).max(100_000).optional() }).strict(), req.body)213 const number = b.manual_number ? normalizeRecipient(b.manual_number) : b.manual_number === null || b.manual_number === "" ? null : undefined214 await sql.begin(async tx => {215 const [s] = await tx`select * from sim_profiles where id = ${P(req).id} for update`216 if (!s) throw notFound("SIM")217 if (number) { const [dup] = await tx`select id from sim_profiles where id <> ${s.id} and coalesce(manual_number, reported_number) = ${number}`; if (dup) throw conflict("number_in_use", `ce numéro est déjà attribué à ${dup.id}`) }218 await tx`update sim_profiles set enabled = coalesce(${b.send_enabled ?? null}, enabled), label = coalesce(${b.label ?? null}, label),219 manual_number = ${number === undefined ? s.manual_number : number}, daily_limit = coalesce(${b.daily_limit ?? null}, daily_limit), updated_at = now() where id = ${s.id}`220 await syncNumbers(tx)221 await audit({ actorType: "admin", actorId: req.admin!.userId, action: "sim.updated", targetType: "sim", targetId: s.id, detail: { ...b, manual_number: number }, ip: req.ip }, tx)222 })223 const [s] = await sql`select device_id from sim_profiles where id = ${P(req).id}`224 await pushConfig(s.device_id); poke(s.device_id); changed("devices")225 return { ok: true }226 })227228 // ── Applications et clés API ────────────────────────────────────────────────229 const AppBody = z.object({ name: z.string().min(2).max(60), description: z.string().max(300).optional(), kind: z.enum(["service", "agent"]).optional(), enabled: z.boolean().optional(),230 daily_quota: z.number().int().min(0).max(100_000).optional(), rate_per_minute: z.number().int().min(0).max(600).optional(), approval_required: z.boolean().optional(),231 require_consent: z.boolean().optional(), allowed_sim_ids: z.array(z.string().max(40)).max(50).nullable().optional() }).strict()232 app.get(`${A}/applications`, async req => {233 await requireAdmin(req)234 const apps = await sql`select a.*, (select coalesce(sum(value), 0)::int from usage_metrics u where u.application_id = a.id and u.metric = 'outbound_created' and u.day = (now() at time zone 'utc')::date) as sent_today from applications a order by a.name`235 const keys = await sql`select * from api_keys order by created_at`236 return { data: apps.map(a => ({ ...publicApp(a), sent_today: a.sent_today, keys: keys.filter(k => k.application_id === a.id).map(publicKey) })), scopes: SCOPES }237 })238 app.post(`${A}/applications`, async (req, reply) => {239 await requireAdmin(req)240 const b = parse(AppBody, req.body)241 const id = newId("app"), agent = b.kind === "agent"242 // Agents IA : permissions minimales par défaut (quota réduit, approbation humaine exigée).243 try {244 await sql`insert into applications(id, name, description, kind, enabled, daily_quota, rate_per_minute, approval_required, require_consent, allowed_sim_ids)245 values (${id}, ${b.name}, ${b.description ?? ""}, ${b.kind ?? "service"}, ${b.enabled ?? true}, ${b.daily_quota ?? (agent ? 20 : 200)}, ${b.rate_per_minute ?? (agent ? 5 : 20)},246 ${b.approval_required ?? agent}, ${b.require_consent ?? false}, ${b.allowed_sim_ids ?? null})`247 } catch (e: any) { if (e?.code === "23505") throw conflict("name_taken", "une application porte déjà ce nom"); throw e }248 await log(req, "application.created", "application", id, { name: b.name, kind: b.kind ?? "service" })249 reply.code(201)250 const [a] = await sql`select * from applications where id = ${id}`251 return publicApp(a)252 })253 app.patch(`${A}/applications/:id`, async req => {254 await requireAdmin(req)255 const b = parse(AppBody.partial(), req.body)256 const [cur] = await sql`select * from applications where id = ${P(req).id}`257 if (!cur) throw notFound("application")258 const n = { ...cur, ...Object.fromEntries(Object.entries(b).filter(([, v]) => v !== undefined)) }259 await sql`update applications set name = ${n.name}, description = ${n.description}, kind = ${n.kind}, enabled = ${n.enabled}, daily_quota = ${n.daily_quota}, rate_per_minute = ${n.rate_per_minute},260 approval_required = ${n.approval_required}, require_consent = ${n.require_consent}, allowed_sim_ids = ${n.allowed_sim_ids} where id = ${cur.id}`261 await log(req, "application.updated", "application", cur.id, b)262 return { ok: true }263 })264 app.delete(`${A}/applications/:id`, async req => {265 await requireAdmin(req)266 const r = await sql`delete from applications where id = ${P(req).id} returning name`267 if (!r.length) throw notFound("application")268 await log(req, "application.deleted", "application", P(req).id, { name: r[0].name })269 return { ok: true }270 })271 app.post(`${A}/applications/:id/keys`, async (req, reply) => {272 await requireAdmin(req)273 const b = parse(z.object({ name: z.string().max(60).optional(), scopes: z.array(z.string()).min(1), expires_in_days: z.number().int().min(1).max(3650).nullable().optional() }).strict(), req.body)274 const [a] = await sql`select id from applications where id = ${P(req).id}`275 if (!a) throw notFound("application")276 const k = await createApiKey(a.id, b.name ?? "", b.scopes, b.expires_in_days ? new Date(Date.now() + b.expires_in_days * 86400_000) : null)277 await log(req, "api_key.created", "api_key", k.id, { application_id: a.id, scopes: b.scopes })278 reply.code(201)279 return k280 })281 app.post(`${A}/keys/:id/revoke`, async req => {282 await requireAdmin(req)283 const r = await sql`update api_keys set revoked_at = now() where id = ${P(req).id} and revoked_at is null returning id`284 if (!r.length) throw notFound("clé")285 await log(req, "api_key.revoked", "api_key", P(req).id)286 return { ok: true }287 })288 // Rotation : nouvelle clé aux mêmes scopes ; l'ancienne reste valide 24 h pour laisser le temps de la remplacer.289 app.post(`${A}/keys/:id/rotate`, async req => {290 await requireAdmin(req)291 const [old] = await sql`select * from api_keys where id = ${P(req).id} and revoked_at is null`292 if (!old) throw notFound("clé")293 const k = await createApiKey(old.application_id, old.name, old.scopes, null, old.id)294 await sql`update api_keys set expires_at = least(coalesce(expires_at, 'infinity'), now() + interval '24 hours') where id = ${old.id}`295 await log(req, "api_key.rotated", "api_key", old.id, { new_key_id: k.id })296 return k297 })298299 // ── Webhooks ────────────────────────────────────────────────────────────────300 app.get(`${A}/webhooks`, async req => {301 await requireAdmin(req)302 const hooks = await sql`select w.*, a.name as application_name from webhooks w left join applications a on a.id = w.application_id order by w.created_at`303 return { data: hooks.map(w => ({ ...publicWebhook(w), application_name: w.application_name })), events: WEBHOOK_EVENTS }304 })305 app.post(`${A}/webhooks`, async (req, reply) => {306 await requireAdmin(req)307 const b = parse(z.object({ url: z.string().max(500), events: z.array(z.string()).min(1), description: z.string().max(200).optional(), application_id: z.string().nullable().optional() }).strict(), req.body)308 const w = await createWebhook({ applicationId: b.application_id ?? null, url: b.url, events: b.events, description: b.description })309 await log(req, "webhook.created", "webhook", w.id, { url: b.url })310 reply.code(201)311 return w312 })313 app.patch(`${A}/webhooks/:id`, async req => {314 await requireAdmin(req)315 const b = parse(z.object({ enabled: z.boolean() }).strict(), req.body)316 const r = await sql`update webhooks set enabled = ${b.enabled}, failure_streak = 0, disabled_reason = null where id = ${P(req).id} returning id`317 if (!r.length) throw notFound("webhook")318 await log(req, "webhook.updated", "webhook", P(req).id, b)319 return { ok: true }320 })321 app.delete(`${A}/webhooks/:id`, async req => {322 await requireAdmin(req)323 const r = await sql`delete from webhooks where id = ${P(req).id} returning id`324 if (!r.length) throw notFound("webhook")325 await log(req, "webhook.deleted", "webhook", P(req).id)326 return { ok: true }327 })328 app.get(`${A}/webhooks/:id/deliveries`, async req => {329 await requireAdmin(req)330 const rows = await sql`select id, event_id, event_type, status, attempts, next_attempt_at, last_status_code, last_error, created_at, delivered_at from webhook_deliveries where webhook_id = ${P(req).id} order by created_at desc limit ${clampLimit((req.query as any).limit, 50, 200)}`331 return { data: rows.map(r => ({ ...r, next_attempt_at: iso(r.next_attempt_at), created_at: iso(r.created_at), delivered_at: iso(r.delivered_at) })) }332 })333 app.post(`${A}/webhook-deliveries/:id/redeliver`, async req => { await requireAdmin(req); if (!(await redeliver(P(req).id))) throw notFound("livraison"); return { ok: true } })334 app.post(`${A}/webhooks/:id/test`, async req => {335 await requireAdmin(req)336 const [w] = await sql`select id, events from webhooks where id = ${P(req).id}`337 if (!w) throw notFound("webhook")338 // Événement d'essai explicite : ne contient aucun message réel.339 const id = newId("whd"), eventId = newId("evt")340 const { seal } = await import("../security/crypto.ts")341 await sql`insert into webhook_deliveries(id, webhook_id, event_id, event_type, payload_enc) values (${id}, ${w.id}, ${eventId}, 'webhook.test',342 ${seal(JSON.stringify({ event: "webhook.test", id: eventId, created_at: new Date().toISOString(), data: { message: "Essai de webhook MacLustr SMS" } }), "webhook-payload:" + id)})`343 pokeWebhooks()344 return { delivery_id: id }345 })346347 // ── Statistiques, journal ───────────────────────────────────────────────────348 app.get(`${A}/analytics`, async req => {349 await requireAdmin(req)350 const q = req.query as any351 const u = await usage({ from: q.from, to: q.to, applicationId: q.application_id || null })352 const byApp = await sql`select coalesce(a.name, '(console)') as name, sum(u.value)::int as value from usage_metrics u left join applications a on a.id = u.application_id353 where u.metric = 'outbound_created' and u.day between ${u.from} and ${u.to} group by 1 order by 2 desc limit 20`354 const bySim = await sql`select sim_id, metric, sum(value)::int as value from usage_metrics where sim_id <> '' and day between ${u.from} and ${u.to} and metric in ('outbound_created','inbound') group by 1, 2 order by 1`355 const errors = await sql`select error_code as code, count(*)::int as n from messages where error_code is not null and created_at >= ${u.from}::date group by 1 order by 2 desc limit 15`356 const [lat] = await sql`select percentile_cont(0.5) within group (order by extract(epoch from submitted_at - created_at)) as p50, percentile_cont(0.95) within group (order by extract(epoch from submitted_at - created_at)) as p95,357 percentile_cont(0.5) within group (order by extract(epoch from delivered_at - submitted_at)) filter (where delivered_at is not null) as delivery_p50358 from messages where submitted_at is not null and created_at >= ${u.from}::date`359 return { ...u, by_application: byApp, by_sim: bySim, errors, latency: { submit_p50_s: lat.p50 == null ? null : Number(lat.p50), submit_p95_s: lat.p95 == null ? null : Number(lat.p95), delivery_p50_s: lat.delivery_p50 == null ? null : Number(lat.delivery_p50) } }360 })361 app.get(`${A}/audit-logs`, async req => {362 await requireAdmin(req)363 const q = req.query as any, limit = clampLimit(q.limit, 100, 500)364 const rows = await sql`select l.*, u.handle from audit_logs l left join users u on l.actor_type = 'admin' and u.id = l.actor_id365 where true ${q.action ? sql`and l.action like ${String(q.action) + "%"}` : sql``} ${q.before ? sql`and l.id < ${Number(q.before)}` : sql``} order by l.id desc limit ${limit}`366 return { data: rows.map(r => ({ id: Number(r.id), actor_type: r.actor_type, actor: r.handle ?? r.actor_id, action: r.action, target_type: r.target_type, target_id: r.target_id, detail: r.detail, ip: r.ip, at: iso(r.created_at) })) }367 })368369 // ── Réglages et conformité ──────────────────────────────────────────────────370 const KEYS = ["kill_switch", "send_mode", "default_sim_id", "default_ttl_seconds", "retention_days_text", "retention_days_records", "opt_out_keywords", "opt_in_keywords"] as const371 app.get(`${A}/settings`, async req => {372 await requireAdmin(req)373 const rows = await sql`select key, value from system_settings`374 return Object.fromEntries(rows.map(r => [r.key, r.value]))375 })376 app.patch(`${A}/settings`, async req => {377 await requireAdmin(req)378 const b = parse(z.object({ kill_switch: z.boolean(), send_mode: z.enum(["allowlist", "open"]), default_sim_id: z.string().max(40).nullable(), default_ttl_seconds: z.number().int().min(60).max(86400),379 retention_days_text: z.number().int().min(1).max(3650), retention_days_records: z.number().int().min(30).max(3650),380 opt_out_keywords: z.array(z.string().min(1).max(20)).max(30), opt_in_keywords: z.array(z.string().min(1).max(20)).max(30) }).partial().strict(), req.body)381 if (b.default_sim_id) { const [s] = await sql`select 1 from sim_profiles where id = ${b.default_sim_id}`; if (!s) throw unprocessable("sim_not_found", "SIM inconnue") }382 for (const k of KEYS) if (b[k] !== undefined) await setSetting(k, k.endsWith("_keywords") ? (b[k] as string[]).map(s => s.trim().toUpperCase()) : b[k])383 await log(req, b.kill_switch === true ? "kill_switch.activated" : b.kill_switch === false ? "kill_switch.released" : "settings.updated", "settings", null, b)384 if (b.kill_switch !== undefined) { await pushConfig(); if (!b.kill_switch) poke() }385 changed("settings")386 return { ok: true }387 })388389 const numberList = (table: "allowed_recipients" | "opt_outs", path: string) => {390 app.get(`${A}/${path}`, async req => { await requireAdmin(req); return { data: (await sql`select * from ${sql(table)} order by created_at desc limit 2000`).map(r => ({ ...r, created_at: iso(r.created_at) })) } })391 app.post(`${A}/${path}`, async req => {392 await requireAdmin(req)393 const b = parse(z.object({ number: z.string().max(32), label: z.string().max(80).optional() }).strict(), req.body)394 const n = normalizeRecipient(b.number)395 if (table === "allowed_recipients") await sql`insert into allowed_recipients(number, label) values (${n}, ${b.label ?? ""}) on conflict (number) do update set label = excluded.label`396 else await sql`insert into opt_outs(number, source) values (${n}, 'manual') on conflict do nothing`397 await log(req, `${table}.added`, table, n)398 return { number: n }399 })400 app.delete(`${A}/${path}/:number`, async req => {401 await requireAdmin(req)402 await sql`delete from ${sql(table)} where number = ${P(req).number}`403 await log(req, `${table}.removed`, table, P(req).number)404 return { ok: true }405 })406 }407 numberList("allowed_recipients", "allowed-recipients")408 numberList("opt_outs", "opt-outs")409410 app.get(`${A}/consents`, async req => { await requireAdmin(req); return { data: (await sql`select c.*, a.name as application_name from consents c left join applications a on a.id = c.application_id order by c.granted_at desc limit 2000`).map(c => ({ id: Number(c.id), number: c.number, application_id: c.application_id, application_name: c.application_name, source: c.source, note: c.note, granted_at: iso(c.granted_at), revoked_at: iso(c.revoked_at) })) } })411 app.post(`${A}/consents`, async req => {412 await requireAdmin(req)413 const b = parse(z.object({ number: z.string().max(32), application_id: z.string().nullable().optional(), source: z.string().max(80).optional(), note: z.string().max(300).optional() }).strict(), req.body)414 const n = normalizeRecipient(b.number)415 await sql`insert into consents(number, application_id, source, note) values (${n}, ${b.application_id ?? null}, ${b.source ?? "dashboard"}, ${b.note ?? ""})416 on conflict (number, coalesce(application_id, '')) do update set revoked_at = null, granted_at = now(), source = excluded.source, note = excluded.note`417 await log(req, "consent.recorded", "consent", n, { application_id: b.application_id ?? null })418 return { number: n }419 })420 app.post(`${A}/consents/:id/revoke`, async req => { await requireAdmin(req); await sql`update consents set revoked_at = now() where id = ${Number(P(req).id)}`; await log(req, "consent.revoked", "consent", P(req).id); return { ok: true } })421422 // ── Application Android ─────────────────────────────────────────────────────423 app.get(`${A}/android`, async req => {424 await requireAdmin(req)425 const r = releaseInfo()426 if (!r) return { available: false }427 const { path, ...rest } = r428 return rest429 })430 app.post(`${A}/android/link`, async req => { const a = await requireAdmin(req); const t = await downloadToken(a.userId, 30); await log(req, "android.download_link_created"); const QR = (await import("qrcode")).default; return { ...t, qr_svg: await QR.toString(t.url, { type: "svg", margin: 1 }) } })431 app.get(`${A}/android/download`, async (req, reply) => { await requireAdmin(req); return sendApk(reply) })432 void enqueueEvent; void ApiError433}434