1
0

server.cjs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. // Per-session secret key. The companion is reachable by any local browser tab
  91. // and, when bound to a non-loopback host, by any host that can route to it.
  92. // The key authenticates the real client uniformly across loopback, tunnel, and
  93. // remote binds — and defeats DNS rebinding — where a Host/Origin allowlist
  94. // cannot. It rides the served URL as ?key= and is mirrored into a cookie on
  95. // first load so same-origin subresources and the WebSocket carry it for free.
  96. // Persisted alongside the port (BRAINSTORM_TOKEN_FILE) so a restart keeps the
  97. // same key and an already-open tab's cookie still validates.
  98. const TOKEN_FILE = process.env.BRAINSTORM_TOKEN_FILE || null;
  99. const TOKEN = (() => {
  100. if (process.env.BRAINSTORM_TOKEN) return process.env.BRAINSTORM_TOKEN;
  101. if (TOKEN_FILE) {
  102. try {
  103. const t = fs.readFileSync(TOKEN_FILE, 'utf-8').trim();
  104. if (/^[0-9a-f]{32,}$/i.test(t)) return t;
  105. } catch (e) { /* no prior token recorded */ }
  106. }
  107. return crypto.randomBytes(32).toString('hex');
  108. })();
  109. let COOKIE_NAME = 'brainstorm-key-' + PORT; // refined to the actual bound port in onListen
  110. const MIME_TYPES = {
  111. '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',
  112. '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',
  113. '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml'
  114. };
  115. // ========== Templates and Constants ==========
  116. const WAITING_PAGE = `<!DOCTYPE html>
  117. <html>
  118. <head><meta charset="utf-8"><title>Brainstorm Companion</title>
  119. <style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
  120. h1 { color: #333; } p { color: #666; }</style>
  121. </head>
  122. <body><h1>Brainstorm Companion</h1>
  123. <p>Waiting for the agent to push a screen...</p></body></html>`;
  124. const FORBIDDEN_PAGE = `<!DOCTYPE html>
  125. <html>
  126. <head><meta charset="utf-8"><title>Session key required</title>
  127. <style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
  128. h1 { color: #333; } p { color: #666; } code { background: #f0f0f0; padding: 0.1em 0.3em; border-radius: 4px; }</style>
  129. </head>
  130. <body><h1>Session key required</h1>
  131. <p>This page needs the full URL your coding agent gave you, including the
  132. <code>?key=&hellip;</code> part. Copy the complete URL and open it again.</p></body></html>`;
  133. function bootstrapPage(key) {
  134. const jsonKey = JSON.stringify(String(key));
  135. return `<!DOCTYPE html>
  136. <html>
  137. <head><meta charset="utf-8"><title>Opening Brainstorm Companion</title></head>
  138. <body>
  139. <script>
  140. try { sessionStorage.setItem('brainstorm-session-key', ${jsonKey}); } catch (e) {}
  141. location.replace('/');
  142. </script>
  143. </body>
  144. </html>`;
  145. }
  146. const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');
  147. const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
  148. const helperInjection = '<script>\n' + helperScript + '\n</script>';
  149. // ========== Helper Functions ==========
  150. function isFullDocument(html) {
  151. const trimmed = html.trimStart().toLowerCase();
  152. return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');
  153. }
  154. function wrapInFrame(content) {
  155. return frameTemplate.replace('<!-- CONTENT -->', content);
  156. }
  157. function getNewestScreen() {
  158. const files = fs.readdirSync(CONTENT_DIR)
  159. .filter(f => !f.startsWith('.') && f.endsWith('.html'))
  160. .map(f => {
  161. const fp = path.join(CONTENT_DIR, f);
  162. return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };
  163. })
  164. .sort((a, b) => b.mtime - a.mtime);
  165. return files.length > 0 ? files[0].path : null;
  166. }
  167. function urlHostForHttp(host) {
  168. const h = String(host);
  169. if (h.startsWith('[') && h.endsWith(']')) return h;
  170. return h.includes(':') ? '[' + h + ']' : h;
  171. }
  172. function companionUrl() {
  173. return 'http://' + urlHostForHttp(URL_HOST) + ':' + PORT + '/?key=' + TOKEN;
  174. }
  175. function isRegularFileInsideContentDir(filePath) {
  176. let stat, realContentDir, realFilePath;
  177. try {
  178. stat = fs.lstatSync(filePath);
  179. if (stat.isSymbolicLink()) return false;
  180. if (!stat.isFile()) return false;
  181. if (stat.nlink !== 1) return false;
  182. realContentDir = fs.realpathSync(CONTENT_DIR);
  183. realFilePath = fs.realpathSync(filePath);
  184. } catch (e) {
  185. return false;
  186. }
  187. return realFilePath.startsWith(realContentDir + path.sep);
  188. }
  189. // ========== Authentication ==========
  190. function timingSafeEqualStr(a, b) {
  191. const ab = Buffer.from(String(a));
  192. const bb = Buffer.from(String(b));
  193. if (ab.length !== bb.length) return false;
  194. return crypto.timingSafeEqual(ab, bb);
  195. }
  196. function parseCookies(header) {
  197. const out = {};
  198. if (!header) return out;
  199. for (const part of header.split(';')) {
  200. const eq = part.indexOf('=');
  201. if (eq < 0) continue;
  202. out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim();
  203. }
  204. return out;
  205. }
  206. // A request is authorized if it carries the session key as ?key= or as the
  207. // session cookie. Both are compared in constant time.
  208. function isAuthorized(req) {
  209. const q = req.url.indexOf('?');
  210. if (q >= 0) {
  211. const params = new URLSearchParams(req.url.slice(q + 1));
  212. if (params.has('key')) {
  213. const key = params.get('key');
  214. return Boolean(key && timingSafeEqualStr(key, TOKEN));
  215. }
  216. }
  217. const cookie = parseCookies(req.headers['cookie'])[COOKIE_NAME];
  218. if (cookie && timingSafeEqualStr(cookie, TOKEN)) return true;
  219. return false;
  220. }
  221. function pathnameOf(url) {
  222. const q = url.indexOf('?');
  223. return q >= 0 ? url.slice(0, q) : url;
  224. }
  225. function queryKey(url) {
  226. const q = url.indexOf('?');
  227. if (q < 0) return null;
  228. return new URLSearchParams(url.slice(q + 1)).get('key');
  229. }
  230. function securityHeaders(headers = {}) {
  231. return {
  232. 'Referrer-Policy': 'no-referrer',
  233. 'Cache-Control': 'no-store',
  234. 'X-Frame-Options': 'DENY',
  235. 'Content-Security-Policy': "frame-ancestors 'none'",
  236. 'Cross-Origin-Resource-Policy': 'same-origin',
  237. ...headers
  238. };
  239. }
  240. function isAllowedWebSocketOrigin(req) {
  241. const origin = req.headers.origin;
  242. if (!origin) return true;
  243. const host = req.headers.host;
  244. if (!host) return false;
  245. return origin === 'http://' + host;
  246. }
  247. // ========== HTTP Request Handler ==========
  248. function handleRequest(req, res) {
  249. if (!isAuthorized(req)) {
  250. res.writeHead(403, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));
  251. res.end(FORBIDDEN_PAGE);
  252. return;
  253. }
  254. touchActivity(); // only authorized requests count as activity
  255. // Mirror the key into a cookie so same-origin subresources (/files/*) can
  256. // authenticate after bootstrap. HttpOnly keeps it away from page scripts; the
  257. // WebSocket Origin check below is what blocks cross-origin localhost injection.
  258. res.setHeader('Set-Cookie',
  259. COOKIE_NAME + '=' + TOKEN + '; HttpOnly; SameSite=Strict; Path=/');
  260. const pathname = pathnameOf(req.url);
  261. const keyFromQuery = queryKey(req.url);
  262. if (req.method === 'GET' && pathname === '/' && keyFromQuery && timingSafeEqualStr(keyFromQuery, TOKEN)) {
  263. res.writeHead(200, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));
  264. res.end(bootstrapPage(keyFromQuery));
  265. } else if (req.method === 'GET' && pathname === '/') {
  266. const screenFile = getNewestScreen();
  267. let html = screenFile
  268. ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8'))
  269. : WAITING_PAGE;
  270. if (html.includes('</body>')) {
  271. html = html.replace('</body>', helperInjection + '\n</body>');
  272. } else {
  273. html += helperInjection;
  274. }
  275. res.writeHead(200, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));
  276. res.end(html);
  277. } else if (req.method === 'GET' && pathname.startsWith('/files/')) {
  278. const fileName = path.basename(pathname.slice(7));
  279. const filePath = path.join(CONTENT_DIR, fileName);
  280. // Reject empty/dotfile names and anything that isn't a regular file —
  281. // `/files/` would otherwise resolve to CONTENT_DIR and crash readFileSync (EISDIR).
  282. if (!fileName || fileName.startsWith('.') || !isRegularFileInsideContentDir(filePath)) {
  283. res.writeHead(404, securityHeaders());
  284. res.end('Not found');
  285. return;
  286. }
  287. const ext = path.extname(filePath).toLowerCase();
  288. const contentType = MIME_TYPES[ext] || 'application/octet-stream';
  289. res.writeHead(200, securityHeaders({ 'Content-Type': contentType }));
  290. res.end(fs.readFileSync(filePath));
  291. } else {
  292. res.writeHead(404, securityHeaders());
  293. res.end('Not found');
  294. }
  295. }
  296. // ========== WebSocket Connection Handling ==========
  297. const clients = new Set();
  298. function handleUpgrade(req, socket) {
  299. if (!isAuthorized(req) || !isAllowedWebSocketOrigin(req)) { socket.destroy(); return; }
  300. const key = req.headers['sec-websocket-key'];
  301. if (!key) { socket.destroy(); return; }
  302. const accept = computeAcceptKey(key);
  303. socket.write(
  304. 'HTTP/1.1 101 Switching Protocols\r\n' +
  305. 'Upgrade: websocket\r\n' +
  306. 'Connection: Upgrade\r\n' +
  307. 'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n'
  308. );
  309. let buffer = Buffer.alloc(0);
  310. clients.add(socket);
  311. socket.on('data', (chunk) => {
  312. buffer = Buffer.concat([buffer, chunk]);
  313. while (buffer.length > 0) {
  314. let result;
  315. try {
  316. result = decodeFrame(buffer);
  317. } catch (e) {
  318. socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
  319. clients.delete(socket);
  320. return;
  321. }
  322. if (!result) break;
  323. buffer = buffer.slice(result.bytesConsumed);
  324. switch (result.opcode) {
  325. case OPCODES.TEXT:
  326. handleMessage(result.payload.toString());
  327. break;
  328. case OPCODES.CLOSE:
  329. socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
  330. clients.delete(socket);
  331. return;
  332. case OPCODES.PING:
  333. socket.write(encodeFrame(OPCODES.PONG, result.payload));
  334. break;
  335. case OPCODES.PONG:
  336. break;
  337. default: {
  338. const closeBuf = Buffer.alloc(2);
  339. closeBuf.writeUInt16BE(1003);
  340. socket.end(encodeFrame(OPCODES.CLOSE, closeBuf));
  341. clients.delete(socket);
  342. return;
  343. }
  344. }
  345. }
  346. });
  347. socket.on('close', () => clients.delete(socket));
  348. socket.on('error', () => clients.delete(socket));
  349. }
  350. function handleMessage(text) {
  351. let event;
  352. try {
  353. event = JSON.parse(text);
  354. } catch (e) {
  355. console.error('Failed to parse WebSocket message:', e.message);
  356. return;
  357. }
  358. touchActivity();
  359. console.log(JSON.stringify({ source: 'user-event', ...event }));
  360. if (event && event.choice) {
  361. const eventsFile = path.join(STATE_DIR, 'events');
  362. fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n');
  363. }
  364. }
  365. function broadcast(msg) {
  366. const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg)));
  367. for (const socket of clients) {
  368. try { socket.write(frame); } catch (e) { clients.delete(socket); }
  369. }
  370. }
  371. // Best-effort: open the user's browser the first time a screen is actually ready
  372. // to show. Skips when disabled, on a non-loopback (remote) bind, or when a
  373. // browser is already connected. Override the launcher with BRAINSTORM_OPEN_CMD.
  374. let browserOpened = false;
  375. function maybeOpenBrowser() {
  376. if (browserOpened) return;
  377. browserOpened = true;
  378. if (!process.env.BRAINSTORM_OPEN) return; // opt-in: only after the user approves the companion
  379. if (HOST !== '127.0.0.1' && HOST !== 'localhost') return;
  380. if (clients.size > 0) return; // the user already opened it
  381. const url = companionUrl(); // must carry the key or the gate 403s it
  382. const cp = require('child_process');
  383. // Operator-provided launcher: run as given (this env var is trusted operator input).
  384. if (process.env.BRAINSTORM_OPEN_CMD) {
  385. try { cp.exec(process.env.BRAINSTORM_OPEN_CMD + ' ' + JSON.stringify(url), () => {}); } catch (e) { /* best effort */ }
  386. return;
  387. }
  388. // Platform launchers: pass the URL as an argv element via execFile (no shell),
  389. // so a url-host containing shell metacharacters can't inject a command.
  390. const isWSL = process.platform === 'linux' && /microsoft/i.test(require('os').release());
  391. let bin, args;
  392. if (process.platform === 'darwin') { bin = 'open'; args = [url]; }
  393. else if (process.platform === 'win32' || isWSL) { bin = 'cmd.exe'; args = ['/c', 'start', '', url]; }
  394. else if (process.env.DISPLAY || process.env.WAYLAND_DISPLAY) { bin = 'xdg-open'; args = [url]; }
  395. else return; // headless: nothing to open
  396. try { cp.execFile(bin, args, () => {}); } catch (e) { /* best effort */ }
  397. }
  398. // ========== Activity Tracking ==========
  399. // Idle timeout: shut down after this long with no activity. Default 4 hours;
  400. // override with BRAINSTORM_IDLE_TIMEOUT_MS (start-server.sh: --idle-timeout-minutes).
  401. const IDLE_TIMEOUT_MS = (() => {
  402. const ms = Number(process.env.BRAINSTORM_IDLE_TIMEOUT_MS);
  403. return Number.isFinite(ms) && ms > 0 ? ms : 4 * 60 * 60 * 1000;
  404. })();
  405. // How often the watchdog checks for owner-death / idleness. Configurable mainly
  406. // so tests can run fast; production default is 60s.
  407. const LIFECYCLE_CHECK_MS = (() => {
  408. const ms = Number(process.env.BRAINSTORM_LIFECYCLE_CHECK_MS);
  409. return Number.isFinite(ms) && ms > 0 ? ms : 60 * 1000;
  410. })();
  411. let lastActivity = Date.now();
  412. function touchActivity() {
  413. lastActivity = Date.now();
  414. }
  415. // ========== File Watching ==========
  416. const debounceTimers = new Map();
  417. // ========== Server Startup ==========
  418. function startServer() {
  419. if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true });
  420. if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true });
  421. // Track known files to distinguish new screens from updates.
  422. // macOS fs.watch reports 'rename' for both new files and overwrites,
  423. // so we can't rely on eventType alone.
  424. const knownFiles = new Set(
  425. fs.readdirSync(CONTENT_DIR).filter(f => !f.startsWith('.') && f.endsWith('.html'))
  426. );
  427. const server = http.createServer(handleRequest);
  428. server.on('upgrade', handleUpgrade);
  429. const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => {
  430. if (!filename || filename.startsWith('.') || !filename.endsWith('.html')) return;
  431. if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename));
  432. debounceTimers.set(filename, setTimeout(() => {
  433. debounceTimers.delete(filename);
  434. const filePath = path.join(CONTENT_DIR, filename);
  435. if (!fs.existsSync(filePath)) return; // file was deleted
  436. touchActivity();
  437. if (!knownFiles.has(filename)) {
  438. knownFiles.add(filename);
  439. const eventsFile = path.join(STATE_DIR, 'events');
  440. if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
  441. console.log(JSON.stringify({ type: 'screen-added', file: filePath }));
  442. maybeOpenBrowser();
  443. } else {
  444. console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));
  445. }
  446. broadcast({ type: 'reload' });
  447. }, 100));
  448. });
  449. watcher.on('error', (err) => console.error('fs.watch error:', err.message));
  450. function shutdown(reason) {
  451. console.log(JSON.stringify({ type: 'server-stopped', reason }));
  452. const infoFile = path.join(STATE_DIR, 'server-info');
  453. if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile);
  454. fs.writeFileSync(
  455. path.join(STATE_DIR, 'server-stopped'),
  456. JSON.stringify({ reason, timestamp: Date.now() }) + '\n'
  457. );
  458. watcher.close();
  459. clearInterval(lifecycleCheck);
  460. // Close any upgraded WebSocket sockets so server.close() can complete and
  461. // the process actually exits instead of lingering on an open connection.
  462. for (const socket of clients) {
  463. try { socket.destroy(); } catch (e) { /* already gone */ }
  464. }
  465. server.close(() => process.exit(0));
  466. }
  467. function ownerAlive() {
  468. if (!ownerPid) return true;
  469. try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
  470. }
  471. // Periodically exit if the owner process died or we've been idle too long.
  472. const lifecycleCheck = setInterval(() => {
  473. if (!ownerAlive()) shutdown('owner process exited');
  474. else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout');
  475. }, LIFECYCLE_CHECK_MS);
  476. lifecycleCheck.unref();
  477. // Validate owner PID at startup. If it's already dead, the PID resolution
  478. // was wrong (common on WSL, Tailscale SSH, and cross-user scenarios).
  479. // Disable monitoring and rely on the idle timeout instead.
  480. if (ownerPid) {
  481. try { process.kill(ownerPid, 0); }
  482. catch (e) {
  483. if (e.code !== 'EPERM') {
  484. console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' }));
  485. ownerPid = null;
  486. }
  487. }
  488. }
  489. // If the preferred port is already taken (e.g. a previous server is still
  490. // alive), fall back to a random port once instead of failing.
  491. let triedFallback = false;
  492. function onListen() {
  493. // Cookie name keys on the ACTUAL bound port (may differ from the preferred
  494. // one after an EADDRINUSE fallback) so it can't collide with another server's
  495. // cookie in the shared localhost jar.
  496. COOKIE_NAME = 'brainstorm-key-' + PORT;
  497. // Record the bound port AND token so the next restart of this session reuses
  498. // them — but ONLY when we got our preferred port. On a fallback we bound a
  499. // *different* port because someone else holds the preferred one; persisting
  500. // would overwrite the shared files and strand that other session's open tab.
  501. if (PORT_FILE && !triedFallback) {
  502. try { fs.writeFileSync(PORT_FILE, String(PORT)); } catch (e) { /* best effort */ }
  503. if (TOKEN_FILE) {
  504. try { fs.writeFileSync(TOKEN_FILE, TOKEN, { mode: 0o600 }); } catch (e) { /* best effort */ }
  505. }
  506. }
  507. const info = JSON.stringify({
  508. type: 'server-started', port: Number(PORT), host: HOST,
  509. url_host: URL_HOST, url: companionUrl(),
  510. screen_dir: CONTENT_DIR, state_dir: STATE_DIR, idle_timeout_ms: IDLE_TIMEOUT_MS
  511. });
  512. console.log(info);
  513. // server-info embeds the key — keep it owner-only.
  514. fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n', { mode: 0o600 });
  515. }
  516. server.on('error', (err) => {
  517. if (err.code === 'EADDRINUSE' && !triedFallback) {
  518. triedFallback = true;
  519. PORT = randomPort();
  520. server.listen(PORT, HOST, onListen);
  521. } else {
  522. console.error('Server failed to bind:', err.message);
  523. process.exit(1);
  524. }
  525. });
  526. server.listen(PORT, HOST, onListen);
  527. }
  528. if (require.main === module) {
  529. startServer();
  530. }
  531. module.exports = { computeAcceptKey, encodeFrame, decodeFrame, OPCODES, MAX_FRAME_PAYLOAD_BYTES };