1// admin-ka v2 — backend : pont HTTP/WebSocket ⇄ Claude Code CLI (stream-json)2// Sessions détachées (survivent à la déconnexion du client), permissions3// relayées en cartes, monitoring Écosystème temps réel.4import http from 'node:http';5import crypto from 'node:crypto';6import fs from 'node:fs';7import path from 'node:path';8import os from 'node:os';9import { spawn } from 'node:child_process';10import { fileURLToPath } from 'node:url';11import { WebSocketServer } from 'ws';12import { startMonitor, ecoSummary, ecoSite, ecoIncidents, ecoNodes, getIcon, SITES } from './monitor.js';13import { execFile } from 'node:child_process';1415const __dirname = path.dirname(fileURLToPath(import.meta.url));16const APP_DIR = path.join(__dirname, '..');17const DATA_DIR = path.join(APP_DIR, 'data');18const TRANSCRIPTS_DIR = path.join(DATA_DIR, 'transcripts');19const PUBLIC_DIR = path.join(APP_DIR, 'public');20const HOME = os.homedir();2122fs.mkdirSync(TRANSCRIPTS_DIR, { recursive: true });2324// ---------- config ----------25const CONFIG_PATH = path.join(DATA_DIR, 'config.json');26if (!fs.existsSync(CONFIG_PATH)) {27 console.error('config.json manquant — exécuter: node server/set-password.js <motdepasse>');28 process.exit(1);29}30const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));31const PORT = config.port || 3300;32const CLAUDE_BIN = config.claudeBin || '/opt/homebrew/bin/claude';33const NODE_BIN = config.nodeBin || '/opt/homebrew/bin/node';3435// toutes les variables de ~/.claude/.env (ANTHROPIC_API_KEY, APIFY_TOKEN, …)36// sont injectées dans les runs claude locaux (les runs distants font37// `export $(cat ~/.claude/.env | xargs)` côté nœud)38function loadClaudeEnv() {39 const out = {};40 try {41 for (const line of fs.readFileSync(path.join(HOME, '.claude', '.env'), 'utf8').split('\n')) {42 const m = line.match(/^([A-Z0-9_]+)=(\S+)/);43 if (m) out[m[1]] = m[2];44 }45 } catch {}46 return out;47}48const CLAUDE_ENV = loadClaudeEnv();49const ANTHROPIC_API_KEY = CLAUDE_ENV.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY || '';5051// ---------- Upgradeur de prompt (Anthropic Messages API) ----------52const UPGRADER_KEY = config.anthropicKey || CLAUDE_ENV.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY || '';53const UPGRADER_MODEL = config.upgraderModel || 'claude-opus-4-8';5455// Connaissance du Groupe KA injectée dans l'upgradeur pour produire des prompts56// Claude Code précis, conformes aux standards de l'écosystème.57const KA_KNOWLEDGE = `Tu es l'"upgradeur de prompt" de la console administration-ka.com. Ta seule tâche : réécrire la demande brute de l'utilisateur en un prompt EXCELLENT destiné à Claude Code, qui s'exécute sur le nœud d'une app du Groupe KA. Tu ne réponds jamais à la demande toi-même, tu ne codes pas : tu produis UNIQUEMENT le prompt amélioré, prêt à être envoyé.5859# Écosystème Groupe KA (12 apps web, stack Node/React, cluster MacLustr)60- lou-ka (lou-ka.com) : location immobilière/logements. immo-ka (immo-ka.com) : achat/vente immobilier. vrai-prix (vrai-prix.com) : comparateur de prix. valoplex : immobilier/valorisation. auto-ka (auto-ka.com) : véhicules. fabri-ka (fabri-ka.com) : fabricants/artisans/friperies. food-ka (food-ka.com) : alimentation/épicerie. resto-ka (resto-ka.com) : restaurants. sorti-ka (sorti-ka.com) : sorties/événements. crea-ka (crea-ka.com) : créateurs de contenu QC (multi-plateforme). job-ka (job-ka.com) : emplois. trouve-ka (trouve-ka.com) : recherche/annuaire. groupe-ka.com : hub + KA ID (SSO). Marché cible : Québec (fr-CA).61- Architecture commune : back Node (souvent Express/Fastify), front React/Next ou Vite, données via connecteurs (scrapers) + SQLite/Postgres, PM2 pour les process, ngrok pour les domaines. Beaucoup d'apps ont un backend "sync"/crawler et une couche qualité (published/quarantaine).6263# Conventions NON négociables (rappelle-les dans le prompt quand c'est pertinent)64- Remote-first : la source de vérité est le repo de PROD sur le nœud de déploiement ; on édite là, on build, on redémarre PM2, puis git add/commit/push origin main. origin = spbgit (git perso, git.spboucher.ai), PAS GitHub.65- Après toute modif : rebuild si nécessaire + pm2 restart <app> + vérifier le healthcheck/site + commit & push spbgit. Ne jamais laisser de modif non commitée/non déployée.66- Standards UI Groupe KA : header/nav opaques fixes ; échelle de z-index par variables --z-* ; mobile-first, contenu jamais masqué par le clavier (dvh + safe-area) ; anti-zoom iOS (inputs 16px). Pages détail : l'ordre du DOM = l'ordre visuel identique mobile ET desktop (galerie → prix/adresse → description → inclusions → détails → analyses → carte → KA Scores → quartier), JAMAIS de réordonnancement via order:/column-reverse entre breakpoints.67- Design system ka-ui : tokens/couleurs/footer centralisés (ecosystem.json). Toujours valider en mobile (simulateur/Playwright) après un changement d'UI.6869# Outils de scraping/recherche disponibles sur chaque nœud (variables dans ~/.claude/.env)70- Serper (SERPER_API_KEY, recherche Google, gl:ca hl:fr) et Tavily (TAVILY_API_KEY, search/map/extract/crawl) pour DÉCOUVRIR des sources de connecteurs.71- Scrapfly (SCRAPFLY_KEY) et Bright Data Web Unlocker (BRIGHTDATA_API_KEY, zone web_unlocker1) et Oxylabs (Realtime API OXYLABS_USER/PASS + proxies résidentiels OXYLABS_PROXY_* avec ciblage -cc-CA) pour l'anti-bot.72- Apify : 13 acteurs maison gorgeous_thistle/ka-<plateforme> (instagram, tiktok, x, youtube, twitch, kick, fansly, onlyfans, facebook, threads, snapchat, discord, patreon) pour l'enrichissement multi-plateforme de crea-ka ; apify-cli installé (apify push pour builder).7374# Comment écrire le prompt amélioré751. Écris en français, à l'impératif, adressé à Claude Code.762. Commence par l'objectif clair, puis le périmètre précis (fichiers/zones probables), puis les critères d'acceptation vérifiables.773. Ajoute les détails manquants que la demande sous-entend (edge cases, validation, mobile, i18n fr-CA) sans dénaturer l'intention.784. Rappelle les étapes de clôture attendues (build, pm2 restart, healthcheck, commit+push spbgit) UNIQUEMENT si la tâche modifie du code.795. Demande à Claude Code d'explorer/lire avant de modifier, et de vérifier son travail.806. Reste concis et actionnable : pas de blabla, pas de sections inutiles. N'invente pas de faits spécifiques non fournis.817. Sortie = le prompt amélioré SEUL, sans préambule ("Voici…"), sans guillemets englobants, sans commentaire méta.`;8283async function upgradePrompt(rawPrompt, project) {84 if (!UPGRADER_KEY) throw new Error('Clé Anthropic non configurée (config.anthropicKey).');85 const ctx = project ? `\n\nContexte : la demande vise le projet "${project.name}" (déployé sur le nœud ${project.node || SELF_NODE}, répertoire ${project.dir}).` : '';86 const resp = await fetch('https://api.anthropic.com/v1/messages', {87 method: 'POST',88 headers: {89 'x-api-key': UPGRADER_KEY,90 'anthropic-version': '2023-06-01',91 'content-type': 'application/json',92 },93 body: JSON.stringify({94 model: UPGRADER_MODEL,95 max_tokens: 1500,96 system: KA_KNOWLEDGE,97 messages: [{ role: 'user', content: `Réécris cette demande en un prompt Claude Code excellent.${ctx}\n\nDemande brute :\n${rawPrompt}` }],98 }),99 });100 const data = await resp.json();101 if (data.error) throw new Error(data.error.message || 'Erreur Anthropic');102 const text = (data.content || []).filter(b => b.type === 'text').map(b => b.text).join('').trim();103 if (!text) throw new Error('Réponse vide du modèle');104 return text;105}106107// ---------- audit ----------108const AUDIT_PATH = path.join(DATA_DIR, 'audit.jsonl');109function audit(entry) {110 fs.appendFile(AUDIT_PATH, JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n', () => {});111}112113// ---------- sessions (auth) ----------114const SESSIONS_PATH = path.join(DATA_DIR, 'sessions.json');115let sessions = {};116try { sessions = JSON.parse(fs.readFileSync(SESSIONS_PATH, 'utf8')); } catch {}117function saveSessions() { fs.writeFileSync(SESSIONS_PATH, JSON.stringify(sessions)); }118const SESSION_IDLE_MS = 7 * 24 * 3600 * 1000;119const SESSION_MAX_MS = 30 * 24 * 3600 * 1000;120121function verifyPassword(pw) {122 const hash = crypto.scryptSync(pw, Buffer.from(config.salt, 'hex'), 64).toString('hex');123 return crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(config.passwordHash));124}125function newSession() {126 const token = crypto.randomBytes(32).toString('hex');127 sessions[token] = { created: Date.now(), last: Date.now() };128 saveSessions();129 return token;130}131function getSession(req) {132 const cookie = req.headers.cookie || '';133 const m = cookie.match(/(?:^|;\s*)akid=([a-f0-9]{64})/);134 if (!m) return null;135 const s = sessions[m[1]];136 if (!s) return null;137 const now = Date.now();138 if (now - s.last > SESSION_IDLE_MS || now - s.created > SESSION_MAX_MS) {139 delete sessions[m[1]]; saveSessions(); return null;140 }141 s.last = now;142 return m[1];143}144145const loginFails = new Map();146function clientIp(req) {147 const xf = req.headers['x-forwarded-for'];148 return (xf ? String(xf).split(',')[0].trim() : req.socket.remoteAddress) || '?';149}150function loginAllowed(ip) {151 const rec = loginFails.get(ip);152 if (!rec) return true;153 if (Date.now() - rec.first > 15 * 60 * 1000) { loginFails.delete(ip); return true; }154 return rec.count < 8;155}156function loginFailed(ip) {157 const rec = loginFails.get(ip) || { first: Date.now(), count: 0 };158 rec.count++; loginFails.set(ip, rec);159}160161// ---------- chats ----------162const CHATS_PATH = path.join(DATA_DIR, 'chats.json');163let chats = [];164try { chats = JSON.parse(fs.readFileSync(CHATS_PATH, 'utf8')); } catch {}165// migration v1 → v2166for (const c of chats) {167 if (!c.model) c.model = 'fable';168 if (!c.permMode) c.permMode = c.mode === 'auto' ? 'bypass' : 'default';169 if (!c.state) c.state = 'idle';170 if (c.totalCost === undefined) c.totalCost = 0;171 if (!c.alwaysAllow) c.alwaysAllow = [];172 if (c.autoAllowAll === undefined) c.autoAllowAll = false;173}174function saveChats() { fs.writeFileSync(CHATS_PATH, JSON.stringify(chats, null, 1)); }175function getChat(id) { return chats.find(c => c.id === id); }176function publicChat(c) {177 return {178 id: c.id, title: c.title, projectId: c.projectId, projectName: c.projectName,179 model: c.model, permMode: c.permMode, state: c.state, autoAllowAll: !!c.autoAllowAll,180 claudeSessionId: c.claudeSessionId, lastModel: c.lastModel || null,181 totalCost: c.totalCost || 0, turns: c.turns || 0, contextTokens: c.contextTokens || 0,182 created: c.created, updated: c.updated,183 };184}185function transcriptPath(id) { return path.join(TRANSCRIPTS_DIR, id.replace(/[^a-zA-Z0-9_-]/g, '') + '.jsonl'); }186function appendTranscript(chatId, event) {187 fs.appendFile(transcriptPath(chatId), JSON.stringify(event) + '\n', () => {});188}189function readTranscript(chatId) {190 try {191 return fs.readFileSync(transcriptPath(chatId), 'utf8')192 .split('\n').filter(Boolean).map(l => { try { return JSON.parse(l); } catch { return null; } })193 .filter(Boolean);194 } catch { return []; }195}196197// ---------- prompt bank ----------198const PROMPTS_PATH = path.join(DATA_DIR, 'prompts.json');199let prompts = [];200try { prompts = JSON.parse(fs.readFileSync(PROMPTS_PATH, 'utf8')); } catch {}201function savePrompts() { fs.writeFileSync(PROMPTS_PATH, JSON.stringify(prompts, null, 1)); }202203// ---------- projets (12 apps Groupe KA) ----------204const SELF_NODE = 'M3U96a';205const PROJECTS = [206 { id: 'groupe-ka@M3U96b', name: 'Groupe·Ka', node: 'M3U96b', dir: '~/apps/groupe-ka' },207 { id: 'lou-ka@M3U96b', name: 'Lou·Ka', node: 'M3U96b', dir: '~/apps/lou-ka' },208 { id: 'immo-ka@M4M64a', name: 'Immo·Ka', node: 'M4M64a', dir: '~/apps/immo-ka' },209 { id: 'vrai-prix@M3U96a', name: 'Vrai-Prix', node: null, dir: path.join(HOME, 'apps', 'vrai-prix') },210 { id: 'valoplex@M3U96a', name: 'ValoPlex', node: null, dir: path.join(HOME, 'apps', 'valoplex') },211 { id: 'auto-ka@M4M64b', name: 'Auto·Ka', node: 'M4M64b', dir: '~/auto-ka' },212 { id: 'fabri-ka@M4M64a', name: 'Fabri·Ka', node: 'M4M64a', dir: '~/fabri-ka' },213 { id: 'food-ka@M4M64b', name: 'Food·Ka', node: 'M4M64b', dir: '~/apps/food-ka' },214 { id: 'resto-ka@M3U96b', name: 'Resto·Ka', node: 'M3U96b', dir: '~/apps/resto-ka' },215 { id: 'sorti-ka@M3U96a', name: 'Sorti·Ka', node: null, dir: path.join(HOME, 'apps', 'sorti-ka') },216 { id: 'crea-ka@M3U96b', name: 'Créa·Ka', node: 'M3U96b', dir: '~/apps/crea-ka' },217 { id: 'job-ka@M3U96a', name: 'Job·Ka', node: null, dir: path.join(HOME, 'apps', 'job-ka') },218 { id: 'trouve-ka@M2M32', name: 'Trouve·Ka', node: 'M2M32', dir: '~/trouve-ka' },219];220function listProjects() {221 return PROJECTS.map(p => ({ id: p.id, name: p.name, node: p.node || SELF_NODE, dir: p.dir }));222}223function findProject(id) { return PROJECTS.find(p => p.id === id) || null; }224225// ---------- exécution Claude Code ----------226const MODELS = ['fable', 'opus', 'sonnet', 'haiku'];227// mappage vers les IDs réels (les alias CLI des nœuds retombent sur d'anciennes versions)228const CLI_MODEL = { fable: 'claude-fable-5', opus: 'claude-opus-5', sonnet: 'claude-sonnet-5', haiku: 'claude-haiku-4-5-20251001' };229const DEFAULT_MODEL = 'fable';230const PERM_MODES = ['default', 'acceptEdits', 'plan', 'bypass'];231const ALLOWED_READONLY = 'Read,Glob,Grep,LS,WebFetch,WebSearch,TodoWrite,NotebookRead,Task';232233const SYSTEM_APPEND = `RÈGLE OBLIGATOIRE (console administration-ka) : si tu as modifié des fichiers du projet pendant ce tour, tu DOIS avant de conclure : (1) rebuild si le projet a une étape de build ; (2) redéployer — pm2 restart <app> (ou le mécanisme en place) — et VÉRIFIER que l'app répond (healthcheck/port/site) ; (3) committer et pousser : git add + git commit + git push origin main — le remote origin est spbgit (git perso git.spboucher.ai), PAS GitHub. Ne termine jamais en laissant des modifications non commitées ou non redéployées. Si aucun fichier n'a été modifié, ignore cette règle.`;234235const shq = (s) => `'` + String(s).replace(/'/g, `'\\''`) + `'`;236237// chatId -> { proc, permToken, stderr, remote }238const running = new Map();239// requestId -> { chatId, resolve, timer, input, toolKey }240const pendingPerms = new Map();241242function broadcast(chatId, msg) {243 const data = JSON.stringify(msg);244 for (const ws of wss.clients) {245 if (ws.readyState === 1 && ws.chatId === chatId) ws.send(data);246 }247}248function broadcastAll(msg) {249 const data = JSON.stringify(msg);250 for (const ws of wss.clients) if (ws.readyState === 1) ws.send(data);251}252function broadcastEco(msg) {253 const data = JSON.stringify(msg);254 for (const ws of wss.clients) if (ws.readyState === 1 && ws.eco) ws.send(data);255}256function emitAndLog(chatId, msg) {257 appendTranscript(chatId, msg);258 broadcast(chatId, msg);259}260function setChatState(chat, state) {261 chat.state = state;262 chat.updated = Date.now();263 saveChats();264 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });265}266267function permKey(tool, input) {268 if (tool === 'Bash') {269 const first = String(input?.command || '').trim().split(/\s+/)[0] || '?';270 return 'Bash:' + first;271 }272 return tool;273}274275function startClaude(chat, prompt) {276 if (running.has(chat.id)) throw new Error('Une exécution est déjà en cours pour cette conversation.');277 const permToken = crypto.randomBytes(16).toString('hex');278 const model = MODELS.includes(chat.model) ? chat.model : DEFAULT_MODEL;279 const permMode = PERM_MODES.includes(chat.permMode) ? chat.permMode : 'default';280 let proc;281282 const baseArgs = ['-p', '--output-format', 'stream-json', '--verbose', '--include-partial-messages',283 '--model', CLI_MODEL[model], '--append-system-prompt', SYSTEM_APPEND];284 if (chat.claudeSessionId) baseArgs.push('--resume', chat.claudeSessionId);285286 if (!chat.node) {287 // exécution locale (app déployée sur M3U96a)288 const args = [...baseArgs];289 if (permMode === 'bypass') {290 args.push('--dangerously-skip-permissions');291 } else {292 args.push('--permission-mode', permMode);293 const mcpCfg = {294 mcpServers: {295 adminka: {296 command: NODE_BIN,297 args: [path.join(__dirname, 'perm-mcp.js')],298 env: {299 ADMIN_KA_PERM_URL: `http://127.0.0.1:${PORT}/internal/perm`,300 ADMIN_KA_PERM_TOKEN: permToken,301 },302 },303 },304 };305 const cfgPath = path.join(DATA_DIR, `mcp-${chat.id}.json`);306 fs.writeFileSync(cfgPath, JSON.stringify(mcpCfg));307 args.push('--mcp-config', cfgPath);308 args.push('--permission-prompt-tool', 'mcp__adminka__approve');309 args.push('--allowedTools', ALLOWED_READONLY);310 }311 proc = spawn(CLAUDE_BIN, args, {312 cwd: chat.dir,313 env: {314 ...process.env, ...CLAUDE_ENV,315 PATH: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', HOME,316 },317 stdio: ['pipe', 'pipe', 'pipe'],318 detached: false,319 });320 } else {321 // exécution distante : claude tourne SUR le nœud de déploiement de l'app,322 // dans le repo de prod. Permissions via tunnel SSH inverse (IPv4 LAN non routée).323 const sshArgs = ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', '-o', 'ServerAliveInterval=30', '-o', 'ServerAliveCountMax=6'];324 let cmd = 'exec /opt/homebrew/bin/claude ' + baseArgs.map(shq).join(' ');325 if (permMode === 'bypass') {326 cmd += ' --dangerously-skip-permissions';327 } else {328 const revPort = 21000 + Math.floor(Math.random() * 3000);329 sshArgs.push('-R', `127.0.0.1:${revPort}:127.0.0.1:${PORT}`);330 const mcpCfg = {331 mcpServers: {332 adminka: {333 command: '/opt/homebrew/bin/node',334 args: ['/Users/simon-pierreboucher/.adminka/perm-mcp.js'],335 env: {336 ADMIN_KA_PERM_URL: `http://127.0.0.1:${revPort}/internal/perm`,337 ADMIN_KA_PERM_TOKEN: permToken,338 },339 },340 },341 };342 const cfgFile = `/tmp/adminka-mcp-${permToken}.json`;343 cmd = `printf '%s' '${JSON.stringify(mcpCfg)}' > ${cfgFile} && ${cmd} --permission-mode ${permMode} --mcp-config ${cfgFile} --permission-prompt-tool mcp__adminka__approve --allowedTools '${ALLOWED_READONLY}'`;344 }345 const remoteCmd = [346 `cd ${chat.dir}`,347 'export PATH=/opt/homebrew/bin:/usr/local/bin:$PATH',348 'export $(cat ~/.claude/.env | xargs)',349 `echo $$ > /tmp/adminka-pid-${permToken}`,350 cmd,351 ].join(' && ');352 proc = spawn('ssh', [...sshArgs, chat.node, remoteCmd], {353 env: { ...process.env, PATH: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', HOME },354 stdio: ['pipe', 'pipe', 'pipe'],355 });356 }357 proc.stdin.write(prompt);358 proc.stdin.end();359360 const state = { proc, permToken, stderr: '', remote: chat.node || null };361 running.set(chat.id, state);362 audit({ kind: 'prompt', chatId: chat.id, project: chat.projectId, node: chat.node || SELF_NODE, dir: chat.dir, model, permMode, prompt: prompt.slice(0, 2000) });363 emitAndLog(chat.id, { type: 'status', state: 'running' });364 setChatState(chat, 'running');365366 let buf = '';367 proc.stdout.on('data', (d) => {368 buf += d.toString('utf8');369 let idx;370 while ((idx = buf.indexOf('\n')) >= 0) {371 const line = buf.slice(0, idx).trim();372 buf = buf.slice(idx + 1);373 if (!line) continue;374 let ev;375 try { ev = JSON.parse(line); } catch { continue; }376 handleClaudeEvent(chat, ev);377 }378 });379 proc.stderr.on('data', (d) => { state.stderr = (state.stderr + d.toString()).slice(-8000); });380 proc.on('close', (code) => {381 running.delete(chat.id);382 for (const [rid, p] of pendingPerms) {383 if (p.chatId === chat.id) { clearTimeout(p.timer); p.resolve({ behavior: 'deny', message: 'Exécution terminée' }); pendingPerms.delete(rid); }384 }385 if (code !== 0 && code !== null) {386 emitAndLog(chat.id, { type: 'error', message: `claude a quitté (code ${code})\n${state.stderr.slice(-1500)}` });387 }388 emitAndLog(chat.id, { type: 'status', state: 'idle' });389 setChatState(chat, 'idle');390 broadcastAll({ type: 'notify', kind: 'done', chatId: chat.id, title: chat.title, project: chat.projectName });391 });392 proc.on('error', (err) => {393 running.delete(chat.id);394 emitAndLog(chat.id, { type: 'error', message: 'Impossible de lancer claude: ' + err.message });395 emitAndLog(chat.id, { type: 'status', state: 'idle' });396 setChatState(chat, 'idle');397 });398}399400function handleClaudeEvent(chat, ev) {401 if (ev.type === 'system' && ev.subtype === 'init') {402 if (ev.session_id) chat.claudeSessionId = ev.session_id;403 if (ev.model) chat.lastModel = ev.model;404 saveChats();405 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });406 }407 if (ev.type === 'assistant' && ev.message && Array.isArray(ev.message.content)) {408 for (const block of ev.message.content) {409 if (block.type === 'tool_use') {410 audit({ kind: 'tool_use', chatId: chat.id, tool: block.name, input: JSON.stringify(block.input || {}).slice(0, 1000) });411 }412 }413 }414 if (ev.type === 'result') {415 chat.totalCost = (chat.totalCost || 0) + (ev.total_cost_usd || 0);416 chat.turns = (chat.turns || 0) + (ev.num_turns || 0);417 const u = ev.usage || {};418 chat.contextTokens = (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);419 saveChats();420 audit({ kind: 'result', chatId: chat.id, subtype: ev.subtype, cost: ev.total_cost_usd, duration_ms: ev.duration_ms, turns: ev.num_turns });421 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });422 }423 if (ev.type === 'stream_event') {424 broadcast(chat.id, { type: 'claude', event: ev });425 } else {426 emitAndLog(chat.id, { type: 'claude', event: ev });427 }428}429430function interrupt(chatId) {431 const st = running.get(chatId);432 if (!st) return;433 audit({ kind: 'interrupt', chatId });434 if (st.remote) {435 spawn('ssh', ['-o', 'BatchMode=yes', st.remote, `kill -TERM $(cat /tmp/adminka-pid-${st.permToken} 2>/dev/null) 2>/dev/null; rm -f /tmp/adminka-pid-${st.permToken}`], {436 env: { ...process.env, HOME }, stdio: 'ignore',437 });438 }439 st.proc.kill('SIGTERM');440 setTimeout(() => { try { st.proc.kill('SIGKILL'); } catch {} }, 5000);441}442443// exécuter un script sur un nœud (local ou ssh) — pour les actions d'admin444function runOnNode(node, script) {445 return new Promise((resolve) => {446 const full = `export PATH=/opt/homebrew/bin:/usr/local/bin:$PATH; ${script}`;447 const bin = node === SELF_NODE ? '/bin/bash' : 'ssh';448 const args = node === SELF_NODE ? ['-c', full] : ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=12', node, full];449 execFile(bin, args, { timeout: 60_000, maxBuffer: 4 * 1024 * 1024, env: { ...process.env, PATH: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', HOME } },450 (err, stdout, stderr) => resolve({ stdout: String(stdout || ''), stderr: String(stderr || ''), error: err ? (stderr || err.message) : null }));451 });452}453454// ---------- HTTP ----------455const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.json': 'application/json', '.woff2': 'font/woff2' };456457function readBody(req, limit = 512 * 1024) {458 return new Promise((resolve, reject) => {459 let data = '';460 req.on('data', (c) => { data += c; if (data.length > limit) { reject(new Error('body trop gros')); req.destroy(); } });461 req.on('end', () => resolve(data));462 req.on('error', reject);463 });464}465function json(res, code, obj) {466 res.writeHead(code, { 'Content-Type': 'application/json' });467 res.end(JSON.stringify(obj));468}469470const server = http.createServer(async (req, res) => {471 const url = new URL(req.url, 'http://x');472 const p = url.pathname;473474 if (p === '/healthz') { res.writeHead(200); return res.end('ok'); }475476 // logos des sites (favicon/apple-touch-icon en cache) — public, léger477 if (p.startsWith('/icons/')) {478 const icon = getIcon(p.split('/')[2]);479 if (!icon) { res.writeHead(404); return res.end(); }480 res.writeHead(200, { 'Content-Type': icon.type, 'Cache-Control': 'public, max-age=86400' });481 return res.end(icon.buf);482 }483484 // --- endpoint interne de permission (long-poll par perm-mcp.js) ---485 if (p === '/internal/perm' && req.method === 'POST') {486 let body;487 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }488 let chatId = null;489 for (const [cid, st] of running) if (st.permToken === body.token) chatId = cid;490 if (!chatId) return json(res, 403, { error: 'bad token' });491 const chat = getChat(chatId);492 const toolKey = permKey(body.tool_name, body.input);493494 // « Tout autoriser » activé → toute la session est auto-approuvée : la tâche495 // va au bout sans jamais attendre l'utilisateur496 if (chat && chat.autoAllowAll) {497 audit({ kind: 'permission_auto_all', chatId, tool: body.tool_name });498 emitAndLog(chatId, { type: 'permission_auto', tool: body.tool_name, key: 'tout autoriser', input: body.input });499 return json(res, 200, { behavior: 'allow', updatedInput: body.input || {} });500 }501502 // « Toujours autoriser » déjà accordé pour cet outil dans cette conversation503 if (chat && (chat.alwaysAllow || []).includes(toolKey)) {504 audit({ kind: 'permission_auto', chatId, tool: body.tool_name, key: toolKey });505 emitAndLog(chatId, { type: 'permission_auto', tool: body.tool_name, key: toolKey, input: body.input });506 return json(res, 200, { behavior: 'allow', updatedInput: body.input || {} });507 }508509 const requestId = crypto.randomBytes(8).toString('hex');510 const p2 = new Promise((resolve) => {511 const timer = setTimeout(() => {512 pendingPerms.delete(requestId);513 emitAndLog(chatId, { type: 'permission_resolved', requestId, allow: false, reason: 'timeout' });514 if (chat && chat.state === 'waiting_perm') setChatState(chat, 'running');515 resolve({ behavior: 'deny', message: "Pas de réponse de l'utilisateur (timeout 30 min)" });516 }, 30 * 60 * 1000);517 pendingPerms.set(requestId, { chatId, resolve, timer, input: body.input, toolKey });518 });519 audit({ kind: 'permission_request', chatId, tool: body.tool_name, input: JSON.stringify(body.input || {}).slice(0, 1000) });520 emitAndLog(chatId, { type: 'permission_request', requestId, tool: body.tool_name, input: body.input });521 if (chat) setChatState(chat, 'waiting_perm');522 broadcastAll({ type: 'notify', kind: 'perm', chatId, title: chat?.title || '', tool: body.tool_name });523 const decision = await p2;524 return json(res, 200, decision);525 }526527 // --- auth ---528 if (p === '/api/login' && req.method === 'POST') {529 const ip = clientIp(req);530 if (!loginAllowed(ip)) return json(res, 429, { error: 'Trop de tentatives — réessayer dans 15 minutes.' });531 let body;532 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }533 if (typeof body.password !== 'string' || !verifyPassword(body.password)) {534 loginFailed(ip);535 audit({ kind: 'login_fail', ip });536 return json(res, 401, { error: 'Mot de passe invalide.' });537 }538 const token = newSession();539 audit({ kind: 'login_ok', ip });540 res.writeHead(200, {541 'Content-Type': 'application/json',542 'Set-Cookie': `akid=${token}; HttpOnly; Path=/; Max-Age=2592000; SameSite=Lax; Secure`,543 });544 return res.end(JSON.stringify({ ok: true }));545 }546 if (p === '/api/logout' && req.method === 'POST') {547 const t = getSession(req);548 if (t) { delete sessions[t]; saveSessions(); }549 res.writeHead(200, { 'Content-Type': 'application/json', 'Set-Cookie': 'akid=; HttpOnly; Path=/; Max-Age=0; SameSite=Lax; Secure' });550 return res.end(JSON.stringify({ ok: true }));551 }552553 // --- API authentifiée ---554 if (p.startsWith('/api/')) {555 if (!getSession(req)) return json(res, 401, { error: 'auth' });556 if (p === '/api/me') return json(res, 200, { ok: true, host: os.hostname(), node: SELF_NODE, version: '2.0.0' });557 if (p === '/api/projects') return json(res, 200, { projects: listProjects() });558 if (p === '/api/chats' && req.method === 'GET') {559 const list = [...chats].sort((a, b) => (b.updated || 0) - (a.updated || 0)).slice(0, 100).map(publicChat);560 return json(res, 200, { chats: list });561 }562 if (p.startsWith('/api/chats/') && req.method === 'DELETE') {563 const id = p.split('/')[3];564 const chat = getChat(id);565 if (chat && !running.has(id)) {566 chats = chats.filter(c => c.id !== id); saveChats();567 try { fs.unlinkSync(transcriptPath(id)); } catch {}568 return json(res, 200, { ok: true });569 }570 return json(res, 400, { error: 'introuvable ou en cours' });571 }572 // --- prompt bank ---573 if (p === '/api/prompts' && req.method === 'GET') {574 const list = [...prompts].sort((a, b) => (b.updated || 0) - (a.updated || 0));575 return json(res, 200, { prompts: list });576 }577 if (p === '/api/prompts' && req.method === 'POST') {578 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }579 const text = String(body.text || '').trim();580 if (!text) return json(res, 400, { error: 'texte vide' });581 const pr = {582 id: crypto.randomBytes(6).toString('hex'),583 title: (String(body.title || '').trim() || text.slice(0, 48)),584 text,585 project: findProject(body.project) ? body.project : null,586 created: Date.now(), updated: Date.now(),587 };588 prompts.push(pr); savePrompts();589 audit({ kind: 'prompt_save', id: pr.id });590 return json(res, 200, { prompt: pr });591 }592 if (p.startsWith('/api/prompts/') && req.method === 'PUT') {593 const id = p.split('/')[3];594 const pr = prompts.find(x => x.id === id);595 if (!pr) return json(res, 404, { error: 'introuvable' });596 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }597 if (typeof body.text === 'string' && body.text.trim()) pr.text = body.text.trim();598 if (typeof body.title === 'string') pr.title = body.title.trim() || pr.text.slice(0, 48);599 if ('project' in body) pr.project = findProject(body.project) ? body.project : null;600 pr.updated = Date.now(); savePrompts();601 return json(res, 200, { prompt: pr });602 }603 if (p.startsWith('/api/prompts/') && req.method === 'DELETE') {604 const id = p.split('/')[3];605 prompts = prompts.filter(x => x.id !== id); savePrompts();606 return json(res, 200, { ok: true });607 }608 if (p === '/api/upgrade-prompt' && req.method === 'POST') {609 let body;610 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }611 const raw = String(body.prompt || '').trim();612 if (!raw) return json(res, 400, { error: 'prompt vide' });613 try {614 const project = findProject(body.project);615 const upgraded = await upgradePrompt(raw, project);616 audit({ kind: 'upgrade_prompt', project: body.project, len_in: raw.length, len_out: upgraded.length });617 return json(res, 200, { upgraded });618 } catch (e) {619 return json(res, 502, { error: e.message });620 }621 }622 if (p === '/api/eco/summary') return json(res, 200, ecoSummary());623 if (p === '/api/eco/incidents') return json(res, 200, { incidents: ecoIncidents() });624 if (p === '/api/eco/nodes') return json(res, 200, ecoNodes());625 if (p.startsWith('/api/eco/site/')) {626 const d = ecoSite(p.split('/')[4]);627 return d ? json(res, 200, d) : json(res, 404, { error: 'site inconnu' });628 }629630 // --- actions d'administration par site (pm2 / logs / commits) ---631 if (p === '/api/admin/action' && req.method === 'POST') {632 let body;633 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }634 const site = SITES.find(s => s.app === body.app);635 const action = ['restart', 'stop', 'start'].includes(body.action) ? body.action : null;636 if (!site || !action) return json(res, 400, { error: 'app ou action invalide' });637 audit({ kind: 'admin_action', app: site.app, node: site.node, action, ip: clientIp(req) });638 const out = await runOnNode(site.node, `pm2 ${action} ${site.pm2} && pm2 jlist | python3 -c "import json,sys; l=json.load(sys.stdin); p=[x for x in l if x['name']=='${site.pm2}']; print(p[0]['pm2_env']['status'] if p else 'introuvable')"`);639 return json(res, 200, { ok: !out.error, output: (out.stdout || out.error || '').trim().split('\n').pop(), full: (out.stdout || '').slice(-1500) });640 }641 if (p.startsWith('/api/admin/logs/')) {642 const site = SITES.find(s => s.app === p.split('/')[4]);643 if (!site) return json(res, 404, { error: 'site inconnu' });644 const out = await runOnNode(site.node, `pm2 logs ${site.pm2} --nostream --lines 60 2>&1 | tail -70`);645 return json(res, 200, { logs: out.stdout || out.error || '(vide)' });646 }647 if (p.startsWith('/api/admin/commits/')) {648 const site = SITES.find(s => s.app === p.split('/')[4]);649 if (!site) return json(res, 404, { error: 'site inconnu' });650 const out = await runOnNode(site.node, `cd ${site.dir} && echo "=== derniers commits ===" && git log --oneline -8 && echo && echo "=== statut ===" && (git status --short | head -10; [ -z "$(git status --short)" ] && echo "propre ✓")`);651 return json(res, 200, { text: out.stdout || out.error || '(vide)' });652 }653 return json(res, 404, { error: 'not found' });654 }655656 // --- statique ---657 let file = p === '/' ? '/index.html' : p;658 file = path.normalize(file).replace(/^(\.\.[/\\])+/, '');659 const full = path.join(PUBLIC_DIR, file);660 if (!full.startsWith(PUBLIC_DIR)) { res.writeHead(403); return res.end(); }661 fs.readFile(full, (err, data) => {662 if (err) { res.writeHead(404); return res.end('not found'); }663 res.writeHead(200, { 'Content-Type': MIME[path.extname(full)] || 'application/octet-stream', 'Cache-Control': full.includes('/vendor/') ? 'public, max-age=86400' : 'no-cache' });664 res.end(data);665 });666});667668// ---------- WebSocket ----------669const wss = new WebSocketServer({ noServer: true });670671server.on('upgrade', (req, socket, head) => {672 const url = new URL(req.url, 'http://x');673 if (url.pathname !== '/ws' || !getSession(req)) {674 socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');675 return socket.destroy();676 }677 wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req));678});679680wss.on('connection', (ws) => {681 ws.chatId = null;682 ws.eco = false;683 ws.isAlive = true;684 ws.on('pong', () => { ws.isAlive = true; });685 ws.on('message', (raw) => {686 let msg;687 try { msg = JSON.parse(raw.toString()); } catch { return; }688 try { handleWsMessage(ws, msg); } catch (e) {689 ws.send(JSON.stringify({ type: 'error', message: e.message }));690 }691 });692 // NB : la fermeture du socket ne touche JAMAIS aux processus claude en cours.693});694695setInterval(() => {696 for (const ws of wss.clients) {697 if (!ws.isAlive) { ws.terminate(); continue; }698 ws.isAlive = false; ws.ping();699 }700}, 30000);701702function handleWsMessage(ws, msg) {703 if (msg.type === 'open') {704 const chat = getChat(msg.chatId);705 if (!chat) return ws.send(JSON.stringify({ type: 'error', message: 'Conversation introuvable' }));706 ws.chatId = chat.id;707 // rejoue tout l'historique persisté puis raccroche le live708 ws.send(JSON.stringify({709 type: 'history',710 chat: publicChat(chat),711 events: readTranscript(chat.id),712 running: running.has(chat.id),713 }));714 return;715 }716 if (msg.type === 'start') {717 const prompt = String(msg.prompt || '').trim();718 if (!prompt) return;719 let chat = msg.chatId ? getChat(msg.chatId) : null;720 if (!chat) {721 const proj = findProject(msg.project) || PROJECTS[0];722 chat = {723 id: crypto.randomBytes(8).toString('hex'),724 title: prompt.slice(0, 60),725 projectId: proj.id, projectName: proj.name,726 node: proj.node, dir: proj.dir,727 model: MODELS.includes(msg.model) ? msg.model : DEFAULT_MODEL,728 permMode: PERM_MODES.includes(msg.permMode) ? msg.permMode : 'default',729 claudeSessionId: null, state: 'idle',730 totalCost: 0, turns: 0, contextTokens: 0, alwaysAllow: [],731 created: Date.now(), updated: Date.now(),732 };733 chats.push(chat); saveChats();734 ws.send(JSON.stringify({ type: 'chat_created', chat: publicChat(chat) }));735 } else {736 if (MODELS.includes(msg.model)) chat.model = msg.model;737 if (PERM_MODES.includes(msg.permMode)) chat.permMode = msg.permMode;738 saveChats();739 }740 ws.chatId = chat.id;741 emitAndLog(chat.id, { type: 'user_prompt', text: prompt, ts: Date.now() });742 startClaude(chat, prompt);743 return;744 }745 if (msg.type === 'set_opts') {746 const chat = getChat(msg.chatId);747 if (!chat) return;748 if (MODELS.includes(msg.model)) chat.model = msg.model;749 if (PERM_MODES.includes(msg.permMode)) chat.permMode = msg.permMode;750 if (typeof msg.autoAllowAll === 'boolean') chat.autoAllowAll = msg.autoAllowAll;751 saveChats();752 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });753 return;754 }755 if (msg.type === 'clear') {756 const chat = getChat(msg.chatId);757 if (!chat || running.has(chat.id)) return;758 chat.claudeSessionId = null;759 chat.contextTokens = 0;760 saveChats();761 emitAndLog(chat.id, { type: 'notice', text: 'Contexte effacé — la prochaine demande démarre une session Claude Code vierge.' });762 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });763 return;764 }765 if (msg.type === 'perm') {766 const pending = pendingPerms.get(msg.requestId);767 if (!pending) return;768 clearTimeout(pending.timer);769 pendingPerms.delete(msg.requestId);770 const chat = getChat(pending.chatId);771 if (msg.allow && msg.allowAll && chat) {772 // « Tout autoriser » : plus AUCUNE permission ne sera demandée pour cette773 // conversation — le serveur approuve tout jusqu'à la fin de la tâche774 chat.autoAllowAll = true;775 saveChats();776 emitAndLog(chat.id, { type: 'notice', text: '🔓 Tout autoriser activé — la tâche ira au bout sans autre demande de permission.' });777 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });778 }779 if (msg.allow && msg.always && chat) {780 if (!chat.alwaysAllow.includes(pending.toolKey)) chat.alwaysAllow.push(pending.toolKey);781 saveChats();782 }783 audit({ kind: 'permission_response', chatId: pending.chatId, requestId: msg.requestId, allow: !!msg.allow, always: !!msg.always });784 emitAndLog(pending.chatId, { type: 'permission_resolved', requestId: msg.requestId, allow: !!msg.allow, always: !!msg.always });785 if (chat && chat.state === 'waiting_perm') setChatState(chat, 'running');786 pending.resolve(msg.allow787 ? { behavior: 'allow', updatedInput: pending.input || {} }788 : { behavior: 'deny', message: "Refusé par l'utilisateur depuis administration-ka.com" });789 return;790 }791 if (msg.type === 'interrupt') {792 if (msg.chatId) interrupt(msg.chatId);793 else if (ws.chatId) interrupt(ws.chatId);794 return;795 }796 if (msg.type === 'eco_sub') { ws.eco = true; return; }797 if (msg.type === 'eco_unsub') { ws.eco = false; return; }798}799800// ---------- monitoring Écosystème ----------801startMonitor({802 dataDir: DATA_DIR,803 onEvent: (ev) => {804 if (ev.type === 'eco_alert') broadcastAll(ev); // alertes → tout le monde805 else broadcastEco(ev); // ticks → abonnés à l'onglet806 },807});808809// au démarrage, les chats marqués "running" par un ancien processus sont orphelins810for (const c of chats) if (c.state !== 'idle') c.state = 'idle';811saveChats();812813server.listen(PORT, '::', () => {814 console.log(`admin-ka v2 sur port ${PORT} (dual-stack)`);815});816