server.cjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. const MAX_FRAME_PAYLOAD_BYTES = 10 * 1024 * 1024;
  9. function computeAcceptKey(clientKey) {
  10. return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64');
  11. }
  12. function encodeFrame(opcode, payload) {
  13. const fin = 0x80;
  14. const len = payload.length;
  15. let header;
  16. if (len < 126) {
  17. header = Buffer.alloc(2);
  18. header[0] = fin | opcode;
  19. header[1] = len;
  20. } else if (len < 65536) {
  21. header = Buffer.alloc(4);
  22. header[0] = fin | opcode;
  23. header[1] = 126;
  24. header.writeUInt16BE(len, 2);
  25. } else {
  26. header = Buffer.alloc(10);
  27. header[0] = fin | opcode;
  28. header[1] = 127;
  29. header.writeBigUInt64BE(BigInt(len), 2);
  30. }
  31. return Buffer.concat([header, payload]);
  32. }
  33. function decodeFrame(buffer) {
  34. if (buffer.length < 2) return null;
  35. const secondByte = buffer[1];
  36. const opcode = buffer[0] & 0x0F;
  37. const masked = (secondByte & 0x80) !== 0;
  38. let payloadLen = secondByte & 0x7F;
  39. let offset = 2;
  40. if (!masked) throw new Error('Client frames must be masked');
  41. if (payloadLen === 126) {
  42. if (buffer.length < 4) return null;
  43. payloadLen = buffer.readUInt16BE(2);
  44. offset = 4;
  45. } else if (payloadLen === 127) {
  46. if (buffer.length < 10) return null;
  47. const extendedLen = buffer.readBigUInt64BE(2);
  48. if (extendedLen > BigInt(MAX_FRAME_PAYLOAD_BYTES)) {
  49. throw new Error('WebSocket frame payload exceeds maximum allowed size');
  50. }
  51. payloadLen = Number(extendedLen);
  52. offset = 10;
  53. }
  54. if (payloadLen > MAX_FRAME_PAYLOAD_BYTES) {
  55. throw new Error('WebSocket frame payload exceeds maximum allowed size');
  56. }
  57. const maskOffset = offset;
  58. const dataOffset = offset + 4;
  59. const totalLen = dataOffset + payloadLen;
  60. if (buffer.length < totalLen) return null;
  61. const mask = buffer.slice(maskOffset, dataOffset);
  62. const data = Buffer.alloc(payloadLen);
  63. for (let i = 0; i < payloadLen; i++) {
  64. data[i] = buffer[dataOffset + i] ^ mask[i % 4];
  65. }
  66. return { opcode, payload: data, bytesConsumed: totalLen };
  67. }
  68. // ========== Configuration ==========
  69. const PORT_FILE = process.env.BRAINSTORM_PORT_FILE || null;
  70. const randomPort = () => 49152 + Math.floor(Math.random() * 16383);
  71. // Prefer an explicit port, else the port this session last bound (so a restart
  72. // reuses it and an already-open browser tab reconnects), else a random high port.
  73. function preferredPort() {
  74. if (process.env.BRAINSTORM_PORT) return Number(process.env.BRAINSTORM_PORT);
  75. if (PORT_FILE) {
  76. try {
  77. const p = Number(fs.readFileSync(PORT_FILE, 'utf-8').trim());
  78. if (Number.isInteger(p) && p > 1023 && p < 65536) return p;
  79. } catch (e) { /* no prior port recorded */ }
  80. }
  81. return randomPort();
  82. }
  83. let PORT = preferredPort();
  84. const HOST = process.env.BRAINSTORM_HOST || '127.0.0.1';
  85. const URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST);
  86. const SESSION_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm';
  87. const CONTENT_DIR = path.join(SESSION_DIR, 'content');
  88. const STATE_DIR = path.join(SESSION_DIR, 'state');
  89. let ownerPid = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null;
  90. const MIME_TYPES = {
  91. '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',
  92. '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',
  93. '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml'
  94. };
  95. // ========== Templates and Constants ==========
  96. const WAITING_PAGE = `<!DOCTYPE html>
  97. <html>
  98. <head><meta charset="utf-8"><title>Brainstorm Companion</title>
  99. <style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
  100. h1 { color: #333; } p { color: #666; }</style>
  101. </head>
  102. <body><h1>Brainstorm Companion</h1>
  103. <p>Waiting for the agent to push a screen...</p></body></html>`;
  104. const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');
  105. const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
  106. const helperInjection = '<script>\n' + helperScript + '\n</script>';
  107. // ========== Helper Functions ==========
  108. function isFullDocument(html) {
  109. const trimmed = html.trimStart().toLowerCase();
  110. return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');
  111. }
  112. function wrapInFrame(content) {
  113. return frameTemplate.replace('<!-- CONTENT -->', content);
  114. }
  115. function getNewestScreen() {
  116. const files = fs.readdirSync(CONTENT_DIR)
  117. .filter(f => !f.startsWith('.') && f.endsWith('.html'))
  118. .map(f => {
  119. const fp = path.join(CONTENT_DIR, f);
  120. return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };
  121. })
  122. .sort((a, b) => b.mtime - a.mtime);
  123. return files.length > 0 ? files[0].path : null;
  124. }
  125. // ========== HTTP Request Handler ==========
  126. function handleRequest(req, res) {
  127. touchActivity();
  128. if (req.method === 'GET' && req.url === '/') {
  129. const screenFile = getNewestScreen();
  130. let html = screenFile
  131. ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8'))
  132. : WAITING_PAGE;
  133. if (html.includes('</body>')) {
  134. html = html.replace('</body>', helperInjection + '\n</body>');
  135. } else {
  136. html += helperInjection;
  137. }
  138. res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  139. res.end(html);
  140. } else if (req.method === 'GET' && req.url.startsWith('/files/')) {
  141. const fileName = path.basename(req.url.slice(7));
  142. const filePath = path.join(CONTENT_DIR, fileName);
  143. if (fileName.startsWith('.') || !fs.existsSync(filePath)) {
  144. res.writeHead(404);
  145. res.end('Not found');
  146. return;
  147. }
  148. const ext = path.extname(filePath).toLowerCase();
  149. const contentType = MIME_TYPES[ext] || 'application/octet-stream';
  150. res.writeHead(200, { 'Content-Type': contentType });
  151. res.end(fs.readFileSync(filePath));
  152. } else {
  153. res.writeHead(404);
  154. res.end('Not found');
  155. }
  156. }
  157. // ========== WebSocket Connection Handling ==========
  158. const clients = new Set();
  159. function handleUpgrade(req, socket) {
  160. const key = req.headers['sec-websocket-key'];
  161. if (!key) { socket.destroy(); return; }
  162. const accept = computeAcceptKey(key);
  163. socket.write(
  164. 'HTTP/1.1 101 Switching Protocols\r\n' +
  165. 'Upgrade: websocket\r\n' +
  166. 'Connection: Upgrade\r\n' +
  167. 'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n'
  168. );
  169. let buffer = Buffer.alloc(0);
  170. clients.add(socket);
  171. socket.on('data', (chunk) => {
  172. buffer = Buffer.concat([buffer, chunk]);
  173. while (buffer.length > 0) {
  174. let result;
  175. try {
  176. result = decodeFrame(buffer);
  177. } catch (e) {
  178. socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
  179. clients.delete(socket);
  180. return;
  181. }
  182. if (!result) break;
  183. buffer = buffer.slice(result.bytesConsumed);
  184. switch (result.opcode) {
  185. case OPCODES.TEXT:
  186. handleMessage(result.payload.toString());
  187. break;
  188. case OPCODES.CLOSE:
  189. socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
  190. clients.delete(socket);
  191. return;
  192. case OPCODES.PING:
  193. socket.write(encodeFrame(OPCODES.PONG, result.payload));
  194. break;
  195. case OPCODES.PONG:
  196. break;
  197. default: {
  198. const closeBuf = Buffer.alloc(2);
  199. closeBuf.writeUInt16BE(1003);
  200. socket.end(encodeFrame(OPCODES.CLOSE, closeBuf));
  201. clients.delete(socket);
  202. return;
  203. }
  204. }
  205. }
  206. });
  207. socket.on('close', () => clients.delete(socket));
  208. socket.on('error', () => clients.delete(socket));
  209. }
  210. function handleMessage(text) {
  211. let event;
  212. try {
  213. event = JSON.parse(text);
  214. } catch (e) {
  215. console.error('Failed to parse WebSocket message:', e.message);
  216. return;
  217. }
  218. touchActivity();
  219. console.log(JSON.stringify({ source: 'user-event', ...event }));
  220. if (event.choice) {
  221. const eventsFile = path.join(STATE_DIR, 'events');
  222. fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n');
  223. }
  224. }
  225. function broadcast(msg) {
  226. const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg)));
  227. for (const socket of clients) {
  228. try { socket.write(frame); } catch (e) { clients.delete(socket); }
  229. }
  230. }
  231. // Best-effort: open the user's browser the first time a screen is actually ready
  232. // to show. Skips when disabled, on a non-loopback (remote) bind, or when a
  233. // browser is already connected. Override the launcher with BRAINSTORM_OPEN_CMD.
  234. let browserOpened = false;
  235. function maybeOpenBrowser() {
  236. if (browserOpened) return;
  237. browserOpened = true;
  238. if (!process.env.BRAINSTORM_OPEN) return; // opt-in: only after the user approves the companion
  239. if (HOST !== '127.0.0.1' && HOST !== 'localhost') return;
  240. if (clients.size > 0) return; // the user already opened it
  241. const url = 'http://' + URL_HOST + ':' + PORT;
  242. let cmd = process.env.BRAINSTORM_OPEN_CMD;
  243. if (!cmd) {
  244. if (process.platform === 'darwin') cmd = 'open';
  245. else if (/microsoft/i.test(require('os').release())) cmd = 'cmd.exe /c start ""'; // WSL → Windows browser
  246. else if (process.env.DISPLAY || process.env.WAYLAND_DISPLAY) cmd = 'xdg-open';
  247. else return; // headless: nothing to open
  248. }
  249. try { require('child_process').exec(cmd + ' ' + JSON.stringify(url), () => {}); } catch (e) { /* best effort */ }
  250. }
  251. // ========== Activity Tracking ==========
  252. // Idle timeout: shut down after this long with no activity. Default 4 hours;
  253. // override with BRAINSTORM_IDLE_TIMEOUT_MS (start-server.sh: --idle-timeout-minutes).
  254. const IDLE_TIMEOUT_MS = (() => {
  255. const ms = Number(process.env.BRAINSTORM_IDLE_TIMEOUT_MS);
  256. return Number.isFinite(ms) && ms > 0 ? ms : 4 * 60 * 60 * 1000;
  257. })();
  258. // How often the watchdog checks for owner-death / idleness. Configurable mainly
  259. // so tests can run fast; production default is 60s.
  260. const LIFECYCLE_CHECK_MS = (() => {
  261. const ms = Number(process.env.BRAINSTORM_LIFECYCLE_CHECK_MS);
  262. return Number.isFinite(ms) && ms > 0 ? ms : 60 * 1000;
  263. })();
  264. let lastActivity = Date.now();
  265. function touchActivity() {
  266. lastActivity = Date.now();
  267. }
  268. // ========== File Watching ==========
  269. const debounceTimers = new Map();
  270. // ========== Server Startup ==========
  271. function startServer() {
  272. if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true });
  273. if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true });
  274. // Track known files to distinguish new screens from updates.
  275. // macOS fs.watch reports 'rename' for both new files and overwrites,
  276. // so we can't rely on eventType alone.
  277. const knownFiles = new Set(
  278. fs.readdirSync(CONTENT_DIR).filter(f => !f.startsWith('.') && f.endsWith('.html'))
  279. );
  280. const server = http.createServer(handleRequest);
  281. server.on('upgrade', handleUpgrade);
  282. const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => {
  283. if (!filename || filename.startsWith('.') || !filename.endsWith('.html')) return;
  284. if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename));
  285. debounceTimers.set(filename, setTimeout(() => {
  286. debounceTimers.delete(filename);
  287. const filePath = path.join(CONTENT_DIR, filename);
  288. if (!fs.existsSync(filePath)) return; // file was deleted
  289. touchActivity();
  290. if (!knownFiles.has(filename)) {
  291. knownFiles.add(filename);
  292. const eventsFile = path.join(STATE_DIR, 'events');
  293. if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
  294. console.log(JSON.stringify({ type: 'screen-added', file: filePath }));
  295. maybeOpenBrowser();
  296. } else {
  297. console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));
  298. }
  299. broadcast({ type: 'reload' });
  300. }, 100));
  301. });
  302. watcher.on('error', (err) => console.error('fs.watch error:', err.message));
  303. function shutdown(reason) {
  304. console.log(JSON.stringify({ type: 'server-stopped', reason }));
  305. const infoFile = path.join(STATE_DIR, 'server-info');
  306. if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile);
  307. fs.writeFileSync(
  308. path.join(STATE_DIR, 'server-stopped'),
  309. JSON.stringify({ reason, timestamp: Date.now() }) + '\n'
  310. );
  311. watcher.close();
  312. clearInterval(lifecycleCheck);
  313. // Close any upgraded WebSocket sockets so server.close() can complete and
  314. // the process actually exits instead of lingering on an open connection.
  315. for (const socket of clients) {
  316. try { socket.destroy(); } catch (e) { /* already gone */ }
  317. }
  318. server.close(() => process.exit(0));
  319. }
  320. function ownerAlive() {
  321. if (!ownerPid) return true;
  322. try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
  323. }
  324. // Periodically exit if the owner process died or we've been idle too long.
  325. const lifecycleCheck = setInterval(() => {
  326. if (!ownerAlive()) shutdown('owner process exited');
  327. else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout');
  328. }, LIFECYCLE_CHECK_MS);
  329. lifecycleCheck.unref();
  330. // Validate owner PID at startup. If it's already dead, the PID resolution
  331. // was wrong (common on WSL, Tailscale SSH, and cross-user scenarios).
  332. // Disable monitoring and rely on the idle timeout instead.
  333. if (ownerPid) {
  334. try { process.kill(ownerPid, 0); }
  335. catch (e) {
  336. if (e.code !== 'EPERM') {
  337. console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' }));
  338. ownerPid = null;
  339. }
  340. }
  341. }
  342. function onListen() {
  343. // Record the bound port so the next restart of this session can reuse it.
  344. if (PORT_FILE) {
  345. try { fs.writeFileSync(PORT_FILE, String(PORT)); } catch (e) { /* best effort */ }
  346. }
  347. const info = JSON.stringify({
  348. type: 'server-started', port: Number(PORT), host: HOST,
  349. url_host: URL_HOST, url: 'http://' + URL_HOST + ':' + PORT,
  350. screen_dir: CONTENT_DIR, state_dir: STATE_DIR, idle_timeout_ms: IDLE_TIMEOUT_MS
  351. });
  352. console.log(info);
  353. fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n');
  354. }
  355. // If the preferred port is already taken (e.g. a previous server is still
  356. // alive), fall back to a random port once instead of failing.
  357. let triedFallback = false;
  358. server.on('error', (err) => {
  359. if (err.code === 'EADDRINUSE' && !triedFallback) {
  360. triedFallback = true;
  361. PORT = randomPort();
  362. server.listen(PORT, HOST, onListen);
  363. } else {
  364. console.error('Server failed to bind:', err.message);
  365. process.exit(1);
  366. }
  367. });
  368. server.listen(PORT, HOST, onListen);
  369. }
  370. if (require.main === module) {
  371. startServer();
  372. }
  373. module.exports = { computeAcceptKey, encodeFrame, decodeFrame, OPCODES, MAX_FRAME_PAYLOAD_BYTES };