lifecycle.test.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. function httpStatus(port, key) {
  61. return new Promise(resolve => {
  62. const pathWithKey = key ? '/?key=' + encodeURIComponent(key) : '/';
  63. require('http')
  64. .get({ hostname: '127.0.0.1', port, path: pathWithKey }, res => {
  65. res.resume();
  66. resolve(res.statusCode);
  67. })
  68. .on('error', () => resolve(0));
  69. });
  70. }
  71. async function runTests() {
  72. let passed = 0, failed = 0;
  73. async function test(name, fn) {
  74. try { await fn(); console.log(` PASS: ${name}`); passed++; }
  75. catch (e) { console.log(` FAIL: ${name}`); console.log(` ${e.message}`); failed++; }
  76. }
  77. await test('server-info reports the configured idle_timeout_ms', async () => {
  78. const dir = fs.mkdtempSync('/tmp/bs-life-');
  79. const srv = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_PORT: 3401, BRAINSTORM_DIR: dir, BRAINSTORM_IDLE_TIMEOUT_MS: 1234567 } });
  80. let out = ''; srv.stdout.on('data', d => out += d.toString());
  81. for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
  82. try {
  83. const info = firstServerStarted(out);
  84. assert.strictEqual(info.idle_timeout_ms, 1234567, 'idle_timeout_ms should reflect the env override');
  85. } finally {
  86. await killAndWait(srv);
  87. fs.rmSync(dir, { recursive: true, force: true });
  88. }
  89. });
  90. await test('idle shutdown closes an open WebSocket and the process exits', async () => {
  91. const dir = fs.mkdtempSync('/tmp/bs-life-');
  92. 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 } });
  93. let out = ''; srv.stdout.on('data', d => out += d.toString());
  94. let exited = false, code = null; srv.on('exit', c => { exited = true; code = c; });
  95. for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
  96. const ws = new WebSocket('ws://localhost:3402/?key=lifetoken');
  97. await new Promise((res, rej) => { ws.on('open', res); ws.on('error', rej); });
  98. // 200ms idle, checked every 100ms — should shut down and exit well within 4s,
  99. // *despite* the open WS, only if shutdown() closes client sockets.
  100. for (let i = 0; i < 40 && !exited; i++) await sleep(100);
  101. try {
  102. assert(exited, 'process must exit after idle shutdown even with an open WebSocket');
  103. assert.strictEqual(code, 0, 'should exit cleanly (0)');
  104. assert(fs.existsSync(path.join(dir, 'state', 'server-stopped')), 'should write server-stopped');
  105. } finally {
  106. try { ws.close(); } catch (e) {}
  107. if (!exited) await killAndWait(srv);
  108. fs.rmSync(dir, { recursive: true, force: true });
  109. }
  110. });
  111. await test('start-server.sh --idle-timeout-minutes sets the timeout', async () => {
  112. const dir = fs.mkdtempSync('/tmp/bs-life-');
  113. let info;
  114. const out = execFileSync('bash', [START, '--project-dir', dir, '--idle-timeout-minutes', '5', '--background'], { encoding: 'utf8' });
  115. info = firstServerStarted(out);
  116. try {
  117. assert.strictEqual(info.idle_timeout_ms, 5 * 60 * 1000, '5 minutes -> 300000 ms');
  118. } finally {
  119. execFileSync('bash', [STOP, path.dirname(info.state_dir)], { stdio: 'ignore' });
  120. fs.rmSync(dir, { recursive: true, force: true });
  121. }
  122. });
  123. await test('server-started URL brackets IPv6 URL hosts', async () => {
  124. const dir = fs.mkdtempSync('/tmp/bs-ipv6-url-');
  125. const srv = spawn('node', [SERVER], {
  126. env: {
  127. ...process.env,
  128. BRAINSTORM_PORT: 3421,
  129. BRAINSTORM_HOST: '127.0.0.1',
  130. BRAINSTORM_URL_HOST: '::1',
  131. BRAINSTORM_TOKEN: 'ipv6token',
  132. BRAINSTORM_DIR: dir,
  133. BRAINSTORM_LIFECYCLE_CHECK_MS: 100000
  134. }
  135. });
  136. let out = ''; srv.stdout.on('data', d => out += d.toString());
  137. try {
  138. for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
  139. const info = firstServerStarted(out);
  140. assert.strictEqual(info.url, 'http://[::1]:3421/?key=ipv6token');
  141. } finally {
  142. await killAndWait(srv);
  143. fs.rmSync(dir, { recursive: true, force: true });
  144. }
  145. });
  146. await test('persists the bound port AND key, and restores both on restart', async () => {
  147. const dir = fs.mkdtempSync('/tmp/bs-port-');
  148. const portFile = path.join(dir, '.last-port');
  149. const tokenFile = path.join(dir, '.last-token');
  150. const env = { ...process.env, BRAINSTORM_PORT_FILE: portFile, BRAINSTORM_TOKEN_FILE: tokenFile, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 };
  151. const a = spawn('node', [SERVER], { env: { ...env, BRAINSTORM_DIR: path.join(dir, 's1') } });
  152. let outA = ''; a.stdout.on('data', d => outA += d.toString());
  153. for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);
  154. const infoA = firstServerStarted(outA);
  155. const keyA = new URL(infoA.url).searchParams.get('key');
  156. assert(fs.existsSync(portFile) && fs.existsSync(tokenFile), 'should write the port and token files');
  157. const exitedA = waitForExit(a);
  158. a.kill();
  159. assert(await exitedA, 'first server should exit before restart binds its port');
  160. const b = spawn('node', [SERVER], { env: { ...env, BRAINSTORM_DIR: path.join(dir, 's2') } });
  161. let outB = ''; b.stdout.on('data', d => outB += d.toString());
  162. for (let i = 0; i < 60 && !outB.includes('server-started'); i++) await sleep(50);
  163. const infoB = firstServerStarted(outB);
  164. const keyB = new URL(infoB.url).searchParams.get('key');
  165. await killAndWait(b);
  166. fs.rmSync(dir, { recursive: true, force: true });
  167. assert.strictEqual(infoB.port, infoA.port, 'restart should reuse the same port');
  168. // Same key too — otherwise the open tab's cookie would 403 against the restart.
  169. assert.strictEqual(keyB, keyA, 'restart should reuse the same session key');
  170. });
  171. await test('stored key can authenticate WebSocket after same-port restart', async () => {
  172. const dir = fs.mkdtempSync('/tmp/bs-reconnect-');
  173. const portFile = path.join(dir, '.last-port');
  174. const tokenFile = path.join(dir, '.last-token');
  175. const env = { ...process.env, BRAINSTORM_PORT_FILE: portFile, BRAINSTORM_TOKEN_FILE: tokenFile, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 };
  176. let a = null, b = null, ws = null;
  177. try {
  178. a = spawn('node', [SERVER], { env: { ...env, BRAINSTORM_DIR: path.join(dir, 's1') } });
  179. let outA = ''; a.stdout.on('data', d => outA += d.toString());
  180. for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);
  181. const infoA = firstServerStarted(outA);
  182. const keyA = new URL(infoA.url).searchParams.get('key');
  183. const exitedA = waitForExit(a);
  184. a.kill();
  185. assert(await exitedA, 'first server should exit before restart binds its port');
  186. a = null;
  187. b = spawn('node', [SERVER], { env: { ...env, BRAINSTORM_DIR: path.join(dir, 's2') } });
  188. let outB = ''; b.stdout.on('data', d => outB += d.toString());
  189. for (let i = 0; i < 60 && !outB.includes('server-started'); i++) await sleep(50);
  190. const infoB = firstServerStarted(outB);
  191. ws = new WebSocket(`ws://localhost:${infoB.port}/?key=${keyA}`, {
  192. headers: { Origin: `http://localhost:${infoB.port}` }
  193. });
  194. const opened = await new Promise(resolve => {
  195. ws.on('open', () => resolve(true));
  196. ws.on('error', () => resolve(false));
  197. setTimeout(() => resolve(false), 1500);
  198. });
  199. assert.strictEqual(infoB.port, infoA.port, 'restart should reuse same port');
  200. assert(opened, 'stored key should authenticate WS after restart');
  201. } finally {
  202. try { if (ws) ws.close(); } catch (e) {}
  203. await killAndWait(a);
  204. await killAndWait(b);
  205. fs.rmSync(dir, { recursive: true, force: true });
  206. }
  207. });
  208. await test('falls back to a random port when the preferred port is taken', async () => {
  209. const dir = fs.mkdtempSync('/tmp/bs-port-');
  210. const portFile = path.join(dir, '.last-port');
  211. const a = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_DIR: path.join(dir, 'a'), BRAINSTORM_PORT: 3415, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 } });
  212. let outA = ''; a.stdout.on('data', d => outA += d.toString());
  213. for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);
  214. fs.writeFileSync(portFile, '3415'); // preferred port, but it's taken by A
  215. const b = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_DIR: path.join(dir, 'b'), BRAINSTORM_PORT_FILE: portFile, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 } });
  216. let outB = ''; b.stdout.on('data', d => outB += d.toString());
  217. for (let i = 0; i < 60 && !outB.includes('server-started'); i++) await sleep(50);
  218. const portB = firstServerStarted(outB).port;
  219. const persisted = fs.readFileSync(portFile, 'utf8').trim();
  220. await killAndWait(a);
  221. await killAndWait(b);
  222. fs.rmSync(dir, { recursive: true, force: true });
  223. assert.notStrictEqual(portB, 3415, 'must not bind the already-taken port');
  224. assert(portB >= 49152, 'should fall back to a random high port');
  225. // The fallback must NOT clobber the shared port file — A still owns 3415 and
  226. // its open tab must keep reconnecting there.
  227. assert.strictEqual(persisted, '3415', 'fallback must not overwrite .last-port');
  228. });
  229. await test('fallback with persisted token generates a fresh unpersisted key', async () => {
  230. const dir = fs.mkdtempSync('/tmp/bs-port-');
  231. const portFile = path.join(dir, '.last-port');
  232. const tokenFile = path.join(dir, '.last-token');
  233. const preferredToken = 'abababababababababababababababab';
  234. let a = null, b = null;
  235. try {
  236. a = spawn('node', [SERVER], {
  237. env: {
  238. ...process.env,
  239. BRAINSTORM_DIR: path.join(dir, 'a'),
  240. BRAINSTORM_PORT: 3422,
  241. BRAINSTORM_TOKEN: preferredToken,
  242. BRAINSTORM_LIFECYCLE_CHECK_MS: 100000
  243. }
  244. });
  245. let outA = ''; a.stdout.on('data', d => outA += d.toString());
  246. for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);
  247. assert(outA.includes('server-started'), 'preferred-port server should start');
  248. fs.writeFileSync(portFile, '3422');
  249. fs.writeFileSync(tokenFile, preferredToken, { mode: 0o600 });
  250. b = spawn('node', [SERVER], {
  251. env: {
  252. ...process.env,
  253. BRAINSTORM_DIR: path.join(dir, 'b'),
  254. BRAINSTORM_PORT_FILE: portFile,
  255. BRAINSTORM_TOKEN_FILE: tokenFile,
  256. BRAINSTORM_LIFECYCLE_CHECK_MS: 100000
  257. }
  258. });
  259. let outB = ''; b.stdout.on('data', d => outB += d.toString());
  260. for (let i = 0; i < 60 && !outB.includes('server-started'); i++) await sleep(50);
  261. const infoB = firstServerStarted(outB);
  262. const fallbackKey = new URL(infoB.url).searchParams.get('key');
  263. const persistedAfter = fs.readFileSync(tokenFile, 'utf8').trim();
  264. const originalStatus = await httpStatus(3422, fallbackKey);
  265. assert.notStrictEqual(infoB.port, 3422, 'fallback should use a different port');
  266. assert.notStrictEqual(fallbackKey, preferredToken, 'fallback must not reuse persisted key');
  267. assert.strictEqual(persistedAfter, preferredToken, 'fallback must not overwrite .last-token');
  268. assert.strictEqual(originalStatus, 403, 'fallback key must not authenticate to original server');
  269. } finally {
  270. await killAndWait(a);
  271. await killAndWait(b);
  272. fs.rmSync(dir, { recursive: true, force: true });
  273. }
  274. });
  275. await test('fallback with explicit BRAINSTORM_TOKEN fails closed', async () => {
  276. const dir = fs.mkdtempSync('/tmp/bs-port-');
  277. const portFile = path.join(dir, '.last-port');
  278. const explicitToken = 'cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd';
  279. let a = null, b = null;
  280. try {
  281. a = spawn('node', [SERVER], {
  282. env: {
  283. ...process.env,
  284. BRAINSTORM_DIR: path.join(dir, 'a'),
  285. BRAINSTORM_PORT: 3423,
  286. BRAINSTORM_TOKEN: explicitToken,
  287. BRAINSTORM_LIFECYCLE_CHECK_MS: 100000
  288. }
  289. });
  290. let outA = ''; a.stdout.on('data', d => outA += d.toString());
  291. for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);
  292. assert(outA.includes('server-started'), 'preferred-port server should start');
  293. fs.writeFileSync(portFile, '3423');
  294. b = spawn('node', [SERVER], {
  295. env: {
  296. ...process.env,
  297. BRAINSTORM_DIR: path.join(dir, 'b'),
  298. BRAINSTORM_PORT_FILE: portFile,
  299. BRAINSTORM_TOKEN: explicitToken,
  300. BRAINSTORM_LIFECYCLE_CHECK_MS: 100000
  301. }
  302. });
  303. let outB = ''; let errB = '';
  304. b.stdout.on('data', d => outB += d.toString());
  305. b.stderr.on('data', d => errB += d.toString());
  306. for (let i = 0; i < 60 && !outB.includes('server-started') && b.exitCode === null; i++) await sleep(50);
  307. const exited = await waitForExit(b, 1500);
  308. assert(exited, 'explicit-token fallback process should exit');
  309. assert.notStrictEqual(b.exitCode, 0, 'explicit-token fallback should fail non-zero');
  310. assert(!outB.includes('server-started'), 'explicit-token fallback must not start on a random port');
  311. assert(/BRAINSTORM_TOKEN/.test(errB), `stderr should explain explicit token fallback refusal, got: ${errB}`);
  312. } finally {
  313. await killAndWait(a);
  314. await killAndWait(b);
  315. fs.rmSync(dir, { recursive: true, force: true });
  316. }
  317. });
  318. await test('auto-opens the browser once, on the first screen', async () => {
  319. const dir = fs.mkdtempSync('/tmp/bs-open-');
  320. const marker = path.join(dir, 'opened.log');
  321. const openCmd = openCaptureCommand(dir, marker); // capture the launch instead of opening a browser
  322. 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 } });
  323. let out = ''; srv.stdout.on('data', d => out += d.toString());
  324. for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
  325. // First screen, with no browser connected -> should auto-open.
  326. fs.writeFileSync(path.join(dir, 'content', 'first.html'), '<h2>First</h2>');
  327. await waitForFile(marker);
  328. // Second screen -> must NOT open again.
  329. fs.writeFileSync(path.join(dir, 'content', 'second.html'), '<h2>Second</h2>');
  330. await sleep(700);
  331. const lines = fs.existsSync(marker) ? fs.readFileSync(marker, 'utf8').trim().split('\n').filter(Boolean) : [];
  332. // The opened URL must carry the key AND be reachable — a keyless URL hits 403.
  333. let status = 0;
  334. if (lines[0]) {
  335. status = await new Promise(r => require('http').get(lines[0], res => { res.resume(); r(res.statusCode); }).on('error', () => r(0)));
  336. }
  337. await killAndWait(srv);
  338. fs.rmSync(dir, { recursive: true, force: true });
  339. assert.strictEqual(lines.length, 1, 'should open exactly once');
  340. assert(lines[0].includes('3417'), `should open the server URL, got: ${lines[0]}`);
  341. assert(/[?&]key=/.test(lines[0]), `opened URL must carry the session key, got: ${lines[0]}`);
  342. assert.strictEqual(status, 200, 'the opened URL must be reachable (valid key), not the 403 page');
  343. });
  344. await test('does NOT auto-open unless approved (BRAINSTORM_OPEN unset)', async () => {
  345. const dir = fs.mkdtempSync('/tmp/bs-open-');
  346. const marker = path.join(dir, 'opened.log');
  347. const openCmd = openCaptureCommand(dir, marker);
  348. // BRAINSTORM_OPEN intentionally NOT set — auto-open must stay off.
  349. const srv = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_PORT: 3418, BRAINSTORM_DIR: dir, BRAINSTORM_OPEN_CMD: openCmd, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 } });
  350. let out = ''; srv.stdout.on('data', d => out += d.toString());
  351. for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
  352. fs.writeFileSync(path.join(dir, 'content', 'first.html'), '<h2>First</h2>');
  353. await sleep(700);
  354. await killAndWait(srv);
  355. const opened = fs.existsSync(marker);
  356. fs.rmSync(dir, { recursive: true, force: true });
  357. assert(!opened, 'must not open the browser without explicit approval');
  358. });
  359. await test('unauthenticated requests do not defeat the idle timeout', async () => {
  360. const dir = fs.mkdtempSync('/tmp/bs-life-');
  361. 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 } });
  362. let out = ''; srv.stdout.on('data', d => out += d.toString());
  363. let exited = false; srv.on('exit', () => { exited = true; });
  364. for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
  365. // Flood with UNAUTHENTICATED (keyless → 403) requests. These must NOT count
  366. // as activity, so the idle timeout still fires and the process exits.
  367. const hammer = setInterval(() => { require('http').get('http://localhost:3419/', r => r.resume()).on('error', () => {}); }, 60);
  368. for (let i = 0; i < 40 && !exited; i++) await sleep(100);
  369. clearInterval(hammer);
  370. if (!exited) await killAndWait(srv);
  371. fs.rmSync(dir, { recursive: true, force: true });
  372. assert(exited, 'idle shutdown must still fire despite a flood of unauthenticated requests');
  373. });
  374. console.log(`\n--- Results: ${passed} passed, ${failed} failed ---`);
  375. if (failed > 0) process.exit(1);
  376. }
  377. runTests().catch(err => { console.error('Test failed:', err); process.exit(1); });