Skip to content

harden brainstorming session access and cleanup boundaries - #685

Closed
sunxiaoguang wants to merge 1 commit into
obra:mainfrom
sunxiaoguang:enhancement
Closed

sunxiaoguang wants to merge 1 commit into
obra:mainfrom
sunxiaoguang:enhancement

Conversation

@sunxiaoguang

Copy link
Copy Markdown

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:

  • HTTP and WebSocket access were effectively unauthenticated
  • malformed client messages could be parsed or persisted too early
  • session directories and metadata files could inherit permissive host defaults
  • stop-server.sh trusted caller-provided paths and pid files too much
  • the lockfile still resolved the vulnerable qs version reported by npm audit

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:

  • cd tests/brainstorm-server && npm test
  • cd skills/brainstorming/scripts && npm audit --omit=dev
  • bash -n skills/brainstorming/scripts/start-server.sh
  • bash -n skills/brainstorming/scripts/stop-server.sh

Scenarios covered by tests:

  • tokenized runtime URLs for HTTP and WebSocket access
  • rejecting requests without the correct session token
  • ignoring malformed WebSocket payloads
  • writing session directories and metadata with restrictive permissions
  • refusing to let stop-server.sh kill unrelated processes via forged pid files

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

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update

Checklist

Additional context

Implementation notes:

  • added per-session token validation for both HTTP and WebSocket access
  • validated client events before accepting/persisting them
  • tightened permissions for session directories, .server-info, and .events
  • hardened stop-server.sh with path canonicalization and process verification
  • updated the lockfile to resolve the qs advisory
  • updated docs to better communicate trust boundaries around non-loopback exposure and networked setup steps

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.

@coderabbitai

coderabbitai Bot commented Mar 11, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This 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

Cohort / File(s) Summary
Brainstorm Server Core
skills/brainstorming/scripts/server-core.js, skills/brainstorming/scripts/index.js
Extracts all server logic (HTTP, WebSocket, file watching, authorization) into a new standalone module. index.js now delegates to server-core via a single startServer() call, reducing it from 146 to 2 lines.
Brainstorm Client Helpers
skills/brainstorming/scripts/helper.js
Centralizes indicator text updates via a new setIndicatorText() helper function. Adds WebSocket URL override via window.BRAINSTORM_WS_URL. Replaces scattered DOM manipulations with consistent helper calls.
Brainstorm Server Scripts
skills/brainstorming/scripts/start-server.sh, skills/brainstorming/scripts/stop-server.sh
start-server.sh: Enforces secure umask (077), generates random token, sets restrictive session directory permissions. stop-server.sh: Adds helper functions for directory canonicalization, validates against .server-info file, verifies running process is Node.js, safely cleans up ephemeral sessions.
Documentation
skills/brainstorming/visual-companion.md, skills/using-git-worktrees/SKILL.md
visual-companion.md: Adds security guidance on treating URLs as secrets and trusting network boundaries. using-git-worktrees/SKILL.md: Adds conditional guards for setup execution based on trust and user approval.
Test Suite
tests/brainstorm-server/server.test.js
Rewrites tests to focus on core module utilities: runtime config, HTTP/WebSocket authorization, HTML response wrapping, file permissions, and asset validation. Replaces integration-style tests with modular unit-like checks against server-core exports.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 A hop and a skip through server-side code,
Where tokens dance and permissions bestow,
We've carved out a core that's tidy and tight,
With watchers and frames that sync up just right!
Now helpers and shells keep watch with care,
Security flourishes—everywhere! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main objective of the PR: hardening session access controls and cleanup boundaries for the brainstorming tool, which aligns directly with the core changes across multiple files.
Description check ✅ Passed The description comprehensively outlines the motivation, risks addressed, key implementation changes, testing approach, and breaking changes, all of which directly relate to the changeset modifications.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5ef73d2 and 978b38c.

⛔ Files ignored due to path filters (2)
  • skills/brainstorming/scripts/node_modules/.package-lock.json is excluded by !**/node_modules/**
  • skills/brainstorming/scripts/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (8)
  • skills/brainstorming/scripts/helper.js
  • skills/brainstorming/scripts/index.js
  • skills/brainstorming/scripts/server-core.js
  • skills/brainstorming/scripts/start-server.sh
  • skills/brainstorming/scripts/stop-server.sh
  • skills/brainstorming/visual-companion.md
  • skills/using-git-worktrees/SKILL.md
  • tests/brainstorm-server/server.test.js

Comment on lines +168 to +191
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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

Comment on lines 82 to +83
mkdir -p "$SCREEN_DIR"
chmod 700 "$SCREEN_DIR"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

Comment on lines 95 to 98
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 $?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

Suggested change
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.

Comment on lines +57 to +60
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

Comment on lines +83 to +84
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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

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.

Comment on lines +103 to +110
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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

Comment on lines +138 to +149
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'));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant