server.cjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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 SCREEN_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm';
  65. const META_DIR = path.join(SCREEN_DIR, '.meta');
  66. const OWNER_PID = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null;
  67. const MIME_TYPES = {
  68. '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',
  69. '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',
  70. '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml'
  71. };
  72. // ========== Templates and Constants ==========
  73. const WAITING_PAGE = `<!DOCTYPE html>
  74. <html>
  75. <head><meta charset="utf-8"><title>Brainstorm Companion</title>
  76. <style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
  77. h1 { color: #333; } p { color: #666; }</style>
  78. </head>
  79. <body><h1>Brainstorm Companion</h1>
  80. <p>Waiting for the agent to push a screen...</p></body></html>`;
  81. const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');
  82. const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
  83. const helperInjection = '<script>\n' + helperScript + '\n</script>';
  84. // ========== Helper Functions ==========
  85. function isFullDocument(html) {
  86. const trimmed = html.trimStart().toLowerCase();
  87. return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');
  88. }
  89. function wrapInFrame(content) {
  90. return frameTemplate.replace('<!-- CONTENT -->', content);
  91. }
  92. function getNewestScreen() {
  93. const files = fs.readdirSync(SCREEN_DIR)
  94. .filter(f => f.endsWith('.html'))
  95. .map(f => {
  96. const fp = path.join(SCREEN_DIR, f);
  97. return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };
  98. })
  99. .sort((a, b) => b.mtime - a.mtime);
  100. return files.length > 0 ? files[0].path : null;
  101. }
  102. // ========== HTTP Request Handler ==========
  103. function handleRequest(req, res) {
  104. touchActivity();
  105. if (req.method === 'GET' && req.url === '/') {
  106. const screenFile = getNewestScreen();
  107. let html = screenFile
  108. ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8'))
  109. : WAITING_PAGE;
  110. if (html.includes('</body>')) {
  111. html = html.replace('</body>', helperInjection + '\n</body>');
  112. } else {
  113. html += helperInjection;
  114. }
  115. res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  116. res.end(html);
  117. } else if (req.method === 'GET' && req.url.startsWith('/files/')) {
  118. const fileName = req.url.slice(7);
  119. const filePath = path.join(SCREEN_DIR, path.basename(fileName));
  120. if (!fs.existsSync(filePath)) {
  121. res.writeHead(404);
  122. res.end('Not found');
  123. return;
  124. }
  125. const ext = path.extname(filePath).toLowerCase();
  126. const contentType = MIME_TYPES[ext] || 'application/octet-stream';
  127. res.writeHead(200, { 'Content-Type': contentType });
  128. res.end(fs.readFileSync(filePath));
  129. } else {
  130. res.writeHead(404);
  131. res.end('Not found');
  132. }
  133. }
  134. // ========== WebSocket Connection Handling ==========
  135. const clients = new Set();
  136. function handleUpgrade(req, socket) {
  137. const key = req.headers['sec-websocket-key'];
  138. if (!key) { socket.destroy(); return; }
  139. const accept = computeAcceptKey(key);
  140. socket.write(
  141. 'HTTP/1.1 101 Switching Protocols\r\n' +
  142. 'Upgrade: websocket\r\n' +
  143. 'Connection: Upgrade\r\n' +
  144. 'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n'
  145. );
  146. let buffer = Buffer.alloc(0);
  147. clients.add(socket);
  148. socket.on('data', (chunk) => {
  149. buffer = Buffer.concat([buffer, chunk]);
  150. while (buffer.length > 0) {
  151. let result;
  152. try {
  153. result = decodeFrame(buffer);
  154. } catch (e) {
  155. socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
  156. clients.delete(socket);
  157. return;
  158. }
  159. if (!result) break;
  160. buffer = buffer.slice(result.bytesConsumed);
  161. switch (result.opcode) {
  162. case OPCODES.TEXT:
  163. handleMessage(result.payload.toString());
  164. break;
  165. case OPCODES.CLOSE:
  166. socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
  167. clients.delete(socket);
  168. return;
  169. case OPCODES.PING:
  170. socket.write(encodeFrame(OPCODES.PONG, result.payload));
  171. break;
  172. case OPCODES.PONG:
  173. break;
  174. default: {
  175. const closeBuf = Buffer.alloc(2);
  176. closeBuf.writeUInt16BE(1003);
  177. socket.end(encodeFrame(OPCODES.CLOSE, closeBuf));
  178. clients.delete(socket);
  179. return;
  180. }
  181. }
  182. }
  183. });
  184. socket.on('close', () => clients.delete(socket));
  185. socket.on('error', () => clients.delete(socket));
  186. }
  187. function handleMessage(text) {
  188. let event;
  189. try {
  190. event = JSON.parse(text);
  191. } catch (e) {
  192. console.error('Failed to parse WebSocket message:', e.message);
  193. return;
  194. }
  195. touchActivity();
  196. console.log(JSON.stringify({ source: 'user-event', ...event }));
  197. if (event.choice) {
  198. const eventsFile = path.join(META_DIR, '.events');
  199. fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n');
  200. }
  201. }
  202. function broadcast(msg) {
  203. const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg)));
  204. for (const socket of clients) {
  205. try { socket.write(frame); } catch (e) { clients.delete(socket); }
  206. }
  207. }
  208. // ========== Activity Tracking ==========
  209. const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
  210. let lastActivity = Date.now();
  211. function touchActivity() {
  212. lastActivity = Date.now();
  213. }
  214. // ========== File Watching ==========
  215. const debounceTimers = new Map();
  216. // ========== Server Startup ==========
  217. function startServer() {
  218. if (!fs.existsSync(SCREEN_DIR)) fs.mkdirSync(SCREEN_DIR, { recursive: true });
  219. if (!fs.existsSync(META_DIR)) fs.mkdirSync(META_DIR, { recursive: true });
  220. // Track known files to distinguish new screens from updates.
  221. // macOS fs.watch reports 'rename' for both new files and overwrites,
  222. // so we can't rely on eventType alone.
  223. const knownFiles = new Set(
  224. fs.readdirSync(SCREEN_DIR).filter(f => f.endsWith('.html'))
  225. );
  226. const server = http.createServer(handleRequest);
  227. server.on('upgrade', handleUpgrade);
  228. const watcher = fs.watch(SCREEN_DIR, (eventType, filename) => {
  229. if (!filename || !filename.endsWith('.html')) return;
  230. if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename));
  231. debounceTimers.set(filename, setTimeout(() => {
  232. debounceTimers.delete(filename);
  233. const filePath = path.join(SCREEN_DIR, filename);
  234. if (!fs.existsSync(filePath)) return; // file was deleted
  235. touchActivity();
  236. if (!knownFiles.has(filename)) {
  237. knownFiles.add(filename);
  238. const eventsFile = path.join(META_DIR, '.events');
  239. if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
  240. console.log(JSON.stringify({ type: 'screen-added', file: filePath }));
  241. } else {
  242. console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));
  243. }
  244. broadcast({ type: 'reload' });
  245. }, 100));
  246. });
  247. watcher.on('error', (err) => console.error('fs.watch error:', err.message));
  248. function shutdown(reason) {
  249. console.log(JSON.stringify({ type: 'server-stopped', reason }));
  250. const infoFile = path.join(META_DIR, '.server-info');
  251. if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile);
  252. fs.writeFileSync(
  253. path.join(META_DIR, '.server-stopped'),
  254. JSON.stringify({ reason, timestamp: Date.now() }) + '\n'
  255. );
  256. watcher.close();
  257. clearInterval(lifecycleCheck);
  258. server.close(() => process.exit(0));
  259. }
  260. function ownerAlive() {
  261. if (!OWNER_PID) return true;
  262. try { process.kill(OWNER_PID, 0); return true; } catch (e) { return false; }
  263. }
  264. // Check every 60s: exit if owner process died or idle for 30 minutes
  265. const lifecycleCheck = setInterval(() => {
  266. if (!ownerAlive()) shutdown('owner process exited');
  267. else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout');
  268. }, 60 * 1000);
  269. lifecycleCheck.unref();
  270. server.listen(PORT, HOST, () => {
  271. const info = JSON.stringify({
  272. type: 'server-started', port: Number(PORT), host: HOST,
  273. url_host: URL_HOST, url: 'http://' + URL_HOST + ':' + PORT,
  274. screen_dir: SCREEN_DIR
  275. });
  276. console.log(info);
  277. fs.writeFileSync(path.join(META_DIR, '.server-info'), info + '\n');
  278. });
  279. }
  280. if (require.main === module) {
  281. startServer();
  282. }
  283. module.exports = { computeAcceptKey, encodeFrame, decodeFrame, OPCODES };