Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr SMS Gateway8 * File : backend/src/index.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 */4142import cookie from "@fastify/cookie"43import fastifyStatic from "@fastify/static"44import Fastify from "fastify"45import { existsSync } from "node:fs"46import { resolve } from "node:path"47import { adminRoutes } from "./api/admin.ts"48import { v1Routes } from "./api/v1.ts"49import { authRoutes } from "./auth/admin.ts"50import { config, initConfig } from "./config.ts"51import { connect, migrate, sql } from "./db.ts"52import { applyRetention, sweep } from "./messages/service.ts"53import { startDispatcher } from "./queue/dispatcher.ts"54import { ApiError } from "./util.ts"55import { sweepVerifications } from "./verify/service.ts"56import { startWebhookWorker } from "./webhooks/service.ts"57import { startHub } from "./websocket/hub.ts"5859export async function start() {60 initConfig()61 connect()62 const applied = await migrate()6364 const app = Fastify({65 trustProxy: config.trustProxy, bodyLimit: 64 * 1024, forceCloseConnections: true,66 // Journaux structurés (JSON). Ni corps de requête, ni en-têtes d'autorisation, ni contenu de SMS n'y figurent.67 logger: { level: config.logLevel, redact: ["req.headers.authorization", "req.headers.cookie"],68 serializers: { req: (r: any) => ({ method: r.method, url: String(r.url).replace(/^\/dl\/.+/, "/dl/[jeton]"), ip: r.ip }) } },69 })70 if (applied.length) app.log.info({ applied }, "migrations appliquées")71 await app.register(cookie)7273 app.addHook("onSend", async (req, reply) => {74 reply.header("x-content-type-options", "nosniff").header("referrer-policy", "no-referrer").header("x-frame-options", "DENY")75 if (config.secure) reply.header("strict-transport-security", "max-age=31536000; includeSubDomains")76 if (req.url.startsWith("/api/") || req.url.startsWith("/v1/")) reply.header("cache-control", "no-store")77 else reply.header("content-security-policy", "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'")78 })79 app.setErrorHandler((e: any, req, reply) => {80 if (e instanceof ApiError && e.retryAfter) reply.header("retry-after", String(e.retryAfter))81 if (e instanceof ApiError) return reply.code(e.status).send({ error: { code: e.code, message: e.message, ...(e.details ? { details: e.details } : {}) } })82 if (e?.statusCode && e.statusCode < 500) return reply.code(e.statusCode).send({ error: { code: e.code === "FST_ERR_CTP_BODY_TOO_LARGE" ? "payload_too_large" : "invalid_request", message: "requête invalide" } })83 req.log.error({ err: { message: e?.message, code: e?.code, stack: e?.stack } }, "erreur interne")84 return reply.code(500).send({ error: { code: "internal_error", message: "erreur interne" } })85 })8687 app.get("/api/health/ready", async (_req, reply) => {88 try { await sql`select 1`; return { status: "ok" } } catch { return reply.code(503).send({ status: "database_unavailable" }) }89 })90 // Association du domaine avec l'application iOS : permet à l'app d'utiliser les clés d'accès de sms.spboucher.ai.91 app.get("/.well-known/apple-app-site-association", async (_req, reply) =>92 reply.header("content-type", "application/json").header("cache-control", "public, max-age=3600").send({ webcredentials: { apps: config.appleAppIds } }))93 authRoutes(app)94 v1Routes(app)95 adminRoutes(app)9697 const webDir = resolve(config.webDir)98 if (existsSync(webDir)) {99 await app.register(fastifyStatic, { root: webDir, index: false, wildcard: false, maxAge: "1h", immutable: false })100 app.setNotFoundHandler((req, reply) => {101 if (req.method !== "GET" || /^\/(api|v1|ws|dl)\//.test(req.url)) return reply.code(404).send({ error: { code: "not_found", message: "ressource introuvable" } })102 return reply.header("cache-control", "no-store").sendFile("index.html") // application monopage : /apps, /android, /enroll, …103 })104 } else app.setNotFoundHandler((_req, reply) => reply.code(404).send({ error: { code: "not_found", message: "ressource introuvable" } }))105106 const hub = await startHub(app.log as any)107 app.server.on("upgrade", (req, socket, head) => {108 if ((req.url ?? "").split("?")[0] !== "/ws/device") { socket.destroy(); return }109 const remote = req.socket.remoteAddress?.replace(/^::ffff:/, "") ?? null110 const fwd = String(req.headers["x-forwarded-for"] ?? "").split(",")[0].trim()111 const ip = remote && config.trustProxy.includes(remote) && fwd ? fwd : remote112 hub.wss.handleUpgrade(req, socket, head, ws => hub.wss.emit("connection", ws, req, ip))113 })114 const stopDispatcher = startDispatcher(app.log as any)115 const stopWebhooks = startWebhookWorker()116 const sweeper = setInterval(() => void sweep().then(sweepVerifications).catch(e => app.log.error(e)), 30_000)117 const retention = setInterval(() => void applyRetention().then(r => app.log.info(r, "rétention appliquée")).catch(e => app.log.error(e)), 6 * 3600_000)118 void sweep().catch(() => {})119120 await app.listen({ port: config.port, host: config.host })121 const stop = async () => {122 clearInterval(sweeper); clearInterval(retention); stopDispatcher(); stopWebhooks(); hub.stop()123 await app.close(); await sql.end({ timeout: 5 })124 }125 return { app, stop }126}127128if (process.argv[1] && /(server\.mjs|index\.ts)$/.test(process.argv[1])) {129 start().then(({ stop }) => {130 for (const s of ["SIGINT", "SIGTERM"] as const) process.once(s, () => {131 setTimeout(() => process.exit(0), 5000).unref() // garde-fou : un flux resté ouvert ne retient jamais l'arrêt132 void stop().then(() => process.exit(0), () => process.exit(1))133 })134 }).catch(e => { console.error(JSON.stringify({ level: "fatal", msg: String(e?.message ?? e) })); process.exit(1) })135}136