server.cjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. const crypto = require('crypto');
  2. const http = require('http');
  3. const fs = require('fs');
  4. const path = require('path');
  5. // ========== WebSocket Protocol (RFC 6455) ==========
  6. const OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0A };
  7. const WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
  8. function computeAcceptKey(clientKey) {
  9. return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64');
  10. }
  11. function encodeFrame(opcode, payload) {
  12. const fin = 0x80;
  13. const len = payload.length;
  14. let header;
  15. if (len < 126) {
  16. header = Buffer.alloc(2);
  17. header[0] = fin | opcode;
  18. header[1] = len;
  19. } else if (len < 65536) {
  20. header = Buffer.alloc(4);
  21. header[0] = fin | opcode;
  22. header[1] = 126;
  23. header.writeUInt16BE(len, 2);
  24. } else {
  25. header = Buffer.alloc(10);
  26. header[0] = fin | opcode;
  27. header[1] = 127;
  28. header.writeBigUInt64BE(BigInt(len), 2);
  29. }
  30. return Buffer.concat([header, payload]);
  31. }
  32. function decodeFrame(buffer) {
  33. if (buffer.length < 2) return null;
  34. const secondByte = buffer[1];
  35. const opcode = buffer[0] & 0x0F;
  36. const masked = (secondByte & 0x80) !== 0;
  37. let payloadLen = secondByte & 0x7F;
  38. let offset = 2;
  39. if (!masked) throw new Error('Client frames must be masked');
  40. if (payloadLen === 126) {
  41. if (buffer.length < 4) return null;
  42. payloadLen = buffer.readUInt16BE(2);
  43. offset = 4;
  44. } else if (payloadLen === 127) {
  45. if (buffer.length < 10) return null;
  46. payloadLen = Number(buffer.readBigUInt64BE(2));
  47. offset = 10;
  48. }
  49. const maskOffset = offset;
  50. const dataOffset = offset + 4;
  51. const totalLen = dataOffset + payloadLen;
  52. if (buffer.length < totalLen) return null;
  53. const mask = buffer.slice(maskOffset, dataOffset);
  54. const data = Buffer.alloc(payloadLen);
  55. for (let i = 0; i < payloadLen; i++) {
  56. data[i] = buffer[dataOffset + i] ^ mask[i % 4];
  57. }
  58. return { opcode, payload: data, bytesConsumed: totalLen };
  59. }
  60. // ========== Configuration ==========
  61. const PORT = process.env.BRAINSTORM_PORT || (49152 + Math.floor(Math.random() * 16383));
  62. const HOST = process.env.BRAINSTORM_HOST || '127.0.0.1';
  63. const URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST);
  64. const SESSION_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm';
  65. const CONTENT_DIR = path.join(SESSION_DIR, 'content');
  66. const STATE_DIR = path.join(SESSION_DIR, 'state');
  67. let ownerPid = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null;
  68. const MIME_TYPES = {
  69. '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',
  70. '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',
  71. '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml'
  72. };
  73. // ========== Templates and Constants ==========
  74. const WAITING_PAGE = `<!DOCTYPE html>
  75. <html>
  76. <head><meta charset="utf-8"><title>Brainstorm Companion</title>
  77. <style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
  78. h1 { color: #333; } p { color: #666; }</style>
  79. </head>
  80. <body><h1>Brainstorm Companion</h1>
  81. <p>Waiting for the agent to push a screen...</p></body></html>`;
  82. const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');
  83. const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
  84. const helperInjection = '<script>\n' + helperScript + '\n</script>';
  85. const ALPINE_VENDOR_PATH = path.join(__dirname, 'vendor', 'alpine.js');
  86. function loadVendorFile(filePath, name) {
  87. try {
  88. return fs.readFileSync(filePath);
  89. } catch (error) {
  90. throw new Error(
  91. `Failed to load vendored ${name} at ${filePath}; ` +
  92. 'run the refresh command in skills/brainstorming/scripts/vendor/THIRD_PARTY_NOTICES.md. ' +
  93. error.message
  94. );
  95. }
  96. }
  97. const VENDOR_FILES = new Map([
  98. ['/vendor/alpine.js', {
  99. content: loadVendorFile(ALPINE_VENDOR_PATH, 'Alpine'),
  100. contentType: 'application/javascript; charset=utf-8'
  101. }]
  102. ]);
  103. // ========== Helper Functions ==========
  104. function isFullDocument(html) {
  105. const trimmed = html.trimStart().toLowerCase();
  106. return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');
  107. }
  108. function wrapInFrame(content) {
  109. return frameTemplate.replace('<!-- CONTENT -->', content);
  110. }
  111. function getNewestScreen() {
  112. const files = fs.readdirSync(CONTENT_DIR)
  113. .filter(f => f.endsWith('.html'))
  114. .map(f => {
  115. const fp = path.join(CONTENT_DIR, f);
  116. return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };
  117. })
  118. .sort((a, b) => b.mtime - a.mtime);
  119. return files.length > 0 ? files[0].path : null;
  120. }
  121. function parseRequestUrl(req) {
  122. // Vendor routing depends on URL normalization before exact pathname allowlist checks.
  123. return new URL(req.url, 'http://localhost');
  124. }
  125. function serveVendorFile(requestUrl, res) {
  126. const vendorFile = VENDOR_FILES.get(requestUrl.pathname);
  127. if (!vendorFile) {
  128. res.writeHead(404);
  129. res.end('Not found');
  130. return;
  131. }
  132. res.writeHead(200, { 'Content-Type': vendorFile.contentType });
  133. res.end(vendorFile.content);
  134. }
  135. // ========== HTTP Request Handler ==========
  136. function handleRequest(req, res) {
  137. touchActivity();
  138. const requestUrl = parseRequestUrl(req);
  139. if (req.method === 'GET' && requestUrl.pathname === '/') {
  140. const screenFile = getNewestScreen();
  141. let html = screenFile
  142. ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8'))
  143. : WAITING_PAGE;
  144. if (html.includes('</body>')) {
  145. html = html.replace('</body>', helperInjection + '\n</body>');
  146. } else {
  147. html += helperInjection;
  148. }
  149. res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  150. res.end(html);
  151. } else if (req.method === 'GET' && requestUrl.pathname.startsWith('/vendor/')) {
  152. serveVendorFile(requestUrl, res);
  153. } else if (req.method === 'GET' && requestUrl.pathname.startsWith('/files/')) {
  154. const fileName = requestUrl.pathname.slice(7);
  155. const filePath = path.join(CONTENT_DIR, path.basename(fileName));
  156. if (!fs.existsSync(filePath)) {
  157. res.writeHead(404);
  158. res.end('Not found');
  159. return;
  160. }
  161. const ext = path.extname(filePath).toLowerCase();
  162. const contentType = MIME_TYPES[ext] || 'application/octet-stream';
  163. res.writeHead(200, { 'Content-Type': contentType });
  164. res.end(fs.readFileSync(filePath));
  165. } else {
  166. res.writeHead(404);
  167. res.end('Not found');
  168. }
  169. }
  170. // ========== WebSocket Connection Handling ==========
  171. const clients = new Set();
  172. function handleUpgrade(req, socket) {
  173. const key = req.headers['sec-websocket-key'];
  174. if (!key) { socket.destroy(); return; }
  175. const accept = computeAcceptKey(key);
  176. socket.write(
  177. 'HTTP/1.1 101 Switching Protocols\r\n' +
  178. 'Upgrade: websocket\r\n' +
  179. 'Connection: Upgrade\r\n' +
  180. 'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n'
  181. );
  182. let buffer = Buffer.alloc(0);
  183. clients.add(socket);
  184. socket.on('data', (chunk) => {
  185. buffer = Buffer.concat([buffer, chunk]);
  186. while (buffer.length > 0) {
  187. let result;
  188. try {
  189. result = decodeFrame(buffer);
  190. } catch (e) {
  191. socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
  192. clients.delete(socket);
  193. return;
  194. }
  195. if (!result) break;
  196. buffer = buffer.slice(result.bytesConsumed);
  197. switch (result.opcode) {
  198. case OPCODES.TEXT:
  199. handleMessage(result.payload.toString());
  200. break;
  201. case OPCODES.CLOSE:
  202. socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
  203. clients.delete(socket);
  204. return;
  205. case OPCODES.PING:
  206. socket.write(encodeFrame(OPCODES.PONG, result.payload));
  207. break;
  208. case OPCODES.PONG:
  209. break;
  210. default: {
  211. const closeBuf = Buffer.alloc(2);
  212. closeBuf.writeUInt16BE(1003);
  213. socket.end(encodeFrame(OPCODES.CLOSE, closeBuf));
  214. clients.delete(socket);
  215. return;
  216. }
  217. }
  218. }
  219. });
  220. socket.on('close', () => clients.delete(socket));
  221. socket.on('error', () => clients.delete(socket));
  222. }
  223. function handleMessage(text) {
  224. let event;
  225. try {
  226. event = JSON.parse(text);
  227. } catch (e) {
  228. console.error('Failed to parse WebSocket message:', e.message);
  229. return;
  230. }
  231. touchActivity();
  232. console.log(JSON.stringify({ source: 'user-event', ...event }));
  233. if (event.choice) {
  234. const eventsFile = path.join(STATE_DIR, 'events');
  235. fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n');
  236. }
  237. }
  238. function broadcast(msg) {
  239. const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg)));
  240. for (const socket of clients) {
  241. try { socket.write(frame); } catch (e) { clients.delete(socket); }
  242. }
  243. }
  244. // ========== Activity Tracking ==========
  245. const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
  246. let lastActivity = Date.now();
  247. function touchActivity() {
  248. lastActivity = Date.now();
  249. }
  250. // ========== File Watching ==========
  251. const debounceTimers = new Map();
  252. // ========== Server Startup ==========
  253. function startServer() {
  254. if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true });
  255. if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true });
  256. // Track known files to distinguish new screens from updates.
  257. // macOS fs.watch reports 'rename' for both new files and overwrites,
  258. // so we can't rely on eventType alone.
  259. const knownFiles = new Set(
  260. fs.readdirSync(CONTENT_DIR).filter(f => f.endsWith('.html'))
  261. );
  262. const server = http.createServer(handleRequest);
  263. server.on('upgrade', handleUpgrade);
  264. const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => {
  265. if (!filename || !filename.endsWith('.html')) return;
  266. if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename));
  267. debounceTimers.set(filename, setTimeout(() => {
  268. debounceTimers.delete(filename);
  269. const filePath = path.join(CONTENT_DIR, filename);
  270. if (!fs.existsSync(filePath)) return; // file was deleted
  271. touchActivity();
  272. if (!knownFiles.has(filename)) {
  273. knownFiles.add(filename);
  274. const eventsFile = path.join(STATE_DIR, 'events');
  275. if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
  276. console.log(JSON.stringify({ type: 'screen-added', file: filePath }));
  277. } else {
  278. console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));
  279. }
  280. broadcast({ type: 'reload' });
  281. }, 100));
  282. });
  283. watcher.on('error', (err) => console.error('fs.watch error:', err.message));
  284. function shutdown(reason) {
  285. console.log(JSON.stringify({ type: 'server-stopped', reason }));
  286. const infoFile = path.join(STATE_DIR, 'server-info');
  287. if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile);
  288. fs.writeFileSync(
  289. path.join(STATE_DIR, 'server-stopped'),
  290. JSON.stringify({ reason, timestamp: Date.now() }) + '\n'
  291. );
  292. watcher.close();
  293. clearInterval(lifecycleCheck);
  294. server.close(() => process.exit(0));
  295. }
  296. function ownerAlive() {
  297. if (!ownerPid) return true;
  298. try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
  299. }
  300. // Check every 60s: exit if owner process died or idle for 30 minutes
  301. const lifecycleCheck = setInterval(() => {
  302. if (!ownerAlive()) shutdown('owner process exited');
  303. else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout');
  304. }, 60 * 1000);
  305. lifecycleCheck.unref();
  306. // Validate owner PID at startup. If it's already dead, the PID resolution
  307. // was wrong (common on WSL, Tailscale SSH, and cross-user scenarios).
  308. // Disable monitoring and rely on the idle timeout instead.
  309. if (ownerPid) {
  310. try { process.kill(ownerPid, 0); }
  311. catch (e) {
  312. if (e.code !== 'EPERM') {
  313. console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' }));
  314. ownerPid = null;
  315. }
  316. }
  317. }
  318. server.listen(PORT, HOST, () => {
  319. const info = JSON.stringify({
  320. type: 'server-started', port: Number(PORT), host: HOST,
  321. url_host: URL_HOST, url: 'http://' + URL_HOST + ':' + PORT,
  322. screen_dir: CONTENT_DIR, state_dir: STATE_DIR
  323. });
  324. console.log(info);
  325. fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n');
  326. });
  327. }
  328. if (require.main === module) {
  329. startServer();
  330. }
  331. module.exports = { computeAcceptKey, encodeFrame, decodeFrame, OPCODES };