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 } from './monitor.js';1314const __dirname = path.dirname(fileURLToPath(import.meta.url));15const APP_DIR = path.join(__dirname, '..');16const DATA_DIR = path.join(APP_DIR, 'data');17const TRANSCRIPTS_DIR = path.join(DATA_DIR, 'transcripts');18const PUBLIC_DIR = path.join(APP_DIR, 'public');19const HOME = os.homedir();2021fs.mkdirSync(TRANSCRIPTS_DIR, { recursive: true });2223// ---------- config ----------24const CONFIG_PATH = path.join(DATA_DIR, 'config.json');25if (!fs.existsSync(CONFIG_PATH)) {26 console.error('config.json manquant — exécuter: node server/set-password.js <motdepasse>');27 process.exit(1);28}29const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));30const PORT = config.port || 3300;31const CLAUDE_BIN = config.claudeBin || '/opt/homebrew/bin/claude';32const NODE_BIN = config.nodeBin || '/opt/homebrew/bin/node';3334function loadAnthropicKey() {35 try {36 const envFile = fs.readFileSync(path.join(HOME, '.claude', '.env'), 'utf8');37 const m = envFile.match(/ANTHROPIC_API_KEY=(\S+)/);38 if (m) return m[1];39 } catch {}40 return process.env.ANTHROPIC_API_KEY || '';41}42const ANTHROPIC_API_KEY = loadAnthropicKey();4344// ---------- audit ----------45const AUDIT_PATH = path.join(DATA_DIR, 'audit.jsonl');46function audit(entry) {47 fs.appendFile(AUDIT_PATH, JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n', () => {});48}4950// ---------- sessions (auth) ----------51const SESSIONS_PATH = path.join(DATA_DIR, 'sessions.json');52let sessions = {};53try { sessions = JSON.parse(fs.readFileSync(SESSIONS_PATH, 'utf8')); } catch {}54function saveSessions() { fs.writeFileSync(SESSIONS_PATH, JSON.stringify(sessions)); }55const SESSION_IDLE_MS = 7 * 24 * 3600 * 1000;56const SESSION_MAX_MS = 30 * 24 * 3600 * 1000;5758function verifyPassword(pw) {59 const hash = crypto.scryptSync(pw, Buffer.from(config.salt, 'hex'), 64).toString('hex');60 return crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(config.passwordHash));61}62function newSession() {63 const token = crypto.randomBytes(32).toString('hex');64 sessions[token] = { created: Date.now(), last: Date.now() };65 saveSessions();66 return token;67}68function getSession(req) {69 const cookie = req.headers.cookie || '';70 const m = cookie.match(/(?:^|;\s*)akid=([a-f0-9]{64})/);71 if (!m) return null;72 const s = sessions[m[1]];73 if (!s) return null;74 const now = Date.now();75 if (now - s.last > SESSION_IDLE_MS || now - s.created > SESSION_MAX_MS) {76 delete sessions[m[1]]; saveSessions(); return null;77 }78 s.last = now;79 return m[1];80}8182const loginFails = new Map();83function clientIp(req) {84 const xf = req.headers['x-forwarded-for'];85 return (xf ? String(xf).split(',')[0].trim() : req.socket.remoteAddress) || '?';86}87function loginAllowed(ip) {88 const rec = loginFails.get(ip);89 if (!rec) return true;90 if (Date.now() - rec.first > 15 * 60 * 1000) { loginFails.delete(ip); return true; }91 return rec.count < 8;92}93function loginFailed(ip) {94 const rec = loginFails.get(ip) || { first: Date.now(), count: 0 };95 rec.count++; loginFails.set(ip, rec);96}9798// ---------- chats ----------99const CHATS_PATH = path.join(DATA_DIR, 'chats.json');100let chats = [];101try { chats = JSON.parse(fs.readFileSync(CHATS_PATH, 'utf8')); } catch {}102// migration v1 → v2103for (const c of chats) {104 if (!c.model) c.model = 'fable';105 if (!c.permMode) c.permMode = c.mode === 'auto' ? 'bypass' : 'default';106 if (!c.state) c.state = 'idle';107 if (c.totalCost === undefined) c.totalCost = 0;108 if (!c.alwaysAllow) c.alwaysAllow = [];109}110function saveChats() { fs.writeFileSync(CHATS_PATH, JSON.stringify(chats, null, 1)); }111function getChat(id) { return chats.find(c => c.id === id); }112function publicChat(c) {113 return {114 id: c.id, title: c.title, projectId: c.projectId, projectName: c.projectName,115 model: c.model, permMode: c.permMode, state: c.state,116 claudeSessionId: c.claudeSessionId, lastModel: c.lastModel || null,117 totalCost: c.totalCost || 0, turns: c.turns || 0, contextTokens: c.contextTokens || 0,118 created: c.created, updated: c.updated,119 };120}121function transcriptPath(id) { return path.join(TRANSCRIPTS_DIR, id.replace(/[^a-zA-Z0-9_-]/g, '') + '.jsonl'); }122function appendTranscript(chatId, event) {123 fs.appendFile(transcriptPath(chatId), JSON.stringify(event) + '\n', () => {});124}125function readTranscript(chatId) {126 try {127 return fs.readFileSync(transcriptPath(chatId), 'utf8')128 .split('\n').filter(Boolean).map(l => { try { return JSON.parse(l); } catch { return null; } })129 .filter(Boolean);130 } catch { return []; }131}132133// ---------- projets (12 apps Groupe KA) ----------134const SELF_NODE = 'M3U96a';135const PROJECTS = [136 { id: 'lou-ka@M3U96b', name: 'Lou·Ka', node: 'M3U96b', dir: '~/apps/lou-ka' },137 { id: 'immo-ka@M4M64a', name: 'Immo·Ka', node: 'M4M64a', dir: '~/apps/immo-ka' },138 { id: 'vrai-prix@M3U96a', name: 'Vrai-Prix', node: null, dir: path.join(HOME, 'apps', 'vrai-prix') },139 { id: 'valoplex@M3U96a', name: 'ValoPlex', node: null, dir: path.join(HOME, 'apps', 'valoplex') },140 { id: 'auto-ka@M4M64b', name: 'Auto·Ka', node: 'M4M64b', dir: '~/auto-ka' },141 { id: 'fabri-ka@M4M64a', name: 'Fabri·Ka', node: 'M4M64a', dir: '~/fabri-ka' },142 { id: 'food-ka@M4M64b', name: 'Food·Ka', node: 'M4M64b', dir: '~/apps/food-ka' },143 { id: 'resto-ka@M3U96b', name: 'Resto·Ka', node: 'M3U96b', dir: '~/apps/resto-ka' },144 { id: 'sorti-ka@M3U96a', name: 'Sorti·Ka', node: null, dir: path.join(HOME, 'apps', 'sorti-ka') },145 { id: 'crea-ka@M3U96b', name: 'Créa·Ka', node: 'M3U96b', dir: '~/apps/crea-ka' },146 { id: 'job-ka@M3U96a', name: 'Job·Ka', node: null, dir: path.join(HOME, 'apps', 'job-ka') },147 { id: 'trouve-ka@M2M32', name: 'Trouve·Ka', node: 'M2M32', dir: '~/trouve-ka' },148];149function listProjects() {150 return PROJECTS.map(p => ({ id: p.id, name: p.name, node: p.node || SELF_NODE, dir: p.dir }));151}152function findProject(id) { return PROJECTS.find(p => p.id === id) || null; }153154// ---------- exécution Claude Code ----------155const MODELS = ['fable', 'opus', 'sonnet', 'haiku'];156// mappage vers les IDs réels (les alias CLI des nœuds retombent sur d'anciennes versions)157const CLI_MODEL = { fable: 'claude-fable-5', opus: 'claude-opus-5', sonnet: 'claude-sonnet-5', haiku: 'claude-haiku-4-5-20251001' };158const DEFAULT_MODEL = 'fable';159const PERM_MODES = ['default', 'acceptEdits', 'plan', 'bypass'];160const ALLOWED_READONLY = 'Read,Glob,Grep,LS,WebFetch,WebSearch,TodoWrite,NotebookRead,Task';161162const 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.`;163164const shq = (s) => `'` + String(s).replace(/'/g, `'\\''`) + `'`;165166// chatId -> { proc, permToken, stderr, remote }167const running = new Map();168// requestId -> { chatId, resolve, timer, input, toolKey }169const pendingPerms = new Map();170171function broadcast(chatId, msg) {172 const data = JSON.stringify(msg);173 for (const ws of wss.clients) {174 if (ws.readyState === 1 && ws.chatId === chatId) ws.send(data);175 }176}177function broadcastAll(msg) {178 const data = JSON.stringify(msg);179 for (const ws of wss.clients) if (ws.readyState === 1) ws.send(data);180}181function broadcastEco(msg) {182 const data = JSON.stringify(msg);183 for (const ws of wss.clients) if (ws.readyState === 1 && ws.eco) ws.send(data);184}185function emitAndLog(chatId, msg) {186 appendTranscript(chatId, msg);187 broadcast(chatId, msg);188}189function setChatState(chat, state) {190 chat.state = state;191 chat.updated = Date.now();192 saveChats();193 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });194}195196function permKey(tool, input) {197 if (tool === 'Bash') {198 const first = String(input?.command || '').trim().split(/\s+/)[0] || '?';199 return 'Bash:' + first;200 }201 return tool;202}203204function startClaude(chat, prompt) {205 if (running.has(chat.id)) throw new Error('Une exécution est déjà en cours pour cette conversation.');206 const permToken = crypto.randomBytes(16).toString('hex');207 const model = MODELS.includes(chat.model) ? chat.model : DEFAULT_MODEL;208 const permMode = PERM_MODES.includes(chat.permMode) ? chat.permMode : 'default';209 let proc;210211 const baseArgs = ['-p', '--output-format', 'stream-json', '--verbose', '--include-partial-messages',212 '--model', CLI_MODEL[model], '--append-system-prompt', SYSTEM_APPEND];213 if (chat.claudeSessionId) baseArgs.push('--resume', chat.claudeSessionId);214215 if (!chat.node) {216 // exécution locale (app déployée sur M3U96a)217 const args = [...baseArgs];218 if (permMode === 'bypass') {219 args.push('--dangerously-skip-permissions');220 } else {221 args.push('--permission-mode', permMode);222 const mcpCfg = {223 mcpServers: {224 adminka: {225 command: NODE_BIN,226 args: [path.join(__dirname, 'perm-mcp.js')],227 env: {228 ADMIN_KA_PERM_URL: `http://127.0.0.1:${PORT}/internal/perm`,229 ADMIN_KA_PERM_TOKEN: permToken,230 },231 },232 },233 };234 const cfgPath = path.join(DATA_DIR, `mcp-${chat.id}.json`);235 fs.writeFileSync(cfgPath, JSON.stringify(mcpCfg));236 args.push('--mcp-config', cfgPath);237 args.push('--permission-prompt-tool', 'mcp__adminka__approve');238 args.push('--allowedTools', ALLOWED_READONLY);239 }240 proc = spawn(CLAUDE_BIN, args, {241 cwd: chat.dir,242 env: {243 ...process.env, ANTHROPIC_API_KEY,244 PATH: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', HOME,245 },246 stdio: ['pipe', 'pipe', 'pipe'],247 detached: false,248 });249 } else {250 // exécution distante : claude tourne SUR le nœud de déploiement de l'app,251 // dans le repo de prod. Permissions via tunnel SSH inverse (IPv4 LAN non routée).252 const sshArgs = ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', '-o', 'ServerAliveInterval=30', '-o', 'ServerAliveCountMax=6'];253 let cmd = 'exec /opt/homebrew/bin/claude ' + baseArgs.map(shq).join(' ');254 if (permMode === 'bypass') {255 cmd += ' --dangerously-skip-permissions';256 } else {257 const revPort = 21000 + Math.floor(Math.random() * 3000);258 sshArgs.push('-R', `127.0.0.1:${revPort}:127.0.0.1:${PORT}`);259 const mcpCfg = {260 mcpServers: {261 adminka: {262 command: '/opt/homebrew/bin/node',263 args: ['/Users/simon-pierreboucher/.adminka/perm-mcp.js'],264 env: {265 ADMIN_KA_PERM_URL: `http://127.0.0.1:${revPort}/internal/perm`,266 ADMIN_KA_PERM_TOKEN: permToken,267 },268 },269 },270 };271 const cfgFile = `/tmp/adminka-mcp-${permToken}.json`;272 cmd = `printf '%s' '${JSON.stringify(mcpCfg)}' > ${cfgFile} && ${cmd} --permission-mode ${permMode} --mcp-config ${cfgFile} --permission-prompt-tool mcp__adminka__approve --allowedTools '${ALLOWED_READONLY}'`;273 }274 const remoteCmd = [275 `cd ${chat.dir}`,276 'export PATH=/opt/homebrew/bin:/usr/local/bin:$PATH',277 'export $(cat ~/.claude/.env | xargs)',278 `echo $$ > /tmp/adminka-pid-${permToken}`,279 cmd,280 ].join(' && ');281 proc = spawn('ssh', [...sshArgs, chat.node, remoteCmd], {282 env: { ...process.env, PATH: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', HOME },283 stdio: ['pipe', 'pipe', 'pipe'],284 });285 }286 proc.stdin.write(prompt);287 proc.stdin.end();288289 const state = { proc, permToken, stderr: '', remote: chat.node || null };290 running.set(chat.id, state);291 audit({ kind: 'prompt', chatId: chat.id, project: chat.projectId, node: chat.node || SELF_NODE, dir: chat.dir, model, permMode, prompt: prompt.slice(0, 2000) });292 emitAndLog(chat.id, { type: 'status', state: 'running' });293 setChatState(chat, 'running');294295 let buf = '';296 proc.stdout.on('data', (d) => {297 buf += d.toString('utf8');298 let idx;299 while ((idx = buf.indexOf('\n')) >= 0) {300 const line = buf.slice(0, idx).trim();301 buf = buf.slice(idx + 1);302 if (!line) continue;303 let ev;304 try { ev = JSON.parse(line); } catch { continue; }305 handleClaudeEvent(chat, ev);306 }307 });308 proc.stderr.on('data', (d) => { state.stderr = (state.stderr + d.toString()).slice(-8000); });309 proc.on('close', (code) => {310 running.delete(chat.id);311 for (const [rid, p] of pendingPerms) {312 if (p.chatId === chat.id) { clearTimeout(p.timer); p.resolve({ behavior: 'deny', message: 'Exécution terminée' }); pendingPerms.delete(rid); }313 }314 if (code !== 0 && code !== null) {315 emitAndLog(chat.id, { type: 'error', message: `claude a quitté (code ${code})\n${state.stderr.slice(-1500)}` });316 }317 emitAndLog(chat.id, { type: 'status', state: 'idle' });318 setChatState(chat, 'idle');319 broadcastAll({ type: 'notify', kind: 'done', chatId: chat.id, title: chat.title, project: chat.projectName });320 });321 proc.on('error', (err) => {322 running.delete(chat.id);323 emitAndLog(chat.id, { type: 'error', message: 'Impossible de lancer claude: ' + err.message });324 emitAndLog(chat.id, { type: 'status', state: 'idle' });325 setChatState(chat, 'idle');326 });327}328329function handleClaudeEvent(chat, ev) {330 if (ev.type === 'system' && ev.subtype === 'init') {331 if (ev.session_id) chat.claudeSessionId = ev.session_id;332 if (ev.model) chat.lastModel = ev.model;333 saveChats();334 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });335 }336 if (ev.type === 'assistant' && ev.message && Array.isArray(ev.message.content)) {337 for (const block of ev.message.content) {338 if (block.type === 'tool_use') {339 audit({ kind: 'tool_use', chatId: chat.id, tool: block.name, input: JSON.stringify(block.input || {}).slice(0, 1000) });340 }341 }342 }343 if (ev.type === 'result') {344 chat.totalCost = (chat.totalCost || 0) + (ev.total_cost_usd || 0);345 chat.turns = (chat.turns || 0) + (ev.num_turns || 0);346 const u = ev.usage || {};347 chat.contextTokens = (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);348 saveChats();349 audit({ kind: 'result', chatId: chat.id, subtype: ev.subtype, cost: ev.total_cost_usd, duration_ms: ev.duration_ms, turns: ev.num_turns });350 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });351 }352 if (ev.type === 'stream_event') {353 broadcast(chat.id, { type: 'claude', event: ev });354 } else {355 emitAndLog(chat.id, { type: 'claude', event: ev });356 }357}358359function interrupt(chatId) {360 const st = running.get(chatId);361 if (!st) return;362 audit({ kind: 'interrupt', chatId });363 if (st.remote) {364 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}`], {365 env: { ...process.env, HOME }, stdio: 'ignore',366 });367 }368 st.proc.kill('SIGTERM');369 setTimeout(() => { try { st.proc.kill('SIGKILL'); } catch {} }, 5000);370}371372// ---------- HTTP ----------373const 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' };374375function readBody(req, limit = 512 * 1024) {376 return new Promise((resolve, reject) => {377 let data = '';378 req.on('data', (c) => { data += c; if (data.length > limit) { reject(new Error('body trop gros')); req.destroy(); } });379 req.on('end', () => resolve(data));380 req.on('error', reject);381 });382}383function json(res, code, obj) {384 res.writeHead(code, { 'Content-Type': 'application/json' });385 res.end(JSON.stringify(obj));386}387388const server = http.createServer(async (req, res) => {389 const url = new URL(req.url, 'http://x');390 const p = url.pathname;391392 if (p === '/healthz') { res.writeHead(200); return res.end('ok'); }393394 // --- endpoint interne de permission (long-poll par perm-mcp.js) ---395 if (p === '/internal/perm' && req.method === 'POST') {396 let body;397 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }398 let chatId = null;399 for (const [cid, st] of running) if (st.permToken === body.token) chatId = cid;400 if (!chatId) return json(res, 403, { error: 'bad token' });401 const chat = getChat(chatId);402 const toolKey = permKey(body.tool_name, body.input);403404 // « Toujours autoriser » déjà accordé pour cet outil dans cette conversation405 if (chat && (chat.alwaysAllow || []).includes(toolKey)) {406 audit({ kind: 'permission_auto', chatId, tool: body.tool_name, key: toolKey });407 emitAndLog(chatId, { type: 'permission_auto', tool: body.tool_name, key: toolKey, input: body.input });408 return json(res, 200, { behavior: 'allow', updatedInput: body.input || {} });409 }410411 const requestId = crypto.randomBytes(8).toString('hex');412 const p2 = new Promise((resolve) => {413 const timer = setTimeout(() => {414 pendingPerms.delete(requestId);415 emitAndLog(chatId, { type: 'permission_resolved', requestId, allow: false, reason: 'timeout' });416 if (chat && chat.state === 'waiting_perm') setChatState(chat, 'running');417 resolve({ behavior: 'deny', message: "Pas de réponse de l'utilisateur (timeout 30 min)" });418 }, 30 * 60 * 1000);419 pendingPerms.set(requestId, { chatId, resolve, timer, input: body.input, toolKey });420 });421 audit({ kind: 'permission_request', chatId, tool: body.tool_name, input: JSON.stringify(body.input || {}).slice(0, 1000) });422 emitAndLog(chatId, { type: 'permission_request', requestId, tool: body.tool_name, input: body.input });423 if (chat) setChatState(chat, 'waiting_perm');424 broadcastAll({ type: 'notify', kind: 'perm', chatId, title: chat?.title || '', tool: body.tool_name });425 const decision = await p2;426 return json(res, 200, decision);427 }428429 // --- auth ---430 if (p === '/api/login' && req.method === 'POST') {431 const ip = clientIp(req);432 if (!loginAllowed(ip)) return json(res, 429, { error: 'Trop de tentatives — réessayer dans 15 minutes.' });433 let body;434 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }435 if (typeof body.password !== 'string' || !verifyPassword(body.password)) {436 loginFailed(ip);437 audit({ kind: 'login_fail', ip });438 return json(res, 401, { error: 'Mot de passe invalide.' });439 }440 const token = newSession();441 audit({ kind: 'login_ok', ip });442 res.writeHead(200, {443 'Content-Type': 'application/json',444 'Set-Cookie': `akid=${token}; HttpOnly; Path=/; Max-Age=2592000; SameSite=Lax; Secure`,445 });446 return res.end(JSON.stringify({ ok: true }));447 }448 if (p === '/api/logout' && req.method === 'POST') {449 const t = getSession(req);450 if (t) { delete sessions[t]; saveSessions(); }451 res.writeHead(200, { 'Content-Type': 'application/json', 'Set-Cookie': 'akid=; HttpOnly; Path=/; Max-Age=0; SameSite=Lax; Secure' });452 return res.end(JSON.stringify({ ok: true }));453 }454455 // --- API authentifiée ---456 if (p.startsWith('/api/')) {457 if (!getSession(req)) return json(res, 401, { error: 'auth' });458 if (p === '/api/me') return json(res, 200, { ok: true, host: os.hostname(), node: SELF_NODE, version: '2.0.0' });459 if (p === '/api/projects') return json(res, 200, { projects: listProjects() });460 if (p === '/api/chats' && req.method === 'GET') {461 const list = [...chats].sort((a, b) => (b.updated || 0) - (a.updated || 0)).slice(0, 100).map(publicChat);462 return json(res, 200, { chats: list });463 }464 if (p.startsWith('/api/chats/') && req.method === 'DELETE') {465 const id = p.split('/')[3];466 const chat = getChat(id);467 if (chat && !running.has(id)) {468 chats = chats.filter(c => c.id !== id); saveChats();469 try { fs.unlinkSync(transcriptPath(id)); } catch {}470 return json(res, 200, { ok: true });471 }472 return json(res, 400, { error: 'introuvable ou en cours' });473 }474 if (p === '/api/eco/summary') return json(res, 200, ecoSummary());475 if (p === '/api/eco/incidents') return json(res, 200, { incidents: ecoIncidents() });476 if (p.startsWith('/api/eco/site/')) {477 const d = ecoSite(p.split('/')[4]);478 return d ? json(res, 200, d) : json(res, 404, { error: 'site inconnu' });479 }480 return json(res, 404, { error: 'not found' });481 }482483 // --- statique ---484 let file = p === '/' ? '/index.html' : p;485 file = path.normalize(file).replace(/^(\.\.[/\\])+/, '');486 const full = path.join(PUBLIC_DIR, file);487 if (!full.startsWith(PUBLIC_DIR)) { res.writeHead(403); return res.end(); }488 fs.readFile(full, (err, data) => {489 if (err) { res.writeHead(404); return res.end('not found'); }490 res.writeHead(200, { 'Content-Type': MIME[path.extname(full)] || 'application/octet-stream', 'Cache-Control': full.includes('/vendor/') ? 'public, max-age=86400' : 'no-cache' });491 res.end(data);492 });493});494495// ---------- WebSocket ----------496const wss = new WebSocketServer({ noServer: true });497498server.on('upgrade', (req, socket, head) => {499 const url = new URL(req.url, 'http://x');500 if (url.pathname !== '/ws' || !getSession(req)) {501 socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');502 return socket.destroy();503 }504 wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req));505});506507wss.on('connection', (ws) => {508 ws.chatId = null;509 ws.eco = false;510 ws.isAlive = true;511 ws.on('pong', () => { ws.isAlive = true; });512 ws.on('message', (raw) => {513 let msg;514 try { msg = JSON.parse(raw.toString()); } catch { return; }515 try { handleWsMessage(ws, msg); } catch (e) {516 ws.send(JSON.stringify({ type: 'error', message: e.message }));517 }518 });519 // NB : la fermeture du socket ne touche JAMAIS aux processus claude en cours.520});521522setInterval(() => {523 for (const ws of wss.clients) {524 if (!ws.isAlive) { ws.terminate(); continue; }525 ws.isAlive = false; ws.ping();526 }527}, 30000);528529function handleWsMessage(ws, msg) {530 if (msg.type === 'open') {531 const chat = getChat(msg.chatId);532 if (!chat) return ws.send(JSON.stringify({ type: 'error', message: 'Conversation introuvable' }));533 ws.chatId = chat.id;534 // rejoue tout l'historique persisté puis raccroche le live535 ws.send(JSON.stringify({536 type: 'history',537 chat: publicChat(chat),538 events: readTranscript(chat.id),539 running: running.has(chat.id),540 }));541 return;542 }543 if (msg.type === 'start') {544 const prompt = String(msg.prompt || '').trim();545 if (!prompt) return;546 let chat = msg.chatId ? getChat(msg.chatId) : null;547 if (!chat) {548 const proj = findProject(msg.project) || PROJECTS[0];549 chat = {550 id: crypto.randomBytes(8).toString('hex'),551 title: prompt.slice(0, 60),552 projectId: proj.id, projectName: proj.name,553 node: proj.node, dir: proj.dir,554 model: MODELS.includes(msg.model) ? msg.model : DEFAULT_MODEL,555 permMode: PERM_MODES.includes(msg.permMode) ? msg.permMode : 'default',556 claudeSessionId: null, state: 'idle',557 totalCost: 0, turns: 0, contextTokens: 0, alwaysAllow: [],558 created: Date.now(), updated: Date.now(),559 };560 chats.push(chat); saveChats();561 ws.send(JSON.stringify({ type: 'chat_created', chat: publicChat(chat) }));562 } else {563 if (MODELS.includes(msg.model)) chat.model = msg.model;564 if (PERM_MODES.includes(msg.permMode)) chat.permMode = msg.permMode;565 saveChats();566 }567 ws.chatId = chat.id;568 emitAndLog(chat.id, { type: 'user_prompt', text: prompt, ts: Date.now() });569 startClaude(chat, prompt);570 return;571 }572 if (msg.type === 'set_opts') {573 const chat = getChat(msg.chatId);574 if (!chat) return;575 if (MODELS.includes(msg.model)) chat.model = msg.model;576 if (PERM_MODES.includes(msg.permMode)) chat.permMode = msg.permMode;577 saveChats();578 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });579 return;580 }581 if (msg.type === 'clear') {582 const chat = getChat(msg.chatId);583 if (!chat || running.has(chat.id)) return;584 chat.claudeSessionId = null;585 chat.contextTokens = 0;586 saveChats();587 emitAndLog(chat.id, { type: 'notice', text: 'Contexte effacé — la prochaine demande démarre une session Claude Code vierge.' });588 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });589 return;590 }591 if (msg.type === 'perm') {592 const pending = pendingPerms.get(msg.requestId);593 if (!pending) return;594 clearTimeout(pending.timer);595 pendingPerms.delete(msg.requestId);596 const chat = getChat(pending.chatId);597 if (msg.allow && msg.always && chat) {598 if (!chat.alwaysAllow.includes(pending.toolKey)) chat.alwaysAllow.push(pending.toolKey);599 saveChats();600 }601 audit({ kind: 'permission_response', chatId: pending.chatId, requestId: msg.requestId, allow: !!msg.allow, always: !!msg.always });602 emitAndLog(pending.chatId, { type: 'permission_resolved', requestId: msg.requestId, allow: !!msg.allow, always: !!msg.always });603 if (chat && chat.state === 'waiting_perm') setChatState(chat, 'running');604 pending.resolve(msg.allow605 ? { behavior: 'allow', updatedInput: pending.input || {} }606 : { behavior: 'deny', message: "Refusé par l'utilisateur depuis administration-ka.com" });607 return;608 }609 if (msg.type === 'interrupt') {610 if (msg.chatId) interrupt(msg.chatId);611 else if (ws.chatId) interrupt(ws.chatId);612 return;613 }614 if (msg.type === 'eco_sub') { ws.eco = true; return; }615 if (msg.type === 'eco_unsub') { ws.eco = false; return; }616}617618// ---------- monitoring Écosystème ----------619startMonitor({620 dataDir: DATA_DIR,621 onEvent: (ev) => {622 if (ev.type === 'eco_alert') broadcastAll(ev); // alertes → tout le monde623 else broadcastEco(ev); // ticks → abonnés à l'onglet624 },625});626627// au démarrage, les chats marqués "running" par un ancien processus sont orphelins628for (const c of chats) if (c.state !== 'idle') c.state = 'idle';629saveChats();630631server.listen(PORT, '::', () => {632 console.log(`admin-ka v2 sur port ${PORT} (dual-stack)`);633});634