SPB Git

Repository Public

apps.ts 6.0 KB 111 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : KA Maps Engine8 * File             : studio/server/apps.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// Configuration par application : marque, thème par défaut, couches, zooms, drapeaux. Chaque43// enregistrement crée une révision ; la plus récente est servie par le manifeste.44import { type AppConfig, brandDocument, validateAppConfig } from '../../server/km-maps/lib/brand.ts';45import { APPS } from '../../server/km-maps/lib/rollout.ts';46import { type Actor, audit, bumpRevision, type Db, HttpError, tx } from './db.ts';47import { validateBrandShape, validateTheme } from './validate.ts';4849export async function listApps(db: Db) {50  const s = db.schema;51  const cur = await db.pool.query(`SELECT DISTINCT ON (app) app, id AS rev, config, note, author_name, created_at FROM ${s}.app_config_rev ORDER BY app, id DESC`);52  const revs = await db.pool.query(`SELECT id AS rev, app, note, author_name, created_at FROM ${s}.app_config_rev ORDER BY id DESC LIMIT 200`);53  return APPS.map((app) => ({ app, current: cur.rows.find((r) => r.app === app) ?? null, revisions: revs.rows.filter((r) => r.app === app) }));54}5556export async function getAppRevision(db: Db, app: string, rev: number) {57  const r = await db.pool.query(`SELECT id AS rev, app, config, note, author_name, created_at FROM ${db.schema}.app_config_rev WHERE app = $1 AND id = $2`, [app, rev]);58  if (!r.rows[0]) throw new HttpError(404, 'révision inconnue');59  return r.rows[0];60}6162/** Vérifie la configuration, puis la marque contre chaque version de thème actuellement servie à l'application. */63export async function checkAppConfig(db: Db, app: string, config: AppConfig) {64  const s = db.schema;65  const known = (await db.pool.query(`SELECT id FROM ${s}.theme WHERE archived_at IS NULL`)).rows.map((r) => r.id);66  const errors: { path: string; message: string }[] = validateAppConfig(config, known);67  if (errors.length) return errors;68  const brand = brandDocument(app, config);69  errors.push(...validateBrandShape(brand).map((e) => ({ path: `brand.${e.path}`, message: e.message })));70  if (errors.length) return errors;71  const served = await db.pool.query(72    `SELECT DISTINCT v.theme_id, v.version, v.doc_text FROM ${s}.channel c JOIN ${s}.theme_version v ON v.theme_id = c.theme_id AND v.version IN (c.stable_version, c.candidate_version)73     WHERE c.app = $1 AND c.theme_id = ANY($2)`,74    [app, config.themes],75  );76  for (const row of served.rows) {77    const r = await validateTheme(JSON.parse(row.doc_text), brand);78    for (const e of r.errors) errors.push({ path: `brand → ${row.theme_id} v${row.version} : ${e.path}`, message: e.message });79  }80  return errors;81}8283export async function saveApp(db: Db, actor: Actor, app: string, body: any) {84  if (!(APPS as readonly string[]).includes(app)) throw new HttpError(404, 'application inconnue');85  const config = body?.config as AppConfig;86  const note = String(body?.note ?? '').trim().slice(0, 500);87  const errors = await checkAppConfig(db, app, config);88  if (errors.length) throw new HttpError(422, 'configuration invalide', { errors });89  return tx(db, async (c) => {90    const r = await c.query(`INSERT INTO ${db.schema}.app_config_rev (app, config, note, author_id, author_name) VALUES ($1, $2, $3, $4, $5) RETURNING id, created_at`, [app, JSON.stringify(config), note, actor.id, actor.name]);91    await bumpRevision(c, db.schema);92    await audit(c, db.schema, actor, 'app.config', app, { rev: r.rows[0].id, note });93    return { rev: r.rows[0].id, at: r.rows[0].created_at };94  });95}9697// ---------- icônes (SVG)9899const FORBIDDEN = [/<script/i, /<foreignObject/i, /\son[a-z]+\s*=/i, /javascript:/i, /<!ENTITY/i, /<!DOCTYPE/i, /<\?xml-stylesheet/i, /<(iframe|object|embed|image|use|audio|video|animate|set)\b/i, /@import/i, /url\(\s*['"]?(?!#)/i, /(?:xlink:)?href\s*=\s*['"](?!#)/i];100101export function checkSvg(svg: unknown): string {102  if (typeof svg !== 'string') throw new HttpError(400, 'svg : texte attendu');103  const s = svg.trim();104  if (Buffer.byteLength(s) > 64 * 1024) throw new HttpError(413, 'icône : 64 Ko au plus');105  if (!/^(<\?xml[^>]*\?>\s*)?(<!--[\s\S]*?-->\s*)*<svg[\s>]/.test(s) || !/<\/svg>\s*$/.test(s)) throw new HttpError(422, 'le fichier doit être un document SVG');106  if (!/xmlns\s*=\s*["']http:\/\/www\.w3\.org\/2000\/svg["']/.test(s)) throw new HttpError(422, 'attribut xmlns SVG manquant');107  if (!/viewBox\s*=/.test(s)) throw new HttpError(422, 'attribut viewBox requis');108  for (const re of FORBIDDEN) if (re.test(s)) throw new HttpError(422, `contenu SVG refusé (${re.source.replace(/\\/g, '').slice(0, 24)}) : formes et couleurs seulement, sans script, lien ni ressource externe`);109  return s;110}111
Files main
Menu

Theme