server.cjs 11 KB

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