lifecycle.test.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. /**
  2. * Tests for the brainstorm server's lifecycle (idle timeout + shutdown).
  3. *
  4. * - The idle timeout is configurable (default 4h) and reported in server-info.
  5. * - Idle shutdown must close any open WebSocket so the process actually exits,
  6. * not hang on a lingering connection.
  7. * - start-server.sh exposes the timeout via --idle-timeout-minutes.
  8. *
  9. * Uses the `ws` npm package as a test client (test-only dependency).
  10. */
  11. const { spawn, execFileSync } = require('child_process');
  12. const WebSocket = require('ws');
  13. const fs = require('fs');
  14. const path = require('path');
  15. const assert = require('assert');
  16. const SERVER = path.join(__dirname, '../../skills/brainstorming/scripts/server.cjs');
  17. const START = path.join(__dirname, '../../skills/brainstorming/scripts/start-server.sh');
  18. const STOP = path.join(__dirname, '../../skills/brainstorming/scripts/stop-server.sh');
  19. const sleep = ms => new Promise(r => setTimeout(r, ms));
  20. function waitForExit(child, timeoutMs = 2000) {
  21. if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
  22. return new Promise(resolve => {
  23. let settled = false;
  24. const finish = (exited) => {
  25. if (settled) return;
  26. settled = true;
  27. resolve(exited);
  28. };
  29. child.once('exit', () => finish(true));
  30. setTimeout(() => finish(false), timeoutMs);
  31. });
  32. }
  33. async function killAndWait(child, timeoutMs = 2000) {
  34. if (!child || child.exitCode !== null || child.signalCode !== null) return true;
  35. const exited = waitForExit(child, timeoutMs);
  36. child.kill();
  37. if (await exited) return true;
  38. child.kill('SIGKILL');
  39. return waitForExit(child, 500);
  40. }
  41. async function waitForFile(file, timeoutMs = 3000) {
  42. const deadline = Date.now() + timeoutMs;
  43. while (Date.now() < deadline) {
  44. if (fs.existsSync(file)) return true;
  45. await sleep(50);
  46. }
  47. return fs.existsSync(file);
  48. }
  49. function firstServerStarted(out) {
  50. return JSON.parse(out.trim().split('\n').find(l => l.includes('server-started')));
  51. }
  52. function openCaptureCommand(dir, marker) {
  53. const scriptPath = path.resolve(dir, 'capture-open.cjs');
  54. const markerPath = path.resolve(marker);
  55. fs.writeFileSync(scriptPath,
  56. "const fs = require('fs');\n" +
  57. "fs.appendFileSync(process.argv[2], process.argv[3] + '\\n');\n");
  58. return `node ${JSON.stringify(scriptPath)} ${JSON.stringify(markerPath)}`;
  59. }
  60. async function runTests() {
  61. let passed = 0, failed = 0;
  62. async function test(name, fn) {
  63. try { await fn(); console.log(` PASS: ${name}`); passed++; }
  64. catch (e) { console.log(` FAIL: ${name}`); console.log(` ${e.message}`); failed++; }
  65. }
  66. await test('server-info reports the configured idle_timeout_ms', async () => {
  67. const dir = fs.mkdtempSync('/tmp/bs-life-');
  68. const srv = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_PORT: 3401, BRAINSTORM_DIR: dir, BRAINSTORM_IDLE_TIMEOUT_MS: 1234567 } });
  69. let out = ''; srv.stdout.on('data', d => out += d.toString());
  70. for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
  71. try {
  72. const info = firstServerStarted(out);
  73. assert.strictEqual(info.idle_timeout_ms, 1234567, 'idle_timeout_ms should reflect the env override');
  74. } finally {
  75. await killAndWait(srv);
  76. fs.rmSync(dir, { recursive: true, force: true });
  77. }
  78. });
  79. await test('idle shutdown closes an open WebSocket and the process exits', async () => {
  80. const dir = fs.mkdtempSync('/tmp/bs-life-');
  81. const srv = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_PORT: 3402, BRAINSTORM_DIR: dir, BRAINSTORM_TOKEN: 'lifetoken', BRAINSTORM_IDLE_TIMEOUT_MS: 200, BRAINSTORM_LIFECYCLE_CHECK_MS: 100 } });
  82. let out = ''; srv.stdout.on('data', d => out += d.toString());
  83. let exited = false, code = null; srv.on('exit', c => { exited = true; code = c; });
  84. for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
  85. const ws = new WebSocket('ws://localhost:3402/?key=lifetoken');
  86. await new Promise((res, rej) => { ws.on('open', res); ws.on('error', rej); });
  87. // 200ms idle, checked every 100ms — should shut down and exit well within 4s,
  88. // *despite* the open WS, only if shutdown() closes client sockets.
  89. for (let i = 0; i < 40 && !exited; i++) await sleep(100);
  90. try {
  91. assert(exited, 'process must exit after idle shutdown even with an open WebSocket');
  92. assert.strictEqual(code, 0, 'should exit cleanly (0)');
  93. assert(fs.existsSync(path.join(dir, 'state', 'server-stopped')), 'should write server-stopped');
  94. } finally {
  95. try { ws.close(); } catch (e) {}
  96. if (!exited) await killAndWait(srv);
  97. fs.rmSync(dir, { recursive: true, force: true });
  98. }
  99. });
  100. await test('start-server.sh --idle-timeout-minutes sets the timeout', async () => {
  101. const dir = fs.mkdtempSync('/tmp/bs-life-');
  102. let info;
  103. const out = execFileSync('bash', [START, '--project-dir', dir, '--idle-timeout-minutes', '5', '--background'], { encoding: 'utf8' });
  104. info = firstServerStarted(out);
  105. try {
  106. assert.strictEqual(info.idle_timeout_ms, 5 * 60 * 1000, '5 minutes -> 300000 ms');
  107. } finally {
  108. execFileSync('bash', [STOP, path.dirname(info.state_dir)], { stdio: 'ignore' });
  109. fs.rmSync(dir, { recursive: true, force: true });
  110. }
  111. });
  112. await test('server-started URL brackets IPv6 URL hosts', async () => {
  113. const dir = fs.mkdtempSync('/tmp/bs-ipv6-url-');
  114. const srv = spawn('node', [SERVER], {
  115. env: {
  116. ...process.env,
  117. BRAINSTORM_PORT: 3421,
  118. BRAINSTORM_HOST: '127.0.0.1',
  119. BRAINSTORM_URL_HOST: '::1',
  120. BRAINSTORM_TOKEN: 'ipv6token',
  121. BRAINSTORM_DIR: dir,
  122. BRAINSTORM_LIFECYCLE_CHECK_MS: 100000
  123. }
  124. });
  125. let out = ''; srv.stdout.on('data', d => out += d.toString());
  126. try {
  127. for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
  128. const info = firstServerStarted(out);
  129. assert.strictEqual(info.url, 'http://[::1]:3421/?key=ipv6token');
  130. } finally {
  131. await killAndWait(srv);
  132. fs.rmSync(dir, { recursive: true, force: true });
  133. }
  134. });
  135. await test('persists the bound port AND key, and restores both on restart', async () => {
  136. const dir = fs.mkdtempSync('/tmp/bs-port-');
  137. const portFile = path.join(dir, '.last-port');
  138. const tokenFile = path.join(dir, '.last-token');
  139. const env = { ...process.env, BRAINSTORM_PORT_FILE: portFile, BRAINSTORM_TOKEN_FILE: tokenFile, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 };
  140. const a = spawn('node', [SERVER], { env: { ...env, BRAINSTORM_DIR: path.join(dir, 's1') } });
  141. let outA = ''; a.stdout.on('data', d => outA += d.toString());
  142. for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);
  143. const infoA = firstServerStarted(outA);
  144. const keyA = new URL(infoA.url).searchParams.get('key');
  145. assert(fs.existsSync(portFile) && fs.existsSync(tokenFile), 'should write the port and token files');
  146. const exitedA = waitForExit(a);
  147. a.kill();
  148. assert(await exitedA, 'first server should exit before restart binds its port');
  149. const b = spawn('node', [SERVER], { env: { ...env, BRAINSTORM_DIR: path.join(dir, 's2') } });
  150. let outB = ''; b.stdout.on('data', d => outB += d.toString());
  151. for (let i = 0; i < 60 && !outB.includes('server-started'); i++) await sleep(50);
  152. const infoB = firstServerStarted(outB);
  153. const keyB = new URL(infoB.url).searchParams.get('key');
  154. await killAndWait(b);
  155. fs.rmSync(dir, { recursive: true, force: true });
  156. assert.strictEqual(infoB.port, infoA.port, 'restart should reuse the same port');
  157. // Same key too — otherwise the open tab's cookie would 403 against the restart.
  158. assert.strictEqual(keyB, keyA, 'restart should reuse the same session key');
  159. });
  160. await test('stored key can authenticate WebSocket after same-port restart', async () => {
  161. const dir = fs.mkdtempSync('/tmp/bs-reconnect-');
  162. const portFile = path.join(dir, '.last-port');
  163. const tokenFile = path.join(dir, '.last-token');
  164. const env = { ...process.env, BRAINSTORM_PORT_FILE: portFile, BRAINSTORM_TOKEN_FILE: tokenFile, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 };
  165. let a = null, b = null, ws = null;
  166. try {
  167. a = spawn('node', [SERVER], { env: { ...env, BRAINSTORM_DIR: path.join(dir, 's1') } });
  168. let outA = ''; a.stdout.on('data', d => outA += d.toString());
  169. for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);
  170. const infoA = firstServerStarted(outA);
  171. const keyA = new URL(infoA.url).searchParams.get('key');
  172. const exitedA = waitForExit(a);
  173. a.kill();
  174. assert(await exitedA, 'first server should exit before restart binds its port');
  175. a = null;
  176. b = spawn('node', [SERVER], { env: { ...env, BRAINSTORM_DIR: path.join(dir, 's2') } });
  177. let outB = ''; b.stdout.on('data', d => outB += d.toString());
  178. for (let i = 0; i < 60 && !outB.includes('server-started'); i++) await sleep(50);
  179. const infoB = firstServerStarted(outB);
  180. ws = new WebSocket(`ws://localhost:${infoB.port}/?key=${keyA}`, {
  181. headers: { Origin: `http://localhost:${infoB.port}` }
  182. });
  183. const opened = await new Promise(resolve => {
  184. ws.on('open', () => resolve(true));
  185. ws.on('error', () => resolve(false));
  186. setTimeout(() => resolve(false), 1500);
  187. });
  188. assert.strictEqual(infoB.port, infoA.port, 'restart should reuse same port');
  189. assert(opened, 'stored key should authenticate WS after restart');
  190. } finally {
  191. try { if (ws) ws.close(); } catch (e) {}
  192. await killAndWait(a);
  193. await killAndWait(b);
  194. fs.rmSync(dir, { recursive: true, force: true });
  195. }
  196. });
  197. await test('falls back to a random port when the preferred port is taken', async () => {
  198. const dir = fs.mkdtempSync('/tmp/bs-port-');
  199. const portFile = path.join(dir, '.last-port');
  200. const a = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_DIR: path.join(dir, 'a'), BRAINSTORM_PORT: 3415, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 } });
  201. let outA = ''; a.stdout.on('data', d => outA += d.toString());
  202. for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);
  203. fs.writeFileSync(portFile, '3415'); // preferred port, but it's taken by A
  204. const b = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_DIR: path.join(dir, 'b'), BRAINSTORM_PORT_FILE: portFile, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 } });
  205. let outB = ''; b.stdout.on('data', d => outB += d.toString());
  206. for (let i = 0; i < 60 && !outB.includes('server-started'); i++) await sleep(50);
  207. const portB = firstServerStarted(outB).port;
  208. const persisted = fs.readFileSync(portFile, 'utf8').trim();
  209. await killAndWait(a);
  210. await killAndWait(b);
  211. fs.rmSync(dir, { recursive: true, force: true });
  212. assert.notStrictEqual(portB, 3415, 'must not bind the already-taken port');
  213. assert(portB >= 49152, 'should fall back to a random high port');
  214. // The fallback must NOT clobber the shared port file — A still owns 3415 and
  215. // its open tab must keep reconnecting there.
  216. assert.strictEqual(persisted, '3415', 'fallback must not overwrite .last-port');
  217. });
  218. await test('auto-opens the browser once, on the first screen', async () => {
  219. const dir = fs.mkdtempSync('/tmp/bs-open-');
  220. const marker = path.join(dir, 'opened.log');
  221. const openCmd = openCaptureCommand(dir, marker); // capture the launch instead of opening a browser
  222. const srv = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_PORT: 3417, BRAINSTORM_DIR: dir, BRAINSTORM_OPEN: '1', BRAINSTORM_OPEN_CMD: openCmd, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 } });
  223. let out = ''; srv.stdout.on('data', d => out += d.toString());
  224. for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
  225. // First screen, with no browser connected -> should auto-open.
  226. fs.writeFileSync(path.join(dir, 'content', 'first.html'), '<h2>First</h2>');
  227. await waitForFile(marker);
  228. // Second screen -> must NOT open again.
  229. fs.writeFileSync(path.join(dir, 'content', 'second.html'), '<h2>Second</h2>');
  230. await sleep(700);
  231. const lines = fs.existsSync(marker) ? fs.readFileSync(marker, 'utf8').trim().split('\n').filter(Boolean) : [];
  232. // The opened URL must carry the key AND be reachable — a keyless URL hits 403.
  233. let status = 0;
  234. if (lines[0]) {
  235. status = await new Promise(r => require('http').get(lines[0], res => { res.resume(); r(res.statusCode); }).on('error', () => r(0)));
  236. }
  237. await killAndWait(srv);
  238. fs.rmSync(dir, { recursive: true, force: true });
  239. assert.strictEqual(lines.length, 1, 'should open exactly once');
  240. assert(lines[0].includes('3417'), `should open the server URL, got: ${lines[0]}`);
  241. assert(/[?&]key=/.test(lines[0]), `opened URL must carry the session key, got: ${lines[0]}`);
  242. assert.strictEqual(status, 200, 'the opened URL must be reachable (valid key), not the 403 page');
  243. });
  244. await test('does NOT auto-open unless approved (BRAINSTORM_OPEN unset)', async () => {
  245. const dir = fs.mkdtempSync('/tmp/bs-open-');
  246. const marker = path.join(dir, 'opened.log');
  247. const openCmd = openCaptureCommand(dir, marker);
  248. // BRAINSTORM_OPEN intentionally NOT set — auto-open must stay off.
  249. const srv = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_PORT: 3418, BRAINSTORM_DIR: dir, BRAINSTORM_OPEN_CMD: openCmd, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 } });
  250. let out = ''; srv.stdout.on('data', d => out += d.toString());
  251. for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
  252. fs.writeFileSync(path.join(dir, 'content', 'first.html'), '<h2>First</h2>');
  253. await sleep(700);
  254. await killAndWait(srv);
  255. const opened = fs.existsSync(marker);
  256. fs.rmSync(dir, { recursive: true, force: true });
  257. assert(!opened, 'must not open the browser without explicit approval');
  258. });
  259. await test('unauthenticated requests do not defeat the idle timeout', async () => {
  260. const dir = fs.mkdtempSync('/tmp/bs-life-');
  261. const srv = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_PORT: 3419, BRAINSTORM_DIR: dir, BRAINSTORM_TOKEN: 'authtok', BRAINSTORM_IDLE_TIMEOUT_MS: 400, BRAINSTORM_LIFECYCLE_CHECK_MS: 100 } });
  262. let out = ''; srv.stdout.on('data', d => out += d.toString());
  263. let exited = false; srv.on('exit', () => { exited = true; });
  264. for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
  265. // Flood with UNAUTHENTICATED (keyless → 403) requests. These must NOT count
  266. // as activity, so the idle timeout still fires and the process exits.
  267. const hammer = setInterval(() => { require('http').get('http://localhost:3419/', r => r.resume()).on('error', () => {}); }, 60);
  268. for (let i = 0; i < 40 && !exited; i++) await sleep(100);
  269. clearInterval(hammer);
  270. if (!exited) await killAndWait(srv);
  271. fs.rmSync(dir, { recursive: true, force: true });
  272. assert(exited, 'idle shutdown must still fire despite a flood of unauthenticated requests');
  273. });
  274. console.log(`\n--- Results: ${passed} passed, ${failed} failed ---`);
  275. if (failed > 0) process.exit(1);
  276. }
  277. runTests().catch(err => { console.error('Test failed:', err); process.exit(1); });