server.cjs 10 KB

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