SPB Git

Repository Public

v1.ts 15.6 KB 262 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr SMS Gateway8 * File             : backend/src/api/v1.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 { createReadStream, existsSync, readFileSync, statSync } from "node:fs"44import { join } from "node:path"45import { z } from "zod"46import { usage } from "../analytics/usage.ts"47import { requireKey } from "../auth/apikeys.ts"48import { config } from "../config.ts"49import { audit, sql } from "../db.ts"50import { latestApp, pairDevice, publicDevice, publicSim, verifySignature } from "../devices/registry.ts"51import { listConversations, listMessages, messageEvents } from "../messages/query.ts"52import { cancelMessage, createOutbound, publicMessage } from "../messages/service.ts"53import { queueSnapshot } from "../queue/dispatcher.ts"54import { enforce } from "../security/ratelimit.ts"55import { ApiError, bad, iso, notFound, randomToken, sha256hex } from "../util.ts"56import { checkVerification, getVerification, startVerification } from "../verify/service.ts"57import { createWebhook, publicWebhook } from "../webhooks/service.ts"58import { openapi } from "./openapi.ts"5960export const VERSION = "1.1.1"61export const parse = <T>(s: z.ZodType<T>, v: unknown): T => {62  const r = s.safeParse(v ?? {})63  if (!r.success) throw bad("invalid_request", "requête invalide", r.error.issues.map(i => ({ path: i.path.join("."), message: i.message })))64  return r.data65}66export const SendBody = z.object({67  to: z.string().min(3).max(32), text: z.string().min(1).max(2000),68  device_id: z.string().max(40).nullish(), sim_id: z.string().max(40).nullish(), from: z.string().max(32).nullish(),69  ttl_seconds: z.number().int().min(60).max(86400).nullish(), delivery_report: z.boolean().nullish(),70}).strict()7172export function releaseInfo() {73  try {74    const j = JSON.parse(readFileSync(join(config.releasesDir, "android-release.json"), "utf8"))75    const file = join(config.releasesDir, String(j.file))76    return { ...j, available: existsSync(file), path: file }77  } catch { return null }78}79export async function downloadToken(createdBy: string, minutes = 30) {80  const token = randomToken(24)81  const [r] = await sql`insert into app_download_tokens(token_hash, created_by, expires_at) values (${sha256hex(token)}, ${createdBy}, now() + make_interval(mins => ${minutes})) returning expires_at`82  return { url: `${config.origin}/dl/${token}`, expires_at: iso(r.expires_at) }83}84export function sendApk(reply: any) {85  const rel = releaseInfo()86  if (!rel?.available) throw new ApiError(404, "apk_unavailable", "aucun APK n'est publié sur ce serveur")87  reply.header("content-type", "application/vnd.android.package-archive").header("content-length", statSync(rel.path).size)88    .header("content-disposition", `attachment; filename="${rel.file}"`).header("cache-control", "private, no-store")89  return reply.send(createReadStream(rel.path))90}9192export function v1Routes(app: FastifyInstance) {93  app.get("/v1/health", async () => {94    let db = true95    try { await sql`select 1` } catch { db = false }96    return { status: db ? "ok" : "degraded", version: VERSION, time: new Date().toISOString() }97  })98  app.get("/v1/openapi.json", async () => openapi)99100  // ── Messages ────────────────────────────────────────────────────────────────101  app.post("/v1/messages", async (req, reply) => {102    const k = await requireKey(req, "messages:send")103    const body = parse(SendBody, req.body)104    const idem = req.headers["idempotency-key"]105    const { message, replayed } = await createOutbound(body, { app: k.app, apiKeyId: k.keyId }, typeof idem === "string" ? idem : null)106    if (replayed) reply.header("idempotent-replayed", "true")107    reply.code(replayed ? 200 : 201)108    return publicMessage(message)109  })110  app.get("/v1/messages", async req => {111    const k = await requireKey(req, "messages:read")112    return listMessages({ ...(req.query as any), direction: "outbound" }, { appId: k.app.id, allowedSimIds: k.app.allowed_sim_ids, inbound: false, outbound: true })113  })114  app.get("/v1/messages/:id", async req => {115    // Envoi de l'application (messages:read) ou SMS reçu sur une SIM qui lui est permise (inbox:read).116    const k = await requireKey(req, ["messages:read", "inbox:read"])117    const [m] = await sql`select * from messages where id = ${(req.params as any).id}`118    const own = m?.direction === "outbound" && m.application_id === k.app.id && k.scopes.includes("messages:read")119    const inbound = m?.direction === "inbound" && k.scopes.includes("inbox:read") && (!k.app.allowed_sim_ids || k.app.allowed_sim_ids.includes(m.sim_id))120    if (!own && !inbound) throw notFound("message")121    return { ...publicMessage(m), events: await messageEvents(m.id) }122  })123  app.post("/v1/messages/:id/cancel", async req => {124    const k = await requireKey(req, "messages:cancel")125    return publicMessage(await cancelMessage((req.params as any).id, "api", k.app.id))126  })127128  // ── Réception ───────────────────────────────────────────────────────────────129  app.get("/v1/inbox", async req => {130    const k = await requireKey(req, "inbox:read")131    return listMessages({ ...(req.query as any), direction: "inbound" }, { appId: k.app.id, allowedSimIds: k.app.allowed_sim_ids, inbound: true, outbound: false })132  })133  app.get("/v1/conversations", async req => {134    const k = await requireKey(req, "inbox:read")135    return listConversations(req.query as any, k.app.allowed_sim_ids)136  })137  app.get("/v1/conversations/:id/messages", async req => {138    const k = await requireKey(req, "inbox:read")139    const id = (req.params as any).id140    const [c] = await sql`select sim_id from conversations where id = ${id}`141    if (!c || (k.app.allowed_sim_ids && !k.app.allowed_sim_ids.includes(c.sim_id))) throw notFound("conversation")142    return listMessages({ ...(req.query as any), conversation_id: id }, { appId: k.app.id, allowedSimIds: k.app.allowed_sim_ids, inbound: true, outbound: true })143  })144145  // ── Appareils, SIM, numéros ─────────────────────────────────────────────────146  const simsFor = async (allowed: string[] | null) => sql`select * from sim_profiles ${allowed ? sql`where id = any(${allowed})` : sql``} order by id`147  app.get("/v1/devices", async req => {148    const k = await requireKey(req, "devices:read")149    const sims = await simsFor(k.app.allowed_sim_ids)150    const devices = await sql`select * from devices where revoked_at is null order by id`151    return { data: devices.filter(d => !k.app.allowed_sim_ids || sims.some(s => s.device_id === d.id)).map(d => { const p = publicDevice(d, sims); const { status, ...rest } = p; return rest }) }152  })153  app.get("/v1/devices/:id", async req => {154    const k = await requireKey(req, "devices:read")155    const sims = await simsFor(k.app.allowed_sim_ids)156    const [d] = await sql`select * from devices where id = ${(req.params as any).id} and revoked_at is null`157    if (!d || (k.app.allowed_sim_ids && !sims.some(s => s.device_id === d.id))) throw notFound("appareil")158    const { status, ...rest } = publicDevice(d, sims)159    return rest160  })161  app.get("/v1/devices/:id/sims", async req => {162    const k = await requireKey(req, "devices:read")163    const [d] = await sql`select id from devices where id = ${(req.params as any).id} and revoked_at is null`164    if (!d) throw notFound("appareil")165    return { data: (await simsFor(k.app.allowed_sim_ids)).filter(s => s.device_id === d.id).map(publicSim) }166  })167  app.get("/v1/numbers", async req => {168    const k = await requireKey(req, "numbers:read")169    const rows = await sql`select n.number, n.sim_id, n.source, n.label, s.device_id, s.enabled, s.active, s.carrier_name from phone_numbers n join sim_profiles s on s.id = n.sim_id170                           ${k.app.allowed_sim_ids ? sql`where n.sim_id = any(${k.app.allowed_sim_ids})` : sql``} order by n.number`171    return { data: rows.map(r => ({ number: r.number, sim_id: r.sim_id, device_id: r.device_id, carrier_name: r.carrier_name, source: r.source, label: r.label, send_enabled: r.enabled, active: r.active })) }172  })173174  // ── Webhooks ────────────────────────────────────────────────────────────────175  app.post("/v1/webhooks", async (req, reply) => {176    const k = await requireKey(req, "webhooks:manage")177    const b = parse(z.object({ url: z.string().max(500), events: z.array(z.string()).min(1).max(20), description: z.string().max(200).optional() }).strict(), req.body)178    const [n] = await sql`select count(*)::int as n from webhooks where application_id = ${k.app.id}`179    if (n.n >= 10) throw new ApiError(422, "too_many_webhooks", "maximum 10 webhooks par application")180    const w = await createWebhook({ applicationId: k.app.id, ...b })181    await audit({ actorType: "api_key", actorId: k.keyId, action: "webhook.created", targetType: "webhook", targetId: w.id, ip: req.ip })182    reply.code(201)183    return w184  })185  app.get("/v1/webhooks", async req => {186    const k = await requireKey(req, "webhooks:manage")187    return { data: (await sql`select * from webhooks where application_id = ${k.app.id} order by created_at`).map(publicWebhook) }188  })189  app.delete("/v1/webhooks/:id", async req => {190    const k = await requireKey(req, "webhooks:manage")191    const r = await sql`delete from webhooks where id = ${(req.params as any).id} and application_id = ${k.app.id} returning id`192    if (!r.length) throw notFound("webhook")193    await audit({ actorType: "api_key", actorId: k.keyId, action: "webhook.deleted", targetType: "webhook", targetId: r[0].id, ip: req.ip })194    return { deleted: true }195  })196197  // ── Vérification de numéro par code (authentification par SMS) ──────────────198  app.post("/v1/verifications", async (req, reply) => {199    const k = await requireKey(req, "verify:manage")200    const b = parse(z.object({ to: z.string().min(3).max(32), locale: z.enum(["fr", "en"]).nullish(), brand: z.string().max(30).nullish(), ttl_seconds: z.number().int().min(120).max(900).nullish(),201      code_length: z.number().int().min(6).max(8).nullish(), sim_id: z.string().max(40).nullish(), from: z.string().max(32).nullish() }).strict(), req.body)202    const idem = req.headers["idempotency-key"]203    const { verification, replayed } = await startVerification(b, k.app, k.keyId, typeof idem === "string" ? idem : null)204    if (replayed) reply.header("idempotent-replayed", "true")205    reply.code(replayed ? 200 : 201)206    return verification207  })208  app.post("/v1/verifications/:id/check", async req => {209    const k = await requireKey(req, "verify:manage")210    const b = parse(z.object({ code: z.string().min(4).max(16) }).strict(), req.body)211    return checkVerification((req.params as any).id, b.code, k.app.id)212  })213  app.get("/v1/verifications/:id", async req => {214    const k = await requireKey(req, "verify:manage")215    return getVerification((req.params as any).id, k.app.id)216  })217218  // ── Consommation, file ──────────────────────────────────────────────────────219  app.get("/v1/usage", async req => {220    const k = await requireKey(req, "usage:read")221    const q = parse(z.object({ from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(), to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional() }), req.query)222    const u = await usage({ applicationId: k.app.id, ...q })223    const today = u.days.find(d => d.day === new Date().toISOString().slice(0, 10)) as any224    return { application_id: k.app.id, quota: { daily: k.app.daily_quota, used_today: today?.outbound_created ?? 0, rate_per_minute: k.app.rate_per_minute }, ...u }225  })226  app.get("/v1/queue", async req => {227    const k = await requireKey(req, "queue:read")228    return queueSnapshot(k.app.id)229  })230231  // ── Points d'entrée de l'appareil (hors clés API) ───────────────────────────232  app.post("/v1/device/pair", async (req, reply) => {233    enforce("pair:" + req.ip, 10, 5)234    const b = parse(z.object({235      code: z.string().min(8).max(40), public_key: z.string().min(80).max(400), name: z.string().max(80).optional(), manufacturer: z.string().max(80).optional(), model: z.string().max(80).optional(),236      android_version: z.string().max(20).optional(), sdk_int: z.number().int().optional(), app_version: z.string().max(20).optional(), app_build: z.number().int().optional(),237    }), req.body)238    reply.code(201)239    return pairDevice(b, req.ip)240  })241  app.post("/v1/device/app-download", async req => {242    enforce("appdl:" + req.ip, 10, 5)243    const b = parse(z.object({ device_id: z.string().max(40), signed_at: z.string().max(40), signature: z.string().max(400) }), req.body)244    const skew = Math.abs(Date.now() - Date.parse(b.signed_at))245    const creds = await sql`select c.public_key from device_credentials c join devices d on d.id = c.device_id where d.id = ${b.device_id} and d.revoked_at is null and c.revoked_at is null`246    if (!Number.isFinite(skew) || skew > 5 * 60_000 || !creds.some(c => verifySignature(c.public_key, `maclustr-sms-device-app-download-v1\n${b.device_id}\n${b.signed_at}`, b.signature)))247      throw new ApiError(401, "unauthenticated", "signature d'appareil invalide")248    const rel = releaseInfo()249    if (!rel?.available) throw new ApiError(404, "apk_unavailable", "aucun APK n'est publié sur ce serveur")250    const t = await downloadToken("device:" + b.device_id, 15)251    return { url: t.url, version: rel.version, build: rel.build, sha256: rel.sha256, expires_at: t.expires_at }252  })253  // Lien de téléchargement temporaire (créé par le tableau de bord ou par un appareil authentifié).254  app.get("/dl/:token", async (req, reply) => {255    enforce("dl:" + req.ip, 20)256    const [t] = await sql`select 1 from app_download_tokens where token_hash = ${sha256hex((req.params as any).token)} and expires_at > now()`257    if (!t) throw new ApiError(404, "link_expired", "lien de téléchargement inconnu ou expiré")258    return sendApk(reply)259  })260  void latestApp261}262
Files main
Menu

Theme