Repository navigation
harden brainstorming session access and cleanup boundaries - #685
sunxiaoguang wants to merge 1 commit into
Conversation
Signed-off-by: Xiaoguang Sun <[email protected]>
📝 WalkthroughWalkthroughThis pull request extracts server-side logic for the Brainstorm Companion tool into a dedicated, reusable module with token-based authorization, enhances shell scripts with validation and security measures, refactors client-side helper functions, and rewrites test coverage to validate the new modular architecture. Changes
Sequence Diagram(s)sequenceDiagram
actor Client
participant HTTP Server
participant WebSocket Server
participant File System
participant Watcher
Client->>HTTP Server: GET / (with/without token)
HTTP Server->>HTTP Server: authorizeHttpRequest(token)
alt Token valid
HTTP Server->>File System: getNewestScreen()
File System-->>HTTP Server: HTML content
HTTP Server->>HTTP Server: prepareHtmlResponse() + inject helper config
HTTP Server-->>Client: 200 + wrapped HTML
else Token invalid
HTTP Server-->>Client: 401 Unauthorized
end
Client->>WebSocket Server: Upgrade request (with token)
WebSocket Server->>WebSocket Server: authorizeWebSocketRequest(token)
alt Token valid
WebSocket Server-->>Client: 101 Upgraded
Client->>WebSocket Server: {type: "choice", value: "..."}
WebSocket Server->>File System: persistChoiceEvent(.events)
Watcher->>File System: Detect .html file change
Watcher->>WebSocket Server: Notify connected clients
WebSocket Server-->>Client: {type: "reload"}
else Token invalid
WebSocket Server-->>Client: 401 Unauthorized
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@skills/brainstorming/scripts/server-core.js`:
- Around line 168-191: parseClientEvent currently rejects payloads missing
parsed.choice before it reads parsed.type/value, which drops helper-sent {type:
'choice', value} events; fix by deferring the "missing choice" rejection until
after you read parsed.type and parsed.value (or if type === 'choice' treat
parsed.value as the choice): in parseClientEvent use normalizeString on
parsed.type and parsed.value before returning {accepted:false,...}, and if type
=== 'choice' accept a missing parsed.choice by assigning choice =
normalizeString(parsed.value, 200) (or require value instead), referencing the
parseClientEvent function, the event object construction, and normalizeString
calls (choice, type, value) so the helper's {type:'choice', value} events are
preserved.
In `@skills/brainstorming/scripts/start-server.sh`:
- Around line 82-83: The script creates and chmods SCREEN_DIR before changing
directories, then later reuses the same relative SCREEN_DIR/PID_FILE/LOG_FILE
after cd "$SCRIPT_DIR", which can create duplicate session files in different
locations; normalize SCREEN_DIR, PID_FILE, and LOG_FILE to absolute paths
immediately after they are computed (before any cd) so all subsequent uses
(including the mkdir/chmod and the later references around the PID_FILE/LOG_FILE
handling) operate on the same absolute locations; update references to
SCREEN_DIR, PID_FILE, and LOG_FILE in start-server.sh accordingly so mkdir -p
and cleanup use the absolute paths.
- Around line 95-98: The foreground branch in start-server.sh writes the wrapper
shell PID to PID_FILE (using $$) so stop-server.sh can't match the Node index.js
process; change the foreground handling so either (a) use exec to replace the
shell with Node (exec node index.js ...) so $$ becomes the Node PID written to
PID_FILE, or (b) spawn Node and record its actual PID (capture $! after starting
node in background and write that to PID_FILE), while preserving the existing
env BRAINSTORM_* assignments and behavior around BIND_HOST/SCREEN_DIR and
BRAINSTORM_TOKEN.
In `@skills/brainstorming/scripts/stop-server.sh`:
- Around line 57-60: The PID guard in stop-server.sh currently only checks for
generic substrings and can match unrelated Node processes; update the logic so
stop-server.sh verifies a session-specific marker before killing the PID: modify
start-server.sh to launch the server with a unique identifier (for example add a
command-line flag like --session-dir or --session-id that includes the session
directory name or create a distinct process title/environment variable) and then
change stop-server.sh to read .server.pid, inspect the running process via the
command variable and only allow termination if that command contains the exact
session-specific marker (e.g., the session dir path or the unique --session-id
string) otherwise refuse to stop. Ensure you update both start-server.sh (to
inject the marker) and stop-server.sh (to check for that exact marker instead of
just "node" or "index.js") using the .server.pid and command variables.
In `@skills/brainstorming/visual-companion.md`:
- Around line 83-84: Update the sample startup JSON in visual-companion.md to
show the tokenized URL shape (e.g., include a session token query or path
fragment) instead of the bare "http://localhost:52341" or explicitly mark that
value as redacted; locate the "sample startup JSON" / "returned URL" example and
replace the unauthenticated URL with either the tokenized form used by the
runtime or a clear "[REDACTED: tokenized URL]" placeholder so readers won't copy
the old unauthenticated shape.
In `@skills/using-git-worktrees/SKILL.md`:
- Around line 103-110: The document describes a gated setup but later sections
still instruct unconditional setup; update the example workflow (Step 4), the
"Always" checklist, and any example run commands so they check the same two
conditions (trusted repository and explicit user consent) before running
installs/tests, and where commands are skipped explicitly state "worktree ready;
dependencies/tests not bootstrapped"; ensure references to "gated setup", "Step
4", and "Always" use the same gating language and add the explicit
user-consent/trust check to any auto-run guidance.
In `@tests/brainstorm-server/server.test.js`:
- Around line 138-149: The test currently never reaches the forged-PID branch
because stop-server.sh requires a valid .server-info; to fix, create/write a
valid .server-info in stopDir (matching the session format expected by
stop-server.sh) before calling spawnSync so the script will process the pid file
and then fail on the unrelated process check; update the assertions to expect
the specific "unrelated process" failure message (rather than the generic
'Refusing') and keep references to stopDir, sleeper, STOP_SERVER_PATH,
.server.pid and .server-info so the change is easy to locate.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 12a98e53-e406-480b-bd6a-d5c1a1369a2d
⛔ Files ignored due to path filters (2)
skills/brainstorming/scripts/node_modules/.package-lock.jsonis excluded by!**/node_modules/**skills/brainstorming/scripts/package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (8)
skills/brainstorming/scripts/helper.jsskills/brainstorming/scripts/index.jsskills/brainstorming/scripts/server-core.jsskills/brainstorming/scripts/start-server.shskills/brainstorming/scripts/stop-server.shskills/brainstorming/visual-companion.mdskills/using-git-worktrees/SKILL.mdtests/brainstorm-server/server.test.js
| const choice = normalizeString(parsed.choice, 200); | ||
| if (!choice) { | ||
| return { accepted: false, reason: 'invalid-choice' }; | ||
| } | ||
|
|
||
| const type = normalizeString(parsed.type, 40) || 'choice'; | ||
| const event = { | ||
| type, | ||
| choice, | ||
| }; | ||
|
|
||
| const text = normalizeString(parsed.text, 500); | ||
| if (text) { | ||
| event.text = text; | ||
| } | ||
|
|
||
| const id = normalizeString(parsed.id, 200); | ||
| if (id) { | ||
| event.id = id; | ||
| } | ||
|
|
||
| const value = normalizeString(parsed.value, 500); | ||
| if (value) { | ||
| event.value = value; |
There was a problem hiding this comment.
parseClientEvent now drops brainstorm.choice() calls.
skills/brainstorming/scripts/helper.js:97-100 still sends { type: 'choice', value }, but Lines 168-170 reject every payload without choice before value is even read. If that public helper remains supported, these events will silently disappear from .events.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@skills/brainstorming/scripts/server-core.js` around lines 168 - 191,
parseClientEvent currently rejects payloads missing parsed.choice before it
reads parsed.type/value, which drops helper-sent {type: 'choice', value} events;
fix by deferring the "missing choice" rejection until after you read parsed.type
and parsed.value (or if type === 'choice' treat parsed.value as the choice): in
parseClientEvent use normalizeString on parsed.type and parsed.value before
returning {accepted:false,...}, and if type === 'choice' accept a missing
parsed.choice by assigning choice = normalizeString(parsed.value, 200) (or
require value instead), referencing the parseClientEvent function, the event
object construction, and normalizeString calls (choice, type, value) so the
helper's {type:'choice', value} events are preserved.
| mkdir -p "$SCREEN_DIR" | ||
| chmod 700 "$SCREEN_DIR" |
There was a problem hiding this comment.
Normalize SCREEN_DIR before the cd.
Lines 82-83 create the session directory in the caller's cwd, but after the cd "$SCRIPT_DIR" on Line 92 the same relative SCREEN_DIR/PID_FILE/LOG_FILE values are reused in Lines 97 and 103. --project-dir . will therefore split one session across two different directories and break .server-info, .events, pid/log files, and later cleanup.
Also applies to: 97-103
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@skills/brainstorming/scripts/start-server.sh` around lines 82 - 83, The
script creates and chmods SCREEN_DIR before changing directories, then later
reuses the same relative SCREEN_DIR/PID_FILE/LOG_FILE after cd "$SCRIPT_DIR",
which can create duplicate session files in different locations; normalize
SCREEN_DIR, PID_FILE, and LOG_FILE to absolute paths immediately after they are
computed (before any cd) so all subsequent uses (including the mkdir/chmod and
the later references around the PID_FILE/LOG_FILE handling) operate on the same
absolute locations; update references to SCREEN_DIR, PID_FILE, and LOG_FILE in
start-server.sh accordingly so mkdir -p and cleanup use the absolute paths.
| if [[ "$FOREGROUND" == "true" ]]; then | ||
| echo "$$" > "$PID_FILE" | ||
| env BRAINSTORM_DIR="$SCREEN_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" node index.js | ||
| env BRAINSTORM_DIR="$SCREEN_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_TOKEN="$BRAINSTORM_TOKEN" node index.js | ||
| exit $? |
There was a problem hiding this comment.
Foreground mode records the shell PID, not the server PID.
Line 96 writes $$, which is the wrapper shell. stop-server.sh later checks for a Node index.js process, so foreground sessions will be treated as unrelated and won't stop cleanly unless this branch execs Node or records the child PID instead.
Suggested fix
if [[ "$FOREGROUND" == "true" ]]; then
echo "$$" > "$PID_FILE"
- env BRAINSTORM_DIR="$SCREEN_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_TOKEN="$BRAINSTORM_TOKEN" node index.js
- exit $?
+ exec env BRAINSTORM_DIR="$SCREEN_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_TOKEN="$BRAINSTORM_TOKEN" node index.js
fi📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if [[ "$FOREGROUND" == "true" ]]; then | |
| echo "$$" > "$PID_FILE" | |
| env BRAINSTORM_DIR="$SCREEN_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" node index.js | |
| env BRAINSTORM_DIR="$SCREEN_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_TOKEN="$BRAINSTORM_TOKEN" node index.js | |
| exit $? | |
| if [[ "$FOREGROUND" == "true" ]]; then | |
| echo "$$" > "$PID_FILE" | |
| exec env BRAINSTORM_DIR="$SCREEN_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_TOKEN="$BRAINSTORM_TOKEN" node index.js | |
| fi |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@skills/brainstorming/scripts/start-server.sh` around lines 95 - 98, The
foreground branch in start-server.sh writes the wrapper shell PID to PID_FILE
(using $$) so stop-server.sh can't match the Node index.js process; change the
foreground handling so either (a) use exec to replace the shell with Node (exec
node index.js ...) so $$ becomes the Node PID written to PID_FILE, or (b) spawn
Node and record its actual PID (capture $! after starting node in background and
write that to PID_FILE), while preserving the existing env BRAINSTORM_*
assignments and behavior around BIND_HOST/SCREEN_DIR and BRAINSTORM_TOKEN.
| command="$(ps -p "$pid" -o command= 2>/dev/null)" | ||
| if [[ -n "$command" && ( "$command" != *"node"* || "$command" != *"index.js"* ) ]]; then | ||
| echo '{"error": "Refusing to stop unrelated process"}' | ||
| exit 1 |
There was a problem hiding this comment.
The PID guard still matches unrelated node index.js services.
Lines 57-60 only prove "some Node process whose command contains index.js". Since skills/brainstorming/scripts/start-server.sh still launches a plain node index.js, a forged session dir can point .server.pid at an unrelated app started as node /other/service/index.js and this script will still kill it. Please validate a session-specific marker instead of generic substrings.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@skills/brainstorming/scripts/stop-server.sh` around lines 57 - 60, The PID
guard in stop-server.sh currently only checks for generic substrings and can
match unrelated Node processes; update the logic so stop-server.sh verifies a
session-specific marker before killing the PID: modify start-server.sh to launch
the server with a unique identifier (for example add a command-line flag like
--session-dir or --session-id that includes the session directory name or create
a distinct process title/environment variable) and then change stop-server.sh to
read .server.pid, inspect the running process via the command variable and only
allow termination if that command contains the exact session-specific marker
(e.g., the session dir path or the unique --session-id string) otherwise refuse
to stop. Ensure you update both start-server.sh (to inject the marker) and
stop-server.sh (to check for that exact marker instead of just "node" or
"index.js") using the .server.pid and command variables.
| The returned URL now includes a session token. Treat that URL as a secret capability: only share it with the intended reviewer, and prefer loopback or another trusted network boundary whenever possible. | ||
| Only bind `0.0.0.0` or another non-loopback host when the surrounding network is trusted enough for the mockup content you are serving. |
There was a problem hiding this comment.
Show the tokenized URL shape in the example output.
Line 83 says the returned URL now carries the session token, but the sample startup JSON above still shows a bare http://localhost:52341. If that value is intentionally redacted, please mark it as redacted; otherwise manual users will copy the old, unauthenticated shape.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@skills/brainstorming/visual-companion.md` around lines 83 - 84, Update the
sample startup JSON in visual-companion.md to show the tokenized URL shape
(e.g., include a session token query or path fragment) instead of the bare
"http://localhost:52341" or explicitly mark that value as redacted; locate the
"sample startup JSON" / "returned URL" example and replace the unauthenticated
URL with either the tokenized form used by the runtime or a clear "[REDACTED:
tokenized URL]" placeholder so readers won't copy the old unauthenticated shape.
| Only run setup commands when both conditions hold: | ||
|
|
||
| - The repository is trusted enough to execute its install/build hooks | ||
| - The user explicitly asked for setup or approved the networked dependency step | ||
|
|
||
| If either condition is not true, skip this section and report that the worktree is ready but dependencies/tests were not bootstrapped. | ||
|
|
||
| When it is safe and explicitly desired, auto-detect and run appropriate setup: |
There was a problem hiding this comment.
The skill is still self-contradictory about gated setup.
This block makes setup conditional, but Step 4, the example workflow, and the "Always" checklist still instruct the agent to run install/test commands unconditionally. Those sections need the same gate or the new trust boundary can still be bypassed by following the later instructions.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@skills/using-git-worktrees/SKILL.md` around lines 103 - 110, The document
describes a gated setup but later sections still instruct unconditional setup;
update the example workflow (Step 4), the "Always" checklist, and any example
run commands so they check the same two conditions (trusted repository and
explicit user consent) before running installs/tests, and where commands are
skipped explicitly state "worktree ready; dependencies/tests not bootstrapped";
ensure references to "gated setup", "Step 4", and "Always" use the same gating
language and add the explicit user-consent/trust check to any auto-run guidance.
| console.log('Test 7: stop-server refuses to kill unrelated processes from forged pid files'); | ||
| const stopDir = makeTempDir('brainstorm-stop-'); | ||
| const sleeper = spawn('sleep', ['30'], { stdio: 'ignore' }); | ||
| fs.writeFileSync(path.join(stopDir, '.server.pid'), `${sleeper.pid}\n`); | ||
|
|
||
| try { | ||
| // Test 1: Server starts and outputs JSON | ||
| console.log('Test 1: Server startup message'); | ||
| assert(stdout.includes('server-started'), 'Should output server-started'); | ||
| assert(stdout.includes(TEST_PORT.toString()), 'Should include port'); | ||
| console.log(' PASS'); | ||
|
|
||
| // Test 2: GET / returns waiting page with helper injected when no screens exist | ||
| console.log('Test 2: Serves waiting page with helper injected'); | ||
| const res = await fetch(`http://localhost:${TEST_PORT}/`); | ||
| assert.strictEqual(res.status, 200); | ||
| assert(res.body.includes('Waiting for Claude'), 'Should show waiting message'); | ||
| assert(res.body.includes('WebSocket'), 'Should have helper.js injected'); | ||
| console.log(' PASS'); | ||
|
|
||
| // Test 3: WebSocket connection and event relay | ||
| console.log('Test 3: WebSocket relays events to stdout'); | ||
| stdout = ''; | ||
| const ws = new WebSocket(`ws://localhost:${TEST_PORT}`); | ||
| await new Promise(resolve => ws.on('open', resolve)); | ||
|
|
||
| ws.send(JSON.stringify({ type: 'click', text: 'Test Button' })); | ||
| await sleep(300); | ||
|
|
||
| assert(stdout.includes('"source":"user-event"'), 'Should relay user events with source field'); | ||
| assert(stdout.includes('Test Button'), 'Should include event data'); | ||
| ws.close(); | ||
| console.log(' PASS'); | ||
|
|
||
| // Test 4: File change triggers reload notification | ||
| console.log('Test 4: File change notifies browsers'); | ||
| const ws2 = new WebSocket(`ws://localhost:${TEST_PORT}`); | ||
| await new Promise(resolve => ws2.on('open', resolve)); | ||
|
|
||
| let gotReload = false; | ||
| ws2.on('message', (data) => { | ||
| const msg = JSON.parse(data.toString()); | ||
| if (msg.type === 'reload') gotReload = true; | ||
| const stopResult = spawnSync('bash', [STOP_SERVER_PATH, stopDir], { | ||
| encoding: 'utf-8', | ||
| }); | ||
|
|
||
| fs.writeFileSync(path.join(TEST_DIR, 'test-screen.html'), '<html><body>Full doc</body></html>'); | ||
| await sleep(500); | ||
|
|
||
| assert(gotReload, 'Should send reload message on file change'); | ||
| ws2.close(); | ||
| console.log(' PASS'); | ||
|
|
||
| // Test: Choice events written to .events file | ||
| console.log('Test: Choice events written to .events file'); | ||
| const ws3 = new WebSocket(`ws://localhost:${TEST_PORT}`); | ||
| await new Promise(resolve => ws3.on('open', resolve)); | ||
|
|
||
| ws3.send(JSON.stringify({ type: 'click', choice: 'a', text: 'Option A' })); | ||
| await sleep(300); | ||
|
|
||
| const eventsFile = path.join(TEST_DIR, '.events'); | ||
| assert(fs.existsSync(eventsFile), '.events file should exist after choice click'); | ||
| const lines = fs.readFileSync(eventsFile, 'utf-8').trim().split('\n'); | ||
| const event = JSON.parse(lines[lines.length - 1]); | ||
| assert.strictEqual(event.choice, 'a', 'Event should contain choice'); | ||
| assert.strictEqual(event.text, 'Option A', 'Event should contain text'); | ||
| ws3.close(); | ||
| assert.notStrictEqual(stopResult.status, 0); | ||
| assert(stopResult.stdout.includes('Refusing')); |
There was a problem hiding this comment.
This test never exercises the forged-PID branch anymore.
stop-server.sh now refuses sessions without a valid .server-info first, so the assertion on stdout.includes('Refusing') will pass even if the unrelated-process check is broken. Seed a matching .server-info here and assert on the specific "unrelated process" failure instead.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/brainstorm-server/server.test.js` around lines 138 - 149, The test
currently never reaches the forged-PID branch because stop-server.sh requires a
valid .server-info; to fix, create/write a valid .server-info in stopDir
(matching the session format expected by stop-server.sh) before calling
spawnSync so the script will process the pid file and then fail on the unrelated
process check; update the assertions to expect the specific "unrelated process"
failure message (rather than the generic 'Refusing') and keep references to
stopDir, sleeper, STOP_SERVER_PATH, .server.pid and .server-info so the change
is easy to locate.
Motivation and Context
The current brainstorming companion flow works well for the local happy path, but it relies on trust assumptions that are not enforced by the implementation.
This change is needed to reduce a few concrete risks:
The goal of this PR is to keep the workflow the same while making the default behavior safer and more defensive.
How Has This Been Tested?
Tested locally with focused security-oriented coverage:
Scenarios covered by tests:
A full end-to-end socket bind was not exercised in this environment because local listen operations are restricted here.
Breaking Changes
For the intended workflow, no user action should be required: start-server.sh now returns a URL that already includes the session token.
However, any custom/manual consumer that previously connected to the brainstorm server by constructing http://host:port/ or ws://host:port directly will now need to include the returned token query parameter.
Types of changes
Checklist
Additional context
Implementation notes:
Only the targeted brainstorm-server test coverage and related script/audit checks were run for this PR; the full repository test suite was not run in this pass.