Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : KA Maps Engine8 * File : studio/cli.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// studio — ligne de commande du Studio (sur le serveur).43// studio migrate44// studio admin-invite "Nom" courriel [--days 7] lien d'activation à usage unique45// studio admin-list | admin-disable courriel | admin-enable courriel46// studio import-themes <dossier> [--rollout 0..100] themes/*.json + themes/brands/*.json47// studio status48import { readdir, readFile } from 'node:fs/promises';49import { join } from 'node:path';50import { authConfigFromEnv, createInvite } from './server/auth.ts';51import { audit, connect, migrate } from './server/db.ts';52import { importThemes } from './server/themes.ts';5354const [cmd, ...args] = process.argv.slice(2);55const url = process.env.STUDIO_DB_URL;56if (!url) {57 console.error('STUDIO_DB_URL requis (voir /etc/kamaps/studio.env)');58 process.exit(2);59}60const db = connect(url, process.env.STUDIO_SCHEMA ?? 'studio');61const opt = (name: string, def: string) => {62 const i = args.indexOf(name);63 return i >= 0 && args[i + 1] !== undefined ? args.splice(i, 2)[1] : def;64};65const cli = { id: null, name: 'cli' };6667try {68 switch (cmd) {69 case 'migrate': {70 const a = await migrate(db);71 console.log(a.length ? `appliqué : ${a.join(', ')}` : 'schéma à jour');72 break;73 }74 case 'admin-invite': {75 const days = Number(opt('--days', '7'));76 const [name, email] = args;77 if (!name || !email) throw new Error('usage : studio admin-invite "Nom" courriel [--days 7]');78 const r = await createInvite(db, name, email, days);79 const origin = authConfigFromEnv().origin;80 console.log(`${r.created ? 'Administrateur créé' : 'Administrateur existant'} : ${r.admin.name} <${r.admin.email}>`);81 console.log(`Lien d'activation (usage unique, valide jusqu'au ${r.expiresAt.toISOString().slice(0, 16).replace('T', ' ')} UTC) :`);82 console.log(`${origin}/activer#${r.token}`);83 break;84 }85 case 'admin-list': {86 const r = await db.pool.query(`SELECT a.name, a.email, a.created_at, a.disabled_at, (SELECT count(*) FROM ${db.schema}.credential c WHERE c.admin_id = a.id) AS keys FROM ${db.schema}.admin a ORDER BY a.created_at`);87 for (const a of r.rows) console.log(`${a.email}\t${a.name}\tclés : ${a.keys}${a.disabled_at ? '\tDÉSACTIVÉ' : ''}`);88 break;89 }90 case 'admin-disable':91 case 'admin-enable': {92 const off = cmd === 'admin-disable';93 const r = await db.pool.query(`UPDATE ${db.schema}.admin SET disabled_at = ${off ? 'now()' : 'NULL'} WHERE email = $1 RETURNING id`, [String(args[0] ?? '').toLowerCase()]);94 if (!r.rows[0]) throw new Error('administrateur inconnu');95 if (off) await db.pool.query(`DELETE FROM ${db.schema}.session WHERE admin_id = $1`, [r.rows[0].id]);96 await audit(db.pool, db.schema, cli, off ? 'admin.disable' : 'admin.enable', args[0]);97 console.log(off ? 'désactivé, sessions fermées' : 'réactivé');98 break;99 }100 case 'import-themes': {101 const percent = Number(opt('--rollout', '0'));102 if (!Number.isInteger(percent) || percent < 0 || percent > 100) throw new Error('--rollout : 0 à 100');103 const dir = args[0];104 if (!dir) throw new Error('usage : studio import-themes <dossier> [--rollout 0..100]');105 await migrate(db);106 const files = [];107 for (const f of (await readdir(dir)).filter((f) => f.endsWith('.json')).sort()) files.push({ name: f, doc: JSON.parse(await readFile(join(dir, f), 'utf8')) });108 const brands = [];109 for (const f of (await readdir(join(dir, 'brands')).catch(() => [])).filter((f) => f.endsWith('.json')).sort()) brands.push({ app: f.replace(/\.json$/, ''), doc: JSON.parse(await readFile(join(dir, 'brands', f), 'utf8')) });110 for (const r of await importThemes(db, cli, files, brands, percent)) console.log(JSON.stringify(r));111 break;112 }113 case 'status': {114 const t = await db.pool.query(`SELECT t.id, (SELECT max(version) FROM ${db.schema}.theme_version v WHERE v.theme_id = t.id) AS latest FROM ${db.schema}.theme t ORDER BY id`);115 const c = await db.pool.query(`SELECT theme_id, app, platform, stable_version, candidate_version, candidate_percent FROM ${db.schema}.channel ORDER BY 1, 2, 3`);116 for (const r of t.rows) console.log(`thème ${r.id} : dernière version ${r.latest ?? '—'}`);117 for (const r of c.rows) console.log(` ${r.theme_id} ${r.app}/${r.platform} : stable v${r.stable_version ?? '—'}${r.candidate_version ? `, candidate v${r.candidate_version} à ${r.candidate_percent} %` : ''}`);118 break;119 }120 default:121 console.log('commandes : migrate | admin-invite "Nom" courriel | admin-list | admin-disable courriel | admin-enable courriel | import-themes <dossier> [--rollout N] | status');122 process.exitCode = cmd ? 2 : 0;123 }124} catch (e: any) {125 console.error(`erreur : ${e.message}${e.detail ? ' ' + JSON.stringify(e.detail).slice(0, 600) : ''}`);126 process.exitCode = 1;127} finally {128 await db.pool.end();129}130