@zfdx123/dsh-superpowers 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +27 -0
  2. package/LICENSE.superpowers +21 -0
  3. package/README.md +109 -0
  4. package/README.zh.md +109 -0
  5. package/cordis.patch.yml +16 -0
  6. package/index.js +395 -0
  7. package/package.json +68 -0
  8. package/skills/brainstorming/SKILL.md +250 -0
  9. package/skills/brainstorming/scripts/frame-template.html +213 -0
  10. package/skills/brainstorming/scripts/helper.js +179 -0
  11. package/skills/brainstorming/scripts/server.cjs +781 -0
  12. package/skills/brainstorming/scripts/start-server.sh +209 -0
  13. package/skills/brainstorming/scripts/stop-server.sh +120 -0
  14. package/skills/brainstorming/spec-document-reviewer-prompt.md +49 -0
  15. package/skills/brainstorming/visual-companion.md +299 -0
  16. package/skills/dispatching-parallel-agents/SKILL.md +167 -0
  17. package/skills/executing-plans/SKILL.md +64 -0
  18. package/skills/finishing-a-development-branch/SKILL.md +225 -0
  19. package/skills/receiving-code-review/SKILL.md +205 -0
  20. package/skills/requesting-code-review/SKILL.md +95 -0
  21. package/skills/requesting-code-review/code-reviewer.md +181 -0
  22. package/skills/subagent-driven-development/SKILL.md +568 -0
  23. package/skills/subagent-driven-development/implementer-prompt.md +154 -0
  24. package/skills/subagent-driven-development/re-review-prompt.md +115 -0
  25. package/skills/subagent-driven-development/scripts/review-package +46 -0
  26. package/skills/subagent-driven-development/scripts/sdd-workspace +40 -0
  27. package/skills/subagent-driven-development/scripts/task-brief +41 -0
  28. package/skills/subagent-driven-development/task-reviewer-prompt.md +207 -0
  29. package/skills/systematic-debugging/CREATION-LOG.md +119 -0
  30. package/skills/systematic-debugging/SKILL.md +283 -0
  31. package/skills/systematic-debugging/condition-based-waiting-example.ts +158 -0
  32. package/skills/systematic-debugging/condition-based-waiting.md +115 -0
  33. package/skills/systematic-debugging/defense-in-depth.md +122 -0
  34. package/skills/systematic-debugging/find-polluter.sh +72 -0
  35. package/skills/systematic-debugging/root-cause-tracing.md +169 -0
  36. package/skills/systematic-debugging/test-academic.md +14 -0
  37. package/skills/systematic-debugging/test-pressure-1.md +58 -0
  38. package/skills/systematic-debugging/test-pressure-2.md +68 -0
  39. package/skills/systematic-debugging/test-pressure-3.md +69 -0
  40. package/skills/test-driven-development/SKILL.md +320 -0
  41. package/skills/test-driven-development/writing-good-tests.md +198 -0
  42. package/skills/using-git-worktrees/SKILL.md +167 -0
  43. package/skills/using-superpowers/SKILL.md +63 -0
  44. package/skills/using-superpowers/references/antigravity-tools.md +23 -0
  45. package/skills/using-superpowers/references/codex-tools.md +108 -0
  46. package/skills/using-superpowers/references/gemini-tools.md +63 -0
  47. package/skills/using-superpowers/references/hermes-tools.md +56 -0
  48. package/skills/using-superpowers/references/pi-tools.md +16 -0
  49. package/skills/verification-before-completion/SKILL.md +120 -0
  50. package/skills/writing-plans/SKILL.md +171 -0
  51. package/skills/writing-plans/plan-document-reviewer-prompt.md +49 -0
  52. package/skills/writing-skills/SKILL.md +679 -0
  53. package/skills/writing-skills/anthropic-best-practices.md +1150 -0
  54. package/skills/writing-skills/examples/CLAUDE_MD_TESTING.md +189 -0
  55. package/skills/writing-skills/graphviz-conventions.dot +172 -0
  56. package/skills/writing-skills/persuasion-principles.md +187 -0
  57. package/skills/writing-skills/render-graphs.js +172 -0
  58. package/skills/writing-skills/testing-skills-with-subagents.md +384 -0
  59. package/test/index.test.js +332 -0
@@ -0,0 +1,781 @@
1
+ const crypto = require('crypto')
2
+ const http = require('http')
3
+ const fs = require('fs')
4
+ const path = require('path')
5
+
6
+ // ========== WebSocket Protocol (RFC 6455) ==========
7
+
8
+ const OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0a }
9
+ const WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
10
+ const MAX_FRAME_PAYLOAD_BYTES = 10 * 1024 * 1024
11
+
12
+ function computeAcceptKey(clientKey) {
13
+ return crypto
14
+ .createHash('sha1')
15
+ .update(clientKey + WS_MAGIC)
16
+ .digest('base64')
17
+ }
18
+
19
+ function encodeFrame(opcode, payload) {
20
+ const fin = 0x80
21
+ const len = payload.length
22
+ let header
23
+
24
+ if (len < 126) {
25
+ header = Buffer.alloc(2)
26
+ header[0] = fin | opcode
27
+ header[1] = len
28
+ } else if (len < 65536) {
29
+ header = Buffer.alloc(4)
30
+ header[0] = fin | opcode
31
+ header[1] = 126
32
+ header.writeUInt16BE(len, 2)
33
+ } else {
34
+ header = Buffer.alloc(10)
35
+ header[0] = fin | opcode
36
+ header[1] = 127
37
+ header.writeBigUInt64BE(BigInt(len), 2)
38
+ }
39
+
40
+ return Buffer.concat([header, payload])
41
+ }
42
+
43
+ function decodeFrame(buffer) {
44
+ if (buffer.length < 2) return null
45
+
46
+ const secondByte = buffer[1]
47
+ const opcode = buffer[0] & 0x0f
48
+ const masked = (secondByte & 0x80) !== 0
49
+ let payloadLen = secondByte & 0x7f
50
+ let offset = 2
51
+
52
+ if (!masked) throw new Error('Client frames must be masked')
53
+
54
+ if (payloadLen === 126) {
55
+ if (buffer.length < 4) return null
56
+ payloadLen = buffer.readUInt16BE(2)
57
+ offset = 4
58
+ } else if (payloadLen === 127) {
59
+ if (buffer.length < 10) return null
60
+ const extendedLen = buffer.readBigUInt64BE(2)
61
+ if (extendedLen > BigInt(MAX_FRAME_PAYLOAD_BYTES)) {
62
+ throw new Error('WebSocket frame payload exceeds maximum allowed size')
63
+ }
64
+ payloadLen = Number(extendedLen)
65
+ offset = 10
66
+ }
67
+
68
+ if (payloadLen > MAX_FRAME_PAYLOAD_BYTES) {
69
+ throw new Error('WebSocket frame payload exceeds maximum allowed size')
70
+ }
71
+
72
+ const maskOffset = offset
73
+ const dataOffset = offset + 4
74
+ const totalLen = dataOffset + payloadLen
75
+ if (buffer.length < totalLen) return null
76
+
77
+ const mask = buffer.slice(maskOffset, dataOffset)
78
+ const data = Buffer.alloc(payloadLen)
79
+ for (let i = 0; i < payloadLen; i++) {
80
+ data[i] = buffer[dataOffset + i] ^ mask[i % 4]
81
+ }
82
+
83
+ return { opcode, payload: data, bytesConsumed: totalLen }
84
+ }
85
+
86
+ // ========== Configuration ==========
87
+
88
+ const PORT_FILE = process.env.BRAINSTORM_PORT_FILE || null
89
+ const randomPort = () => 49152 + Math.floor(Math.random() * 16383)
90
+ // Prefer an explicit port, else the port this session last bound (so a restart
91
+ // reuses it and an already-open browser tab reconnects), else a random high port.
92
+ function preferredPort() {
93
+ if (process.env.BRAINSTORM_PORT) return Number(process.env.BRAINSTORM_PORT)
94
+ if (PORT_FILE) {
95
+ try {
96
+ const p = Number(fs.readFileSync(PORT_FILE, 'utf-8').trim())
97
+ if (Number.isInteger(p) && p > 1023 && p < 65536) return p
98
+ } catch (e) {
99
+ /* no prior port recorded */
100
+ }
101
+ }
102
+ return randomPort()
103
+ }
104
+ let PORT = preferredPort()
105
+ const HOST = process.env.BRAINSTORM_HOST || '127.0.0.1'
106
+ const URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST)
107
+ const SESSION_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm'
108
+ const CONTENT_DIR = path.join(SESSION_DIR, 'content')
109
+ const STATE_DIR = path.join(SESSION_DIR, 'state')
110
+ const SUPERPOWERS_VERSION = readSuperpowersVersion()
111
+ const SUPERPOWERS_BRAND_IMAGE_URL = 'https://primeradiant.com/brand/superpowers-visual-brainstorming-logo.png'
112
+ const TELEMETRY_DISABLE_ENV_VARS = [
113
+ 'SUPERPOWERS_DISABLE_TELEMETRY',
114
+ 'DISABLE_TELEMETRY',
115
+ 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC',
116
+ ]
117
+ const SUPERPOWERS_TELEMETRY_DISABLED = TELEMETRY_DISABLE_ENV_VARS.some((name) => isTruthyEnv(process.env[name]))
118
+ let ownerPid = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null
119
+
120
+ // Per-session secret key. The companion is reachable by any local browser tab
121
+ // and, when bound to a non-loopback host, by any host that can route to it.
122
+ // The key authenticates the real client uniformly across loopback, tunnel, and
123
+ // remote binds — and defeats DNS rebinding — where a Host/Origin allowlist
124
+ // cannot. It rides the served URL as ?key= and is mirrored into a cookie on
125
+ // first load so same-origin subresources and the WebSocket carry it for free.
126
+ // Persisted alongside the port (BRAINSTORM_TOKEN_FILE) so a restart keeps the
127
+ // same key and an already-open tab's cookie still validates.
128
+ const TOKEN_FILE = process.env.BRAINSTORM_TOKEN_FILE || null
129
+ function generateToken() {
130
+ return crypto.randomBytes(32).toString('hex')
131
+ }
132
+
133
+ function chmodOwnerOnly(file) {
134
+ try {
135
+ fs.chmodSync(file, 0o600)
136
+ } catch (e) {
137
+ /* best effort */
138
+ }
139
+ }
140
+
141
+ function initialToken() {
142
+ if (process.env.BRAINSTORM_TOKEN) {
143
+ return { value: process.env.BRAINSTORM_TOKEN, source: 'env' }
144
+ }
145
+ if (TOKEN_FILE) {
146
+ try {
147
+ const t = fs.readFileSync(TOKEN_FILE, 'utf-8').trim()
148
+ if (/^[0-9a-f]{32,}$/i.test(t)) {
149
+ chmodOwnerOnly(TOKEN_FILE)
150
+ return { value: t, source: 'file' }
151
+ }
152
+ } catch (e) {
153
+ /* no prior token recorded */
154
+ }
155
+ }
156
+ return { value: generateToken(), source: 'generated' }
157
+ }
158
+
159
+ const tokenInfo = initialToken()
160
+ let TOKEN = tokenInfo.value
161
+ let tokenSource = tokenInfo.source
162
+ let COOKIE_NAME = 'brainstorm-key-' + PORT // refined to the actual bound port in onListen
163
+
164
+ const MIME_TYPES = {
165
+ '.html': 'text/html',
166
+ '.css': 'text/css',
167
+ '.js': 'application/javascript',
168
+ '.json': 'application/json',
169
+ '.png': 'image/png',
170
+ '.jpg': 'image/jpeg',
171
+ '.jpeg': 'image/jpeg',
172
+ '.gif': 'image/gif',
173
+ '.svg': 'image/svg+xml',
174
+ }
175
+
176
+ // ========== Templates and Constants ==========
177
+
178
+ function waitingPage() {
179
+ return renderBranding(`<!DOCTYPE html>
180
+ <html>
181
+ <head><meta charset="utf-8"><title>Brainstorm Companion</title>
182
+ <style>
183
+ body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
184
+ h1 { color: #333; } p { color: #666; }
185
+ .brand { display: flex; align-items: center; min-width: 0; overflow: hidden; margin-bottom: 1.5rem; color: #666; font-size: 0.9rem; line-height: 1; }
186
+ .brand a { color: inherit; text-decoration: none; display: flex; align-items: center; gap: 0.5rem; min-width: 0; max-width: 100%; line-height: 1; }
187
+ .brand-copy { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1; transform: translateY(-1px); }
188
+ .brand-logo { display: block; height: 1em; width: auto; max-width: 180px; filter: invert(1); }
189
+ </style>
190
+ </head>
191
+ <body><!-- BRANDING --><h1>Brainstorm Companion</h1>
192
+ <p>Waiting for the agent to push a screen...</p></body></html>`)
193
+ }
194
+
195
+ const FORBIDDEN_PAGE = `<!DOCTYPE html>
196
+ <html>
197
+ <head><meta charset="utf-8"><title>Session key required</title>
198
+ <style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
199
+ h1 { color: #333; } p { color: #666; } code { background: #f0f0f0; padding: 0.1em 0.3em; border-radius: 4px; }</style>
200
+ </head>
201
+ <body><h1>Session key required</h1>
202
+ <p>This page needs the full URL your coding agent gave you, including the
203
+ <code>?key=&hellip;</code> part. Copy the complete URL and open it again.</p></body></html>`
204
+
205
+ function bootstrapPage(key) {
206
+ const jsonKey = JSON.stringify(String(key))
207
+ return `<!DOCTYPE html>
208
+ <html>
209
+ <head><meta charset="utf-8"><title>Opening Brainstorm Companion</title></head>
210
+ <body>
211
+ <script>
212
+ try { sessionStorage.setItem('brainstorm-session-key', ${jsonKey}); } catch (e) {}
213
+ location.replace('/');
214
+ </script>
215
+ </body>
216
+ </html>`
217
+ }
218
+
219
+ const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8')
220
+ const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8')
221
+ const helperInjection = '<script>\n' + helperScript + '\n</script>'
222
+
223
+ // ========== Helper Functions ==========
224
+
225
+ function readSuperpowersVersion() {
226
+ const root = path.join(__dirname, '../../..')
227
+ const manifests = [path.join(root, 'package.json'), path.join(root, '.codex-plugin/plugin.json')]
228
+
229
+ for (const manifest of manifests) {
230
+ try {
231
+ const data = JSON.parse(fs.readFileSync(manifest, 'utf-8'))
232
+ if (data.version) return String(data.version)
233
+ } catch (e) {
234
+ // Packaged Codex plugins omit package.json; try the next manifest.
235
+ }
236
+ }
237
+
238
+ return 'unknown'
239
+ }
240
+
241
+ function isTruthyEnv(value) {
242
+ if (!value) return false
243
+ const normalized = String(value).trim().toLowerCase()
244
+ if (!normalized) return false
245
+ return !['0', 'false', 'no', 'off'].includes(normalized)
246
+ }
247
+
248
+ function escapeHtmlText(value) {
249
+ return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
250
+ }
251
+
252
+ function brandMarkup() {
253
+ const version = escapeHtmlText(SUPERPOWERS_VERSION)
254
+ const text = SUPERPOWERS_TELEMETRY_DISABLED ? 'Prime Radiant Superpowers v' + version : 'Superpowers v' + version
255
+ const logo = SUPERPOWERS_TELEMETRY_DISABLED
256
+ ? ''
257
+ : '<img class="brand-logo" src="' +
258
+ SUPERPOWERS_BRAND_IMAGE_URL +
259
+ '?v=' +
260
+ encodeURIComponent(SUPERPOWERS_VERSION) +
261
+ '" alt="Prime Radiant" referrerpolicy="no-referrer" decoding="async">'
262
+
263
+ return (
264
+ '<div class="brand"><a href="https://github.com/obra/superpowers">' +
265
+ logo +
266
+ '<span class="brand-copy">' +
267
+ text +
268
+ '</span></a></div>'
269
+ )
270
+ }
271
+
272
+ function renderBranding(html) {
273
+ return html.split('<!-- BRANDING -->').join(brandMarkup())
274
+ }
275
+
276
+ function isFullDocument(html) {
277
+ const trimmed = html.trimStart().toLowerCase()
278
+ return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html')
279
+ }
280
+
281
+ function wrapInFrame(content) {
282
+ return renderBranding(frameTemplate).replace('<!-- CONTENT -->', content)
283
+ }
284
+
285
+ function getNewestScreen() {
286
+ const files = fs
287
+ .readdirSync(CONTENT_DIR)
288
+ .filter((f) => !f.startsWith('.') && f.endsWith('.html'))
289
+ .map((f) => {
290
+ const fp = path.join(CONTENT_DIR, f)
291
+ if (!isRegularFileInsideContentDir(fp)) return null
292
+ return { path: fp, mtime: fs.statSync(fp).mtime.getTime() }
293
+ })
294
+ .filter(Boolean)
295
+ .sort((a, b) => b.mtime - a.mtime)
296
+ return files.length > 0 ? files[0].path : null
297
+ }
298
+
299
+ function urlHostForHttp(host) {
300
+ const h = String(host)
301
+ if (h.startsWith('[') && h.endsWith(']')) return h
302
+ return h.includes(':') ? '[' + h + ']' : h
303
+ }
304
+
305
+ function companionUrl() {
306
+ return 'http://' + urlHostForHttp(URL_HOST) + ':' + PORT + '/?key=' + TOKEN
307
+ }
308
+
309
+ function browserLauncherForPlatform(
310
+ url,
311
+ { platform = process.platform, osRelease = require('os').release(), env = process.env } = {},
312
+ ) {
313
+ const isWSL = platform === 'linux' && /microsoft/i.test(osRelease)
314
+ if (platform === 'darwin') return { bin: 'open', args: [url] }
315
+ if (platform === 'win32' || isWSL) {
316
+ return { bin: 'rundll32.exe', args: ['url.dll,FileProtocolHandler', url] }
317
+ }
318
+ if (env.DISPLAY || env.WAYLAND_DISPLAY) return { bin: 'xdg-open', args: [url] }
319
+ return null
320
+ }
321
+
322
+ function isRegularFileInsideContentDir(filePath) {
323
+ let stat, realContentDir, realFilePath
324
+ try {
325
+ stat = fs.lstatSync(filePath)
326
+ if (stat.isSymbolicLink()) return false
327
+ if (!stat.isFile()) return false
328
+ if (stat.nlink !== 1) return false
329
+ realContentDir = fs.realpathSync(CONTENT_DIR)
330
+ realFilePath = fs.realpathSync(filePath)
331
+ } catch (e) {
332
+ return false
333
+ }
334
+ return realFilePath.startsWith(realContentDir + path.sep)
335
+ }
336
+
337
+ // ========== Authentication ==========
338
+
339
+ function timingSafeEqualStr(a, b) {
340
+ const ab = Buffer.from(String(a))
341
+ const bb = Buffer.from(String(b))
342
+ if (ab.length !== bb.length) return false
343
+ return crypto.timingSafeEqual(ab, bb)
344
+ }
345
+
346
+ function parseCookies(header) {
347
+ const out = {}
348
+ if (!header) return out
349
+ for (const part of header.split(';')) {
350
+ const eq = part.indexOf('=')
351
+ if (eq < 0) continue
352
+ out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim()
353
+ }
354
+ return out
355
+ }
356
+
357
+ // A request is authorized if it carries the session key as ?key= or as the
358
+ // session cookie. Both are compared in constant time.
359
+ function isAuthorized(req) {
360
+ const q = req.url.indexOf('?')
361
+ if (q >= 0) {
362
+ const params = new URLSearchParams(req.url.slice(q + 1))
363
+ if (params.has('key')) {
364
+ const key = params.get('key')
365
+ return Boolean(key && timingSafeEqualStr(key, TOKEN))
366
+ }
367
+ }
368
+ const cookie = parseCookies(req.headers['cookie'])[COOKIE_NAME]
369
+ if (cookie && timingSafeEqualStr(cookie, TOKEN)) return true
370
+ return false
371
+ }
372
+
373
+ function pathnameOf(url) {
374
+ const q = url.indexOf('?')
375
+ return q >= 0 ? url.slice(0, q) : url
376
+ }
377
+
378
+ function queryKey(url) {
379
+ const q = url.indexOf('?')
380
+ if (q < 0) return null
381
+ return new URLSearchParams(url.slice(q + 1)).get('key')
382
+ }
383
+
384
+ function securityHeaders(headers = {}) {
385
+ return {
386
+ 'Referrer-Policy': 'no-referrer',
387
+ 'Cache-Control': 'no-store',
388
+ 'X-Frame-Options': 'DENY',
389
+ 'Content-Security-Policy': "frame-ancestors 'none'",
390
+ 'Cross-Origin-Resource-Policy': 'same-origin',
391
+ ...headers,
392
+ }
393
+ }
394
+
395
+ function isAllowedWebSocketOrigin(req) {
396
+ const origin = req.headers.origin
397
+ if (!origin) return true
398
+ const host = req.headers.host
399
+ if (!host) return false
400
+ return origin === 'http://' + host
401
+ }
402
+
403
+ // ========== HTTP Request Handler ==========
404
+
405
+ function handleRequest(req, res) {
406
+ if (!isAuthorized(req)) {
407
+ res.writeHead(403, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }))
408
+ res.end(FORBIDDEN_PAGE)
409
+ return
410
+ }
411
+ touchActivity() // only authorized requests count as activity
412
+
413
+ // Mirror the key into a cookie so same-origin subresources (/files/*) can
414
+ // authenticate after bootstrap. HttpOnly keeps it away from page scripts; the
415
+ // WebSocket Origin check below is what blocks cross-origin localhost injection.
416
+ res.setHeader('Set-Cookie', COOKIE_NAME + '=' + TOKEN + '; HttpOnly; SameSite=Strict; Path=/')
417
+
418
+ const pathname = pathnameOf(req.url)
419
+ const keyFromQuery = queryKey(req.url)
420
+ if (req.method === 'GET' && pathname === '/' && keyFromQuery && timingSafeEqualStr(keyFromQuery, TOKEN)) {
421
+ res.writeHead(200, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }))
422
+ res.end(bootstrapPage(keyFromQuery))
423
+ } else if (req.method === 'GET' && pathname === '/') {
424
+ const screenFile = getNewestScreen()
425
+ let html = screenFile
426
+ ? ((raw) => (isFullDocument(raw) ? raw : wrapInFrame(raw)))(fs.readFileSync(screenFile, 'utf-8'))
427
+ : waitingPage()
428
+
429
+ if (html.includes('</body>')) {
430
+ html = html.replace('</body>', helperInjection + '\n</body>')
431
+ } else {
432
+ html += helperInjection
433
+ }
434
+
435
+ res.writeHead(200, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }))
436
+ res.end(html)
437
+ } else if (req.method === 'GET' && pathname.startsWith('/files/')) {
438
+ const fileName = path.basename(pathname.slice(7))
439
+ const filePath = path.join(CONTENT_DIR, fileName)
440
+ // Reject empty/dotfile names and anything that isn't a regular file —
441
+ // `/files/` would otherwise resolve to CONTENT_DIR and crash readFileSync (EISDIR).
442
+ if (!fileName || fileName.startsWith('.') || !isRegularFileInsideContentDir(filePath)) {
443
+ res.writeHead(404, securityHeaders())
444
+ res.end('Not found')
445
+ return
446
+ }
447
+ const ext = path.extname(filePath).toLowerCase()
448
+ const contentType = MIME_TYPES[ext] || 'application/octet-stream'
449
+ res.writeHead(200, securityHeaders({ 'Content-Type': contentType }))
450
+ res.end(fs.readFileSync(filePath))
451
+ } else {
452
+ res.writeHead(404, securityHeaders())
453
+ res.end('Not found')
454
+ }
455
+ }
456
+
457
+ // ========== WebSocket Connection Handling ==========
458
+
459
+ const clients = new Set()
460
+
461
+ function handleUpgrade(req, socket) {
462
+ if (!isAuthorized(req) || !isAllowedWebSocketOrigin(req)) {
463
+ socket.destroy()
464
+ return
465
+ }
466
+
467
+ const key = req.headers['sec-websocket-key']
468
+ if (!key) {
469
+ socket.destroy()
470
+ return
471
+ }
472
+
473
+ const accept = computeAcceptKey(key)
474
+ socket.write(
475
+ 'HTTP/1.1 101 Switching Protocols\r\n' +
476
+ 'Upgrade: websocket\r\n' +
477
+ 'Connection: Upgrade\r\n' +
478
+ 'Sec-WebSocket-Accept: ' +
479
+ accept +
480
+ '\r\n\r\n',
481
+ )
482
+
483
+ let buffer = Buffer.alloc(0)
484
+ clients.add(socket)
485
+
486
+ socket.on('data', (chunk) => {
487
+ buffer = Buffer.concat([buffer, chunk])
488
+ while (buffer.length > 0) {
489
+ let result
490
+ try {
491
+ result = decodeFrame(buffer)
492
+ } catch (e) {
493
+ socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)))
494
+ clients.delete(socket)
495
+ return
496
+ }
497
+ if (!result) break
498
+ buffer = buffer.slice(result.bytesConsumed)
499
+
500
+ switch (result.opcode) {
501
+ case OPCODES.TEXT:
502
+ handleMessage(result.payload.toString())
503
+ break
504
+ case OPCODES.CLOSE:
505
+ socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)))
506
+ clients.delete(socket)
507
+ return
508
+ case OPCODES.PING:
509
+ socket.write(encodeFrame(OPCODES.PONG, result.payload))
510
+ break
511
+ case OPCODES.PONG:
512
+ break
513
+ default: {
514
+ const closeBuf = Buffer.alloc(2)
515
+ closeBuf.writeUInt16BE(1003)
516
+ socket.end(encodeFrame(OPCODES.CLOSE, closeBuf))
517
+ clients.delete(socket)
518
+ return
519
+ }
520
+ }
521
+ }
522
+ })
523
+
524
+ socket.on('close', () => clients.delete(socket))
525
+ socket.on('error', () => clients.delete(socket))
526
+ }
527
+
528
+ function handleMessage(text) {
529
+ let event
530
+ try {
531
+ event = JSON.parse(text)
532
+ } catch (e) {
533
+ console.error('Failed to parse WebSocket message:', e.message)
534
+ return
535
+ }
536
+ touchActivity()
537
+ console.log(JSON.stringify({ source: 'user-event', ...event }))
538
+ if (event && event.choice) {
539
+ const eventsFile = path.join(STATE_DIR, 'events')
540
+ fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n')
541
+ }
542
+ }
543
+
544
+ function broadcast(msg) {
545
+ const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg)))
546
+ for (const socket of clients) {
547
+ try {
548
+ socket.write(frame)
549
+ } catch (e) {
550
+ clients.delete(socket)
551
+ }
552
+ }
553
+ }
554
+
555
+ // Best-effort: open the user's browser the first time a screen is actually ready
556
+ // to show. Skips when disabled, on a non-loopback (remote) bind, or when a
557
+ // browser is already connected. Override the launcher with BRAINSTORM_OPEN_CMD.
558
+ let browserOpened = false
559
+ function maybeOpenBrowser() {
560
+ if (browserOpened) return
561
+ browserOpened = true
562
+ if (!process.env.BRAINSTORM_OPEN) return // opt-in: only after the user approves the companion
563
+ if (HOST !== '127.0.0.1' && HOST !== 'localhost') return
564
+ if (clients.size > 0) return // the user already opened it
565
+ const url = companionUrl() // must carry the key or the gate 403s it
566
+ const cp = require('child_process')
567
+ // Operator-provided launcher: run as given (this env var is trusted operator input).
568
+ if (process.env.BRAINSTORM_OPEN_CMD) {
569
+ try {
570
+ cp.exec(process.env.BRAINSTORM_OPEN_CMD + ' ' + JSON.stringify(url), () => {})
571
+ } catch (e) {
572
+ /* best effort */
573
+ }
574
+ return
575
+ }
576
+ // Platform launchers: pass the URL as an argv element via execFile (no shell),
577
+ // so a url-host containing shell metacharacters can't inject a command.
578
+ const launcher = browserLauncherForPlatform(url)
579
+ if (!launcher) return // headless: nothing to open
580
+ try {
581
+ cp.execFile(launcher.bin, launcher.args, () => {})
582
+ } catch (e) {
583
+ /* best effort */
584
+ }
585
+ }
586
+
587
+ // ========== Activity Tracking ==========
588
+
589
+ // Idle timeout: shut down after this long with no activity. Default 4 hours;
590
+ // override with BRAINSTORM_IDLE_TIMEOUT_MS (start-server.sh: --idle-timeout-minutes).
591
+ const IDLE_TIMEOUT_MS = (() => {
592
+ const ms = Number(process.env.BRAINSTORM_IDLE_TIMEOUT_MS)
593
+ return Number.isFinite(ms) && ms > 0 ? ms : 4 * 60 * 60 * 1000
594
+ })()
595
+ // How often the watchdog checks for owner-death / idleness. Configurable mainly
596
+ // so tests can run fast; production default is 60s.
597
+ const LIFECYCLE_CHECK_MS = (() => {
598
+ const ms = Number(process.env.BRAINSTORM_LIFECYCLE_CHECK_MS)
599
+ return Number.isFinite(ms) && ms > 0 ? ms : 60 * 1000
600
+ })()
601
+ let lastActivity = Date.now()
602
+
603
+ function touchActivity() {
604
+ lastActivity = Date.now()
605
+ }
606
+
607
+ // ========== File Watching ==========
608
+
609
+ const debounceTimers = new Map()
610
+
611
+ // ========== Server Startup ==========
612
+
613
+ function startServer() {
614
+ if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true })
615
+ if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true })
616
+
617
+ // Track known files to distinguish new screens from updates.
618
+ // macOS fs.watch reports 'rename' for both new files and overwrites,
619
+ // so we can't rely on eventType alone.
620
+ const knownFiles = new Set(fs.readdirSync(CONTENT_DIR).filter((f) => !f.startsWith('.') && f.endsWith('.html')))
621
+
622
+ const server = http.createServer(handleRequest)
623
+ server.on('upgrade', handleUpgrade)
624
+
625
+ const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => {
626
+ if (!filename || filename.startsWith('.') || !filename.endsWith('.html')) return
627
+
628
+ if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename))
629
+ debounceTimers.set(
630
+ filename,
631
+ setTimeout(() => {
632
+ debounceTimers.delete(filename)
633
+ const filePath = path.join(CONTENT_DIR, filename)
634
+
635
+ if (!fs.existsSync(filePath)) return // file was deleted
636
+ touchActivity()
637
+
638
+ if (!knownFiles.has(filename)) {
639
+ knownFiles.add(filename)
640
+ const eventsFile = path.join(STATE_DIR, 'events')
641
+ if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile)
642
+ console.log(JSON.stringify({ type: 'screen-added', file: filePath }))
643
+ maybeOpenBrowser()
644
+ } else {
645
+ console.log(JSON.stringify({ type: 'screen-updated', file: filePath }))
646
+ }
647
+
648
+ broadcast({ type: 'reload' })
649
+ }, 100),
650
+ )
651
+ })
652
+ watcher.on('error', (err) => console.error('fs.watch error:', err.message))
653
+
654
+ function shutdown(reason) {
655
+ console.log(JSON.stringify({ type: 'server-stopped', reason }))
656
+ const infoFile = path.join(STATE_DIR, 'server-info')
657
+ if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile)
658
+ fs.writeFileSync(path.join(STATE_DIR, 'server-stopped'), JSON.stringify({ reason, timestamp: Date.now() }) + '\n')
659
+ watcher.close()
660
+ clearInterval(lifecycleCheck)
661
+ // Close any upgraded WebSocket sockets so server.close() can complete and
662
+ // the process actually exits instead of lingering on an open connection.
663
+ for (const socket of clients) {
664
+ try {
665
+ socket.destroy()
666
+ } catch (e) {
667
+ /* already gone */
668
+ }
669
+ }
670
+ server.close(() => process.exit(0))
671
+ }
672
+
673
+ function ownerAlive() {
674
+ if (!ownerPid) return true
675
+ try {
676
+ process.kill(ownerPid, 0)
677
+ return true
678
+ } catch (e) {
679
+ return e.code === 'EPERM'
680
+ }
681
+ }
682
+
683
+ // Periodically exit if the owner process died or we've been idle too long.
684
+ const lifecycleCheck = setInterval(() => {
685
+ if (!ownerAlive()) shutdown('owner process exited')
686
+ else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout')
687
+ }, LIFECYCLE_CHECK_MS)
688
+ lifecycleCheck.unref()
689
+
690
+ // Validate owner PID at startup. If it's already dead, the PID resolution
691
+ // was wrong (common on WSL, Tailscale SSH, and cross-user scenarios).
692
+ // Disable monitoring and rely on the idle timeout instead.
693
+ if (ownerPid) {
694
+ try {
695
+ process.kill(ownerPid, 0)
696
+ } catch (e) {
697
+ if (e.code !== 'EPERM') {
698
+ console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' }))
699
+ ownerPid = null
700
+ }
701
+ }
702
+ }
703
+
704
+ // If the preferred port is already taken (e.g. a previous server is still
705
+ // alive), fall back to a random port once instead of failing.
706
+ let triedFallback = false
707
+
708
+ function onListen() {
709
+ // Cookie name keys on the ACTUAL bound port (may differ from the preferred
710
+ // one after an EADDRINUSE fallback) so it can't collide with another server's
711
+ // cookie in the shared localhost jar.
712
+ COOKIE_NAME = 'brainstorm-key-' + PORT
713
+ // Record the bound port AND token so the next restart of this session reuses
714
+ // them — but ONLY when we got our preferred port. On a fallback we bound a
715
+ // *different* port because someone else holds the preferred one; persisting
716
+ // would overwrite the shared files and strand that other session's open tab.
717
+ if (PORT_FILE && !triedFallback) {
718
+ try {
719
+ fs.writeFileSync(PORT_FILE, String(PORT))
720
+ } catch (e) {
721
+ /* best effort */
722
+ }
723
+ if (TOKEN_FILE) {
724
+ try {
725
+ fs.writeFileSync(TOKEN_FILE, TOKEN, { mode: 0o600 })
726
+ chmodOwnerOnly(TOKEN_FILE)
727
+ } catch (e) {
728
+ /* best effort */
729
+ }
730
+ }
731
+ }
732
+ const info = JSON.stringify({
733
+ type: 'server-started',
734
+ port: Number(PORT),
735
+ host: HOST,
736
+ url_host: URL_HOST,
737
+ url: companionUrl(),
738
+ screen_dir: CONTENT_DIR,
739
+ state_dir: STATE_DIR,
740
+ idle_timeout_ms: IDLE_TIMEOUT_MS,
741
+ })
742
+ console.log(info)
743
+ // server-info embeds the key — keep it owner-only.
744
+ fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n', { mode: 0o600 })
745
+ }
746
+
747
+ server.on('error', (err) => {
748
+ if (err.code === 'EADDRINUSE' && !triedFallback) {
749
+ if (tokenSource === 'env') {
750
+ console.error(
751
+ 'Server failed to bind: preferred port is in use and BRAINSTORM_TOKEN is set; refusing fallback with explicit token',
752
+ )
753
+ process.exit(1)
754
+ }
755
+ triedFallback = true
756
+ PORT = randomPort()
757
+ if (tokenSource === 'file') {
758
+ TOKEN = generateToken()
759
+ tokenSource = 'generated-fallback'
760
+ }
761
+ server.listen(PORT, HOST, onListen)
762
+ } else {
763
+ console.error('Server failed to bind:', err.message)
764
+ process.exit(1)
765
+ }
766
+ })
767
+ server.listen(PORT, HOST, onListen)
768
+ }
769
+
770
+ if (require.main === module) {
771
+ startServer()
772
+ }
773
+
774
+ module.exports = {
775
+ computeAcceptKey,
776
+ encodeFrame,
777
+ decodeFrame,
778
+ browserLauncherForPlatform,
779
+ OPCODES,
780
+ MAX_FRAME_PAYLOAD_BYTES,
781
+ }