server.cjs 25 KB

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