SPB Git

Repository Public

app.ts 13.4 KB 191 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Social Engine & Remote Navigator8 * File             : services/control-api/src/app.ts9 * Module           : services10 * Repository       : https://git.spboucher.ai/maclustr-social11 * Project Website  : https://social.spboucher.ai12 * Created          : 2026-12-0113 * Last Modified    : 2026-12-0114 *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 Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from 'fastify';43import cookie from '@fastify/cookie';44import multipart from '@fastify/multipart';45import rateLimit from '@fastify/rate-limit';46import fstatic from '@fastify/static';47import { randomUUID, timingSafeEqual } from 'node:crypto';48import { existsSync, mkdirSync } from 'node:fs';49import { join } from 'node:path';50import { z, ROLE_RANK, type Role } from '@mls/contracts';51import type { Config } from './config.ts';52import type { Db } from './db.ts';53import { ApiErr, forbidden } from './core/errors.ts';54import { cookieName, csrfOk, h, loadSession, originForHost, type AuthSession } from './auth.ts';55import { audit, type Actor } from './audit.ts';56import { registerAuthRoutes } from './routes/auth.ts';57import { registerEditorialRoutes } from './routes/editorial.ts';58import { registerNavigatorRoutes } from './routes/navigator.ts';59import { registerOpsRoutes } from './routes/ops.ts';60import { registerInternalRoutes } from './routes/internal.ts';6162export type RouteDoc = { method: string; path: string; summary: string; tag: string; auth: AuthKind; role?: Role; body?: z.ZodType; query?: z.ZodType };63export type AuthKind = 'public' | 'user' | 'worker' | 'service';64export type Req = FastifyRequest & { cid: string; origin: string; session?: AuthSession; worker?: { id: string; name: string }; data: any };65export type Ctx = {66  db: Db; cfg: Config; mediaKey: Buffer; serviceToken: string; docs: RouteDoc[];67  notifyGateway: (event: Record<string, unknown>) => void;68  route: (d: RouteDoc, handler: (req: Req, reply: FastifyReply) => Promise<unknown>) => void;69  actor: (req: Req) => Actor & { kind: 'user' };70  brandRole: (req: Req, brandId: string) => Promise<Role | null>;71  requireBrand: (req: Req, brandId: string, min: Role) => Promise<Role>;72  visibleBrandIds: (req: Req) => Promise<string[] | 'all'>;73};74const MUTATING = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);75export const SECURITY_HEADERS: Record<string, string> = {76  'content-security-policy': "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'; object-src 'none'",77  'x-content-type-options': 'nosniff', 'x-frame-options': 'DENY', 'referrer-policy': 'no-referrer', 'cross-origin-opener-policy': 'same-origin', 'cross-origin-resource-policy': 'same-origin',78  'permissions-policy': 'camera=(), microphone=(), geolocation=(), clipboard-read=(), payment=()', 'strict-transport-security': 'max-age=31536000; includeSubDomains',79};80export function safeEqual(a: string, b: string) { const x = Buffer.from(a), y = Buffer.from(b); return x.length === y.length && timingSafeEqual(x, y); }8182export async function buildApp(db: Db, cfg: Config, opts: { notifyGateway?: Ctx['notifyGateway']; logger?: boolean } = {}): Promise<{ app: FastifyInstance; ctx: Ctx }> {83  const app = Fastify({ logger: opts.logger ? { level: 'info', redact: ['req.headers.cookie', 'req.headers.authorization', 'req.headers["x-csrf"]'] } : false, trustProxy: cfg.trustProxy, bodyLimit: 1024 * 1024, genReqId: () => randomUUID(), forceCloseConnections: true });84  await app.register(cookie);85  await app.register(multipart, { limits: { fileSize: 15 * 1024 * 1024, files: 1, fields: 8 } });86  await app.register(rateLimit, { global: true, max: 600, timeWindow: '1 minute', keyGenerator: (r) => r.ip, allowList: (r) => r.url.startsWith('/internal/') || r.url === '/v1/workers/heartbeat' });87  app.addContentTypeParser('application/octet-stream', { parseAs: 'buffer', bodyLimit: 8 * 1024 * 1024 }, (_req, body, done) => done(null, body));88  for (const d of ['media', 'evidence']) mkdirSync(join(cfg.dataDir, d), { recursive: true, mode: 0o700 });89  const serviceToken = cfg.secret('service').toString('hex');90  const isLoopback = (req: FastifyRequest) => ['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(req.socket.remoteAddress ?? '') && !req.headers['x-forwarded-for'] && !req.headers['x-mls-via'];9192  const ctx: Ctx = {93    db, cfg, mediaKey: cfg.secret('media'), serviceToken, docs: [],94    notifyGateway: opts.notifyGateway ?? ((event) => { fetch(`${cfg.gatewayInternalUrl}/internal/notify`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${serviceToken}` }, body: JSON.stringify(event), signal: AbortSignal.timeout(2000) }).catch(() => {}); }),95    actor: (req) => ({ kind: 'user', id: req.session!.user.id }),96    async brandRole(req, brandId) {97      const u = req.session!.user;98      if (ROLE_RANK[u.role] >= ROLE_RANK.admin) return u.role;99      return ((await db.one('SELECT role_id FROM brand_members WHERE brand_id=$1 AND user_id=$2', [brandId, u.id]))?.role_id as Role) ?? null;100    },101    async requireBrand(req, brandId, min) {102      const r = await ctx.brandRole(req, brandId);103      // Same answer whether the brand exists or not: no cross-brand existence oracle.104      if (!r || ROLE_RANK[r] < ROLE_RANK[min]) { await db.tx((tx) => audit(tx, { correlationId: req.cid, actor: ctx.actor(req), action: 'access.brand', targetKind: 'brand', targetId: brandId, result: 'denied', detail: { min } })); throw new ApiErr(404, 'not_found', 'ressource introuvable'); }105      return r;106    },107    async visibleBrandIds(req) {108      const u = req.session!.user;109      if (ROLE_RANK[u.role] >= ROLE_RANK.admin) return 'all';110      return (await db.query('SELECT brand_id FROM brand_members WHERE user_id=$1', [u.id])).rows.map((r) => r.brand_id);111    },112    route(d, handler) {113      ctx.docs.push(d);114      app.route({ method: d.method as any, url: d.path, config: d.auth === 'public' ? { rateLimit: { max: 30, timeWindow: '1 minute' } } : {}, handler: async (request, reply) => {115        const req = request as Req;116        if (d.auth === 'service') { if (!isLoopback(req) || !safeEqual(String(req.headers.authorization ?? ''), `Bearer ${serviceToken}`)) throw new ApiErr(404, 'not_found'); }117        else if (d.auth === 'worker') {118          const t = String(req.headers.authorization ?? '').replace(/^Bearer /, '');119          const w = t.length >= 32 ? await db.one("SELECT id, name FROM workers WHERE token_hash=$1 AND status <> 'disabled'", [h(t)]) : null;120          if (!isLoopback(req) || !w) throw new ApiErr(401, 'worker_unauthorized');121          req.worker = w;122        } else {123          if (d.auth === 'user') {124            if (!req.session) throw new ApiErr(401, 'unauthenticated', 'Connexion requise.');125            if (d.role && ROLE_RANK[req.session.user.role] < ROLE_RANK[d.role]) {126              await db.tx((tx) => audit(tx, { correlationId: req.cid, actor: ctx.actor(req), action: 'access.route', targetKind: 'route', targetId: `${d.method} ${d.path}`, result: 'denied' }));127              throw forbidden('role_insufficient', 'Rôle insuffisant.');128            }129          }130          if (MUTATING.has(d.method)) {131            const o = req.headers.origin;132            if (o !== undefined && o !== req.origin) throw forbidden('origin_mismatch');133            if (req.headers['sec-fetch-site'] && !['same-origin', 'none'].includes(String(req.headers['sec-fetch-site']))) throw forbidden('cross_site');134            if (d.auth === 'user' && !csrfOk(req.session!.csrf, String(req.headers['x-csrf'] ?? ''))) throw forbidden('csrf', 'Jeton CSRF invalide.');135            if (!String(req.headers['content-type'] ?? '').match(/^(application\/json|multipart\/form-data|application\/octet-stream)/) && req.body !== undefined) throw new ApiErr(415, 'unsupported_media_type');136          }137        }138        if (d.body) { const p = d.body.safeParse(req.body ?? {}); if (!p.success) throw new ApiErr(400, 'validation', 'Requête invalide', p.error.issues.map((i) => ({ path: i.path.join('.'), message: i.message }))); req.data = p.data; }139        if (d.query) { const p = d.query.safeParse(req.query ?? {}); if (!p.success) throw new ApiErr(400, 'validation', 'Paramètres invalides', p.error.issues.map((i) => ({ path: i.path.join('.'), message: i.message }))); (req as any).q = p.data; }140        for (const [k, v] of Object.entries((req.params ?? {}) as Record<string, string>)) if (/id$/i.test(k) && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v)) throw new ApiErr(404, 'not_found');141        const out = await handler(req, reply);142        return reply.sent ? undefined : reply.send(out ?? { ok: true });143      } });144    },145  };146147  const peerOk = (a: string | undefined) => !cfg.allowedPeers.length || cfg.allowedPeers.includes((a ?? '').replace(/^::ffff:/, ''));148  app.server.on('connection', (sock) => { if (!peerOk(sock.remoteAddress)) sock.destroy(); }); // the LAN cannot bypass the reverse proxy149  app.addHook('onRequest', async (request, reply) => {150    const req = request as Req;151    req.cid = request.id;152    reply.header('x-correlation-id', req.cid);153    for (const [k, v] of Object.entries(SECURITY_HEADERS)) reply.header(k, v);154    if (request.url.startsWith('/internal/') || request.url === '/v1/workers/heartbeat' || request.url.startsWith('/health/')) return;155    req.origin = originForHost(cfg, request.headers.host);156    const c = request.cookies[cookieName(cfg)];157    if (c) req.session = (await loadSession(db, cfg, c, new URL(req.origin).host)) ?? undefined;158    if (request.url.startsWith('/v1/') || request.url.startsWith('/auth/')) reply.header('cache-control', 'no-store');159  });160  app.setErrorHandler((err: any, request, reply) => {161    const cid = (request as Req).cid;162    if (err instanceof ApiErr) return reply.status(err.status).send({ error: { code: err.code, message: err.message, correlationId: cid, details: err.details } });163    if (err?.code === '23505') return reply.status(409).send({ error: { code: 'conflict', message: 'Conflit avec une ressource existante.', correlationId: cid } });164    if (err?.code === '23503' || err?.code === '23514' || err?.code === '22P02') return reply.status(400).send({ error: { code: 'invalid_reference', message: 'Référence ou valeur invalide.', correlationId: cid } });165    if (err?.statusCode && err.statusCode < 500) return reply.status(err.statusCode).send({ error: { code: err.code ?? 'bad_request', message: err.statusCode === 429 ? 'Trop de requêtes.' : 'Requête refusée.', correlationId: cid } });166    request.log.error({ err }, 'unhandled');167    if (!opts.logger && process.env.MLS_TEST_DEBUG) console.error(err);168    return reply.status(500).send({ error: { code: 'internal', message: 'Erreur interne.', correlationId: cid } }); // never leak internals169  });170171  ctx.route({ method: 'GET', path: '/health/live', summary: 'Processus vivant', tag: 'health', auth: 'public' }, async () => ({ ok: true }));172  ctx.route({ method: 'GET', path: '/health/ready', summary: 'Base joignable et schéma à jour', tag: 'health', auth: 'public' }, async () => {173    const r = await db.one("SELECT (SELECT count(*) FROM schema_migrations)::int AS migrations, (SELECT emergency_stop FROM system_state) AS stop, (SELECT version FROM policy_versions WHERE active) AS policy");174    return { ok: true, migrations: r!.migrations, emergencyStop: r!.stop, policyVersion: r!.policy };175  });176  registerAuthRoutes(ctx);177  registerEditorialRoutes(ctx);178  registerNavigatorRoutes(ctx);179  registerOpsRoutes(ctx);180  registerInternalRoutes(ctx);181182  if (cfg.webDir && existsSync(cfg.webDir)) {183    await app.register(fstatic, { root: cfg.webDir, wildcard: false, index: false, setHeaders: (res: any, path: string) => { (res.setHeader ?? res.header).call(res, 'cache-control', path.includes('/assets/') ? 'public, max-age=31536000, immutable' : 'no-cache'); } });184    app.get('/*', async (request, reply) => {185      if (/^\/(v1|auth|internal|media|health)\//.test(request.url)) return reply.status(404).send({ error: { code: 'not_found', message: 'introuvable' } });186      return reply.header('cache-control', 'no-cache').sendFile('index.html');187    });188  } else app.setNotFoundHandler((_r, reply) => reply.status(404).send({ error: { code: 'not_found', message: 'introuvable' } }));189  return { app, ctx };190}191
Files main
Menu

Theme