SPB Git

Repository Public

app.ts 21.3 KB 321 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : KA Maps Engine8 * File             : studio/server/app.ts9 * Module           : studio10 * Repository       : https://git.spboucher.ai/ka-maps-engine11 * Created          : 2026-12-0112 * Last Modified    : 2026-12-0113 *14 * Author           : Simon-Pierre Boucher15 * Position         : Professor of Finance16 * Institution      : Université du Québec en Outaouais (UQO)17 * Organization     : SP Boucher18 * Website          : https://spboucher.ai19 * Git              : https://git.spboucher.ai20 *21 * Preferred Contact: support@spboucher.ai22 * Development      : dev@spboucher.ai23 * Support          : support@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// KA Maps Studio — routes HTTP. Tout /api exige une session, sauf l'état, l'activation et la connexion.43import { randomBytes } from 'node:crypto';44import { readFile, stat, unlink } from 'node:fs/promises';45import type { IncomingMessage, ServerResponse } from 'node:http';46import { tmpdir } from 'node:os';47import { extname, join, normalize } from 'node:path';48import { brandDocument, KNOWN_FLAGS, LAYER_SWITCHES } from '../../server/km-maps/lib/brand.ts';49import { clientIp, etagOf, json, problem, RateLimiter, readJson, type Reply, send, sha256hex } from '../../server/km-maps/lib/http.ts';50import { Gate, kmrRender, kmrValidate } from '../../server/km-maps/lib/kmr.ts';51import { APPS, inRollout, PLATFORMS, themeSalt } from '../../server/km-maps/lib/rollout.ts';52import { compareSemver, SEMVER_RE } from '../../server/km-maps/lib/semver.ts';53import * as apps from './apps.ts';54import * as auth from './auth.ts';55import { type Actor, audit, type Db, HttpError } from './db.ts';56import * as ops from './ops.ts';57import * as themes from './themes.ts';58import { THEME_SCHEMA, validateTheme } from './validate.ts';5960export type StudioConfig = { auth: auth.AuthConfig; ops: ops.OpsConfig; webDir: string; sdkDir: string; tiler: string; publicMaps: string; limits?: { auth: number; api: number } };6162export const PRESETS = [63  { id: 'montreal', label: 'Montréal, centre-ville', center: [-73.5674, 45.5019], zoom: 15 },64  { id: 'plateau', label: 'Plateau-Mont-Royal, rues', center: [-73.5805, 45.5232], zoom: 16.4 },65  { id: 'quebec', label: 'Vieux-Québec', center: [-71.2075, 46.8123], zoom: 15.4 },66  { id: 'laval', label: 'Laval, banlieue', center: [-73.7952, 45.5853], zoom: 15 },67  { id: 'lac-saint-jean', label: 'Lac-Saint-Jean, rural', center: [-72.2354, 48.5522], zoom: 11.5 },68];6970const MIME: Record<string, string> = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.json': 'application/json; charset=utf-8', '.wasm': 'application/wasm', '.woff2': 'font/woff2', '.map': 'application/json' };7172type Ctx = { req: IncomingMessage; url: URL; params: string[]; session: auth.Session | null; actor: Actor; ip: string; body: any };73type Route = { method: string; re: RegExp; open?: boolean; handler: (c: Ctx) => Promise<Reply | unknown> };7475export function createStudio(db: Db, cfg: StudioConfig) {76  const A = cfg.auth;77  const authLimiter = new RateLimiter(cfg.limits?.auth ?? 30, cfg.limits?.auth ?? 30);78  const apiLimiter = new RateLimiter(cfg.limits?.api ?? 900, cfg.limits?.api ?? 300);79  const previewLimiter = new RateLimiter(120, 60);80  const gate = new Gate(3, 8);81  const collector = new ops.Collector(db, cfg.ops);82  const connectSrc = ["'self'", ...new Set([cfg.publicMaps, 'https://tiles.spboucher.ai', 'https://terrain.spboucher.ai', 'https://geo.spboucher.ai'])].join(' ');83  const SECURITY: Record<string, string> = {84    'Content-Security-Policy': `default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src ${connectSrc}; worker-src 'self' blob:; manifest-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,85    'X-Content-Type-Options': 'nosniff',86    'X-Frame-Options': 'DENY',87    'Referrer-Policy': 'no-referrer',88    'Strict-Transport-Security': 'max-age=31536000',89    'Cross-Origin-Opener-Policy': 'same-origin',90    'Cross-Origin-Resource-Policy': 'same-origin',91    'Permissions-Policy': 'geolocation=(), camera=(), microphone=(), payment=(), usb=()',92    'X-Robots-Tag': 'noindex, nofollow',93  };9495  const int = (s: string) => Number(s);96  const routes: Route[] = [97    // ----- authentification98    { method: 'GET', re: /^\/api\/auth\/state$/, open: true, handler: async (c) => (c.session ? { authenticated: true, admin: c.session.admin, csrf: c.session.csrf } : { authenticated: false }) },99    { method: 'POST', re: /^\/api\/auth\/invite$/, open: true, handler: (c) => auth.inviteInfo(db, c.body?.token) },100    { method: 'POST', re: /^\/api\/auth\/register\/options$/, open: true, handler: (c) => auth.registerOptions(db, A, c.body?.token) },101    { method: 'POST', re: /^\/api\/auth\/register\/verify$/, open: true, handler: async (c) => sessionReply(await auth.registerVerify(db, A, c.body, c.req, c.ip)) },102    { method: 'POST', re: /^\/api\/auth\/login\/options$/, open: true, handler: () => auth.loginOptions(db, A) },103    { method: 'POST', re: /^\/api\/auth\/login\/verify$/, open: true, handler: async (c) => sessionReply(await auth.loginVerify(db, A, c.body, c.req, c.ip)) },104    {105      method: 'POST', re: /^\/api\/auth\/logout$/, handler: async (c) => {106        await auth.closeSession(db, c.session!);107        await audit(db.pool, db.schema, c.actor, 'auth.logout', c.session!.admin.email);108        return json({ ok: true }, { headers: { 'Set-Cookie': auth.sessionCookie(A, '', 0) } });109      },110    },111    {112      method: 'GET', re: /^\/api\/admins$/, handler: async () => ({113        admins: (await db.pool.query(114          `SELECT a.id, a.name, a.email, a.created_at, a.disabled_at,115                  (SELECT count(*)::int FROM ${db.schema}.credential c WHERE c.admin_id = a.id) AS credentials,116                  (SELECT max(last_used_at) FROM ${db.schema}.credential c WHERE c.admin_id = a.id) AS last_login,117                  (SELECT count(*)::int FROM ${db.schema}.invite i WHERE i.admin_id = a.id AND i.used_at IS NULL AND i.expires_at > now()) AS pending_invites118           FROM ${db.schema}.admin a ORDER BY a.created_at`)).rows,119      }),120    },121    {122      method: 'GET', re: /^\/api\/audit$/, handler: async (c) => {123        const limit = Math.min(500, Math.max(1, Number(c.url.searchParams.get('limit') ?? 100) || 100));124        const before = Number(c.url.searchParams.get('before') ?? 0) || null;125        return { entries: (await db.pool.query(`SELECT id, at, admin_name, action, target, detail, ip FROM ${db.schema}.audit WHERE ($2::bigint IS NULL OR id < $2) ORDER BY id DESC LIMIT $1`, [limit, before])).rows };126      },127    },128    // ----- référentiel de l'interface129    {130      method: 'GET', re: /^\/api\/meta$/, handler: async () => ({131        apps: APPS, platforms: PLATFORMS, presets: PRESETS, layerSwitches: LAYER_SWITCHES, knownFlags: KNOWN_FLAGS, publicMaps: cfg.publicMaps,132        salts: Object.fromEntries((await db.pool.query(`SELECT id FROM ${db.schema}.theme`)).rows.map((r) => [r.id, themeSalt(r.id)])),133        sdk: await sdkVersions(),134      }),135    },136    { method: 'GET', re: /^\/api\/schema\/kastyle-1\.json$/, handler: async () => THEME_SCHEMA },137    // ----- thèmes138    { method: 'GET', re: /^\/api\/themes$/, handler: async () => ({ themes: await themes.listThemes(db) }) },139    { method: 'POST', re: /^\/api\/themes$/, handler: (c) => themes.createTheme(db, c.actor, c.body) },140    { method: 'GET', re: /^\/api\/themes\/([a-z][a-z0-9-]{1,30})$/, handler: (c) => themes.getTheme(db, c.params[0]) },141    { method: 'POST', re: /^\/api\/themes\/([a-z][a-z0-9-]{1,30})\/drafts$/, handler: (c) => themes.saveDraft(db, c.actor, c.params[0], c.body) },142    { method: 'GET', re: /^\/api\/themes\/([a-z][a-z0-9-]{1,30})\/drafts\/(\d{1,12})$/, handler: async (c) => ({ doc: await themes.getDraftDoc(db, c.params[0], int(c.params[1])) }) },143    { method: 'GET', re: /^\/api\/themes\/([a-z][a-z0-9-]{1,30})\/versions\/(\d{1,6})$/, handler: async (c) => ({ doc: await themes.getVersionDoc(db, c.params[0], int(c.params[1])) }) },144    { method: 'GET', re: /^\/api\/themes\/([a-z][a-z0-9-]{1,30})\/diff$/, handler: (c) => themes.diff(db, c.params[0], c.url.searchParams.get('from') ?? '', c.url.searchParams.get('to') ?? '') },145    { method: 'POST', re: /^\/api\/themes\/([a-z][a-z0-9-]{1,30})\/publish$/, handler: (c) => themes.publish(db, c.actor, c.params[0], c.body) },146    { method: 'POST', re: /^\/api\/themes\/([a-z][a-z0-9-]{1,30})\/rollout$/, handler: (c) => themes.rollout(db, c.actor, c.params[0], c.body) },147    { method: 'POST', re: /^\/api\/themes\/([a-z][a-z0-9-]{1,30})\/rollback$/, handler: (c) => themes.rollback(db, c.actor, c.params[0], c.body) },148    { method: 'POST', re: /^\/api\/themes\/([a-z][a-z0-9-]{1,30})\/archive$/, handler: (c) => themes.archiveTheme(db, c.actor, c.params[0], c.body?.archived !== false) },149    { method: 'POST', re: /^\/api\/validate$/, handler: async (c) => validateTheme(c.body?.doc, c.body?.app && c.body?.brand ? brandDocument(c.body.app, { brand: c.body.brand } as any) : undefined) },150    {151      // Aide à la lecture d'une diffusion : quelles tranches (0–99) reçoivent la candidate à ce pourcentage.152      method: 'GET', re: /^\/api\/themes\/([a-z][a-z0-9-]{1,30})\/buckets$/, handler: async (c) => {153        const percent = Number(c.url.searchParams.get('percent') ?? 0);154        const served = Array.from({ length: 100 }, (_, b) => b).filter((b) => inRollout(c.params[0], b, percent));155        return { theme: c.params[0], percent, salt: themeSalt(c.params[0]), served };156      },157    },158    // ----- applications159    { method: 'GET', re: /^\/api\/apps$/, handler: async () => ({ apps: await apps.listApps(db) }) },160    { method: 'GET', re: /^\/api\/apps\/([a-z]{3,12})\/revisions\/(\d{1,12})$/, handler: (c) => apps.getAppRevision(db, c.params[0], int(c.params[1])) },161    { method: 'PUT', re: /^\/api\/apps\/([a-z]{3,12})$/, handler: (c) => apps.saveApp(db, c.actor, c.params[0], c.body) },162    { method: 'POST', re: /^\/api\/apps\/([a-z]{3,12})\/check$/, handler: async (c) => ({ errors: await apps.checkAppConfig(db, c.params[0], c.body?.config) }) },163    // ----- icônes164    { method: 'GET', re: /^\/api\/icons$/, handler: async () => ({ icons: (await db.pool.query(`SELECT name, svg, sha256, bytes, updated_at, updated_by FROM ${db.schema}.icon ORDER BY name`)).rows }) },165    {166      method: 'PUT', re: /^\/api\/icons\/([a-z][a-z0-9-]{0,40})$/, handler: async (c) => {167        const svg = apps.checkSvg(c.body?.svg);168        const r = await db.pool.query(169          `INSERT INTO ${db.schema}.icon (name, svg, sha256, bytes, updated_by) VALUES ($1, $2, $3, $4, $5)170           ON CONFLICT (name) DO UPDATE SET svg = EXCLUDED.svg, sha256 = EXCLUDED.sha256, bytes = EXCLUDED.bytes, updated_at = now(), updated_by = EXCLUDED.updated_by RETURNING (xmax = 0) AS created`,171          [c.params[0], svg, sha256hex(svg), Buffer.byteLength(svg), c.actor.name]);172        await db.pool.query(`UPDATE ${db.schema}.state SET value = value + 1 WHERE key = 'revision'`);173        await audit(db.pool, db.schema, c.actor, r.rows[0].created ? 'icon.create' : 'icon.replace', c.params[0], { bytes: Buffer.byteLength(svg), sha256: sha256hex(svg) });174        return { name: c.params[0], created: r.rows[0].created };175      },176    },177    {178      method: 'DELETE', re: /^\/api\/icons\/([a-z][a-z0-9-]{0,40})$/, handler: async (c) => {179        const r = await db.pool.query(`DELETE FROM ${db.schema}.icon WHERE name = $1 RETURNING name`, [c.params[0]]);180        if (!r.rows[0]) throw new HttpError(404, 'icône inconnue');181        await db.pool.query(`UPDATE ${db.schema}.state SET value = value + 1 WHERE key = 'revision'`);182        await audit(db.pool, db.schema, c.actor, 'icon.delete', c.params[0]);183        return { ok: true };184      },185    },186    {187      // Document effectif (thème + marque, tel que le moteur le calcule) pour l'aperçu par le SDK Web.188      method: 'POST', re: /^\/api\/effective$/, handler: async (c) => {189        const app = c.body?.app;190        if (!(APPS as readonly string[]).includes(app)) throw new HttpError(400, 'app inconnue');191        const r = await kmrValidate(c.body?.doc, brandDocument(app, { brand: c.body?.brand ?? (await currentBrand(app)) } as any), true);192        if (!r.ok) throw new HttpError(422, 'document refusé par le moteur', { errors: r.errors.map((e) => ({ source: 'engine', path: e.path, message: e.message })) });193        return { doc: r.effective };194      },195    },196    // ----- aperçu rendu par le serveur (moteur réel, kmr)197    { method: 'POST', re: /^\/api\/preview$/, handler: (c) => preview(c) },198    // ----- exploitation199    { method: 'GET', re: /^\/api\/ops\/health$/, handler: () => ops.healthBoard(db, cfg.ops) },200    { method: 'GET', re: /^\/api\/ops\/metrics$/, handler: (c) => ops.metricSeries(db, c.url.searchParams.get('service') ?? 'km-tiler', Number(c.url.searchParams.get('hours') ?? 6) || 6) },201    { method: 'GET', re: /^\/api\/ops\/usage$/, handler: (c) => ops.usage(db, Number(c.url.searchParams.get('days') ?? 30) || 30) },202    { method: 'GET', re: /^\/api\/ops\/tile-probes$/, handler: () => ops.tileProbes(db) },203    { method: 'POST', re: /^\/api\/ops\/tile-probes$/, handler: (c) => ops.runTileProbe(db, cfg.ops, c.actor) },204    { method: 'GET', re: /^\/api\/ops\/data$/, handler: () => ops.dataStatus(db, cfg.ops) },205    { method: 'GET', re: /^\/api\/ops\/logs\/([A-Za-z0-9._-]{1,120})$/, handler: (c) => ops.logTail(cfg.ops, c.params[0]) },206    { method: 'POST', re: /^\/api\/ops\/pipeline\/run$/, handler: (c) => ops.pipelineRun(db, cfg.ops, c.actor, c.body) },207  ];208209  function sessionReply(s: { admin: auth.Admin; csrf: string; cookie: string }): Reply {210    return json({ authenticated: true, admin: s.admin, csrf: s.csrf }, { headers: { 'Set-Cookie': s.cookie } });211  }212213  async function sdkVersions(): Promise<string[]> {214    const { readdir } = await import('node:fs/promises');215    const list = await readdir(cfg.sdkDir, { withFileTypes: true }).catch(() => []);216    return list.filter((d) => d.isDirectory() && SEMVER_RE.test(d.name)).map((d) => d.name).sort(compareSemver).reverse();217  }218219  async function preview(c: Ctx): Promise<Reply> {220    if (!previewLimiter.take(c.session!.admin.id)) throw new HttpError(429, "trop d'aperçus demandés, patienter");221    const b = c.body ?? {};222    const n = (v: any, lo: number, hi: number, d: number) => (Number.isFinite(v) ? Math.min(hi, Math.max(lo, v)) : d);223    if (!Array.isArray(b.center) || b.center.length !== 2 || !b.center.every(Number.isFinite)) throw new HttpError(400, 'center : [lon, lat]');224    if (b.app !== undefined && b.app !== null && !(APPS as readonly string[]).includes(b.app)) throw new HttpError(400, 'app inconnue');225    const brand = b.app ? brandDocument(b.app, { brand: b.brand ?? (await currentBrand(b.app)) } as any) : undefined;226    const out = join(tmpdir(), `kms-preview-${randomBytes(8).toString('hex')}.png`);227    try {228      const r = await gate.run(() => kmrRender({229        theme: b.doc, brand, center: [n(b.center[0], -180, 180, 0), n(b.center[1], -85, 85, 0)], zoom: n(b.zoom, 0, 20, 14), pitch: n(b.pitch, 0, 72, 0), bearing: n(b.bearing, -360, 360, 0),230        mode: b.mode === '3d' ? '3d' : '2d', width: n(b.width, 64, 1400, 640), height: n(b.height, 64, 1000, 420), scale: b.scale === 2 ? 2 : 1, tiles: cfg.tiler,231        markers: Array.isArray(b.markers) ? b.markers.slice(0, 20) : [], timeout: 20, attribution: false,232      }, out));233      if (!r.ok) throw new HttpError(422, 'document refusé par le moteur', { errors: (r.errors ?? []).map((e: any) => ({ source: 'engine', path: e.path ?? '', message: e.message ?? String(e) })) });234      const buf = await readFile(out);235      return { type: 'image/png', body: buf, headers: { 'Cache-Control': 'no-store', 'X-Render-Ms': String(r.ms ?? ''), 'X-Render-Settled': String(r.settled ?? '') } };236    } catch (e: any) {237      if (e.code === 'BUSY') throw new HttpError(503, 'rendu saturé, réessayer');238      throw e;239    } finally {240      unlink(out).catch(() => {});241    }242  }243244  async function currentBrand(app: string) {245    const r = await db.pool.query(`SELECT config FROM ${db.schema}.app_config_rev WHERE app = $1 ORDER BY id DESC LIMIT 1`, [app]);246    return r.rows[0]?.config?.brand ?? {};247  }248249  async function serveFile(root: string, rel: string, cache: string): Promise<Reply | null> {250    if (!/^[A-Za-z0-9._\-/]{1,200}$/.test(rel) || rel.includes('..')) return null;251    const file = normalize(join(root, rel));252    if (!file.startsWith(root + '/')) return null;253    const st = await stat(file).catch(() => null);254    if (!st?.isFile()) return null;255    const body = await readFile(file);256    return { type: MIME[extname(file)] ?? 'application/octet-stream', body, headers: { 'Cache-Control': cache, ETag: etagOf(body) } };257  }258259  async function dispatch(req: IncomingMessage): Promise<Reply> {260    const url = new URL(req.url ?? '/', 'http://x');261    const p = url.pathname;262    const ip = clientIp(req);263    const method = req.method ?? 'GET';264    if (p === '/healthz') return json({ status: 'ok' }, { headers: { 'Cache-Control': 'no-store' } });265    if (p.startsWith('/api/')) {266      const noStore = { 'Cache-Control': 'no-store' };267      if (!(p.startsWith('/api/auth/') ? authLimiter : apiLimiter).take(ip)) return { ...problem(429, 'trop de requêtes'), headers: { ...noStore, 'Retry-After': '30' } };268      const route = routes.find((r) => r.re.test(p));269      if (!route) return problem(404, 'introuvable');270      const allowed = routes.filter((r) => r.re.test(p));271      const match = allowed.find((r) => r.method === method);272      if (!match) return { ...problem(405, 'méthode non admise'), headers: { ...noStore, Allow: allowed.map((r) => r.method).join(', ') } };273      const mutating = method !== 'GET';274      if (mutating && !auth.originOk(A, req)) return problem(403, 'origine refusée');275      const session = await auth.currentSession(db, A, req);276      if (!match.open) {277        if (!session) return problem(401, 'session requise');278        if (mutating && !auth.csrfOk(session, req)) return problem(403, 'jeton CSRF manquant ou invalide');279      }280      if (mutating && !/^application\/json\b/.test(String(req.headers['content-type'] ?? ''))) return problem(415, 'application/json attendu');281      const body = mutating ? await readJson(req, 3_000_000) : undefined;282      const actor: Actor = { id: session?.admin.id ?? null, name: session?.admin.name ?? 'anonyme', ip };283      const out = await match.handler({ req, url, params: match.re.exec(p)!.slice(1), session, actor, ip, body });284      const isReply = out !== null && typeof out === 'object' && typeof (out as any).type === 'string' && 'body' in (out as any);285      const reply: Reply = isReply ? (out as Reply) : json(out);286      reply.headers = { ...noStore, ...(reply.headers ?? {}) };287      return reply;288    }289    if (method !== 'GET' && method !== 'HEAD') return problem(405, 'méthode non admise');290    if (p.startsWith('/sdk/')) {291      // Le SDK Web est servi de la même origine que l'interface (modules, workers, wasm) — session requise.292      if (!(await auth.currentSession(db, A, req))) return problem(401, 'session requise');293      return (await serveFile(cfg.sdkDir, p.slice(5), 'private, max-age=3600')) ?? problem(404, 'introuvable');294    }295    if (p.startsWith('/assets/')) return (await serveFile(cfg.webDir, p.slice(1), 'public, max-age=31536000, immutable')) ?? problem(404, 'introuvable');296    if (p === '/favicon.svg') return (await serveFile(cfg.webDir, 'favicon.svg', 'public, max-age=86400')) ?? problem(404, 'introuvable');297    if (/\.[a-z0-9]{2,5}$/i.test(p)) return problem(404, 'introuvable');298    return (await serveFile(cfg.webDir, 'index.html', 'no-cache')) ?? problem(503, "interface non construite (npm run build)");299  }300301  async function handler(req: IncomingMessage, res: ServerResponse) {302    let reply: Reply;303    try {304      reply = await dispatch(req);305    } catch (e: any) {306      if (e instanceof HttpError) reply = problem(e.status, e.message, e.detail);307      else if (e?.status) reply = problem(e.status, e.message);308      else {309        console.error(`erreur ${req.method} ${String(req.url).split('?')[0]} : ${e?.stack ?? e}`);310        reply = problem(500, 'erreur interne');311      }312    }313    reply.headers = { ...SECURITY, ...(reply.headers ?? {}) };314    send(req, res, reply);315  }316317  const sweeper = setInterval(() => auth.sweep(db).catch(() => {}), 600_000);318  sweeper.unref();319  return { handler, collector, routes, stop: () => { clearInterval(sweeper); collector.stop(); } };320}321
Files main
Menu

Theme