Repository navigation
Conversation
|
@RinZ27 is attempting to deploy a commit to the rohitg00's projects Team on Vercel. A member of the Team first needs to authorize it. |
📝 WalkthroughWalkthroughThis PR hardens file write operations by replacing direct path-based writes with secure file descriptor patterns using ChangesSecurity Hardening Across File Writes, Authentication, and Logging
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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: 2
♻️ Duplicate comments (2)
test/snapshot.test.ts (1)
33-39: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick winTest mocks should include
closeSyncto verify resource cleanup.Same issue as in
test/claude-bridge.test.ts: the mock should includecloseSyncand verify it's called to ensure the file descriptor is properly released.🧪 Enhanced mock with closeSync verification
vi.mock("node:fs", () => ({ existsSync: vi.fn().mockReturnValue(true), mkdirSync: vi.fn(), writeFileSync: vi.fn(), readFileSync: vi .fn() .mockReturnValue('{"version":"0.4.0","sessions":[],"memories":[]}'), constants: { O_WRONLY: 1, O_CREAT: 2, O_TRUNC: 4, O_NOFOLLOW: 8, }, openSync: vi.fn().mockReturnValue(123), + closeSync: vi.fn(), }));Then verify in the snapshot creation test:
+import { closeSync } from "node:fs"; + it("snapshot-create serializes state and returns meta", async () => { const result = (await sdk.trigger("mem::snapshot-create", { message: "Test snapshot", })) as { success: boolean; snapshot: SnapshotMeta }; expect(result.success).toBe(true); + expect(closeSync).toHaveBeenCalledWith(123); // ... rest of test });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/snapshot.test.ts` around lines 33 - 39, Add a mock for closeSync alongside openSync in the test's fs mock (the constants object and openSync mock already present) and update the snapshot creation test to assert that the mocked closeSync was called to verify the file descriptor was released; specifically, add a vi.fn() mock named closeSync where openSync is mocked and then add an expectation like expect(closeSync).toHaveBeenCalled() in the relevant snapshot creation test to ensure resource cleanup is verified.src/functions/snapshot.ts (1)
78-84:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winFile descriptor leak: missing
closeSyncafter write.Identical to the issue in
claude-bridge.ts, the file descriptor fromopenSyncis never closed, causing a resource leak on everymem::snapshot-createinvocation.🔒 Proposed fix with explicit close
+import { existsSync, mkdirSync, writeFileSync, readFileSync, constants, openSync, closeSync } from "node:fs";const stateContent = JSON.stringify(state, null, 2); const statePath = join(snapshotDir, "state.json"); const fd = openSync( statePath, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW, ); -writeFileSync(fd, stateContent, "utf-8"); +try { + writeFileSync(fd, stateContent, "utf-8"); +} finally { + closeSync(fd); +}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/functions/snapshot.ts` around lines 78 - 84, The state file descriptor opened via openSync (fd) is never closed, causing a leak; update the snapshot creation in src/functions/snapshot.ts (around stateContent/statePath/fd) to ensure the descriptor is closed after writing (e.g., wrap the writeFileSync call in a try/finally and call closeSync(fd) in the finally, or avoid openSync entirely and write directly to statePath), so fd is always closed even on errors.
🧹 Nitpick comments (1)
src/viewer/server.ts (1)
108-114: 💤 Low valueConsider extracting the token before comparison.
While the current implementation works, it compares the entire
Authorizationheader including theBearerprefix. Standard practice is to validate the scheme separately, then extract and compare just the token. This makes the validation more robust against whitespace variations.♻️ More flexible token validation
if (secret) { const auth = req.headers["authorization"]; - if (typeof auth !== "string" || !timingSafeCompare(auth, `Bearer ${secret}`)) { + const expectedScheme = "Bearer "; + if ( + typeof auth !== "string" || + !auth.startsWith(expectedScheme) || + !timingSafeCompare(auth.slice(expectedScheme.length).trim(), secret) + ) { json(res, 401, { error: "unauthorized" }, req); return; } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/viewer/server.ts` around lines 108 - 114, Extract and validate the Bearer token separately before calling timingSafeCompare: read req.headers["authorization"] into a variable, verify it's a string and starts with the "Bearer " scheme (handle casing/whitespace by trimming and using .startsWith or splitting on whitespace), extract the token portion (everything after "Bearer "), then call timingSafeCompare(token, secret); if checks fail call json(res, 401, { error: "unauthorized" }, req) and return. This change should be applied in the same block that currently references secret, req.headers["authorization"], timingSafeCompare, and json.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/functions/claude-bridge.ts`:
- Around line 142-146: The code opens a file descriptor with openSync (using
constants.O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW) and calls writeFileSync(fd,
md, "utf-8") but never closes the descriptor; import closeSync from node:fs and
change the write to ensure the fd is always closed by wrapping the writeFileSync
call in a try/finally (or equivalent) that calls closeSync(fd) in the finally
block; update the imports and ensure the logic around config.memoryFilePath,
openSync, writeFileSync and closeSync is adjusted accordingly to prevent file
descriptor leaks.
In `@test/claude-bridge.test.ts`:
- Around line 12-18: Add a mocked closeSync alongside the existing openSync and
constants in the test's fs mock (e.g., add closeSync: vi.fn()), keep
openSync.mockReturnValue(123) as-is, and update the sync write test to assert
closeSync was called (for example
expect(mockFs.closeSync).toHaveBeenCalledWith(123) or
expect(mockFs.closeSync).toHaveBeenCalled()). This ensures the implementation
calls closeSync after writes and the test will catch file descriptor leaks.
---
Duplicate comments:
In `@src/functions/snapshot.ts`:
- Around line 78-84: The state file descriptor opened via openSync (fd) is never
closed, causing a leak; update the snapshot creation in
src/functions/snapshot.ts (around stateContent/statePath/fd) to ensure the
descriptor is closed after writing (e.g., wrap the writeFileSync call in a
try/finally and call closeSync(fd) in the finally, or avoid openSync entirely
and write directly to statePath), so fd is always closed even on errors.
In `@test/snapshot.test.ts`:
- Around line 33-39: Add a mock for closeSync alongside openSync in the test's
fs mock (the constants object and openSync mock already present) and update the
snapshot creation test to assert that the mocked closeSync was called to verify
the file descriptor was released; specifically, add a vi.fn() mock named
closeSync where openSync is mocked and then add an expectation like
expect(closeSync).toHaveBeenCalled() in the relevant snapshot creation test to
ensure resource cleanup is verified.
---
Nitpick comments:
In `@src/viewer/server.ts`:
- Around line 108-114: Extract and validate the Bearer token separately before
calling timingSafeCompare: read req.headers["authorization"] into a variable,
verify it's a string and starts with the "Bearer " scheme (handle
casing/whitespace by trimming and using .startsWith or splitting on whitespace),
extract the token portion (everything after "Bearer "), then call
timingSafeCompare(token, secret); if checks fail call json(res, 401, { error:
"unauthorized" }, req) and return. This change should be applied in the same
block that currently references secret, req.headers["authorization"],
timingSafeCompare, and json.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 9245273f-0c61-41c9-8ba0-3a00505f63c4
📒 Files selected for processing (6)
src/functions/claude-bridge.tssrc/functions/snapshot.tssrc/index.tssrc/viewer/server.tstest/claude-bridge.test.tstest/snapshot.test.ts
f2b76b7 to
7ef3afd
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/auth.ts`:
- Around line 6-10: In timingSafeCompare, create the buffers from the input
strings first (e.g., Buffer.from(a) and Buffer.from(b)), then compare their byte
lengths (bufA.length and bufB.length) and return false if they differ before
calling timingSafeEqual; update the function (timingSafeCompare) to check buffer
byte lengths rather than JavaScript string lengths so timingSafeEqual cannot
throw for differing byte-length inputs.
In `@src/mcp/server.ts`:
- Around line 54-58: The Bearer scheme check in the MCP auth path uses a
case-sensitive startsWith("Bearer ") which rejects valid variants; update the
logic that builds and checks prefix to compare the auth-scheme
case-insensitively (e.g., lowercasing the scheme portion of auth before
matching) and then perform timingSafeCompare on the token part (use auth.slice
after the scheme delimiter). Replace the local prefix/check in src/mcp/server.ts
(references: prefix, auth, timingSafeCompare) to call/reuse the existing
scheme/token parsing helper used by the REST auth path so both paths share the
same case-insensitive parsing behavior.
In `@src/triggers/api.ts`:
- Around line 39-43: The auth parsing is too strict: update checkAuth() to split
the Authorization header on whitespace (e.g., auth.trim().split(/\s+/)), verify
there are at least two parts, compare the scheme case-insensitively
(scheme.toLowerCase() === "bearer"), and then perform timingSafeCompare on the
rest joined as the token; apply the same change to the middleware handler that
currently uses prefix = "Bearer " so both places accept any case and multiple
spaces between scheme and credentials.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 56c2fd5e-6e7f-4eca-8b75-d988428737fb
📒 Files selected for processing (9)
src/auth.tssrc/functions/claude-bridge.tssrc/functions/snapshot.tssrc/index.tssrc/mcp/server.tssrc/triggers/api.tssrc/viewer/server.tstest/claude-bridge.test.tstest/snapshot.test.ts
🚧 Files skipped from review as they are similar to previous changes (6)
- src/functions/claude-bridge.ts
- test/claude-bridge.test.ts
- test/snapshot.test.ts
- src/functions/snapshot.ts
- src/viewer/server.ts
- src/index.ts
7ef3afd to
663e25a
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/triggers/api.ts (1)
39-40: ⚡ Quick winConsider stricter RFC 7235 compliance for Bearer token parsing.
The regex
/^bearer\s+(.+)$/iis more permissive than RFC 7235/9110 requires. While it correctly handles case-insensitivity and multiple spaces (addressing the prior review), it deviates from the spec in two ways:
\s+matches any whitespace (tabs, form-feeds, etc.), but RFC 7235 specifies1*SP(one or more ASCII space characters, U+0020 only).+accepts any token content, including embedded spaces, but RFC 7235token68allows only[A-Za-z0-9\-._~+/=]While not a security risk (malformed tokens won't match the secret and will be rejected), adopting the helper function from the previous review would improve RFC compliance and fail fast on malformed input:
📋 Recommended refactor aligned with past review
+function extractBearerToken(auth: unknown): string | null { + if (typeof auth !== "string") return null; + const parts = auth.trim().split(/ +/); + if (parts.length !== 2 || parts[0].toLowerCase() !== "bearer") return null; + return parts[1]; +} + function checkAuth( req: ApiRequest, secret: string | undefined, ): Response | null { if (!secret) return null; const auth = req.headers?.["authorization"] || req.headers?.["Authorization"]; - const match = typeof auth === "string" ? auth.match(/^bearer\s+(.+)$/i) : null; - if (!match || !timingSafeCompare(match[1], secret)) { + const token = extractBearerToken(auth); + if (!token || !timingSafeCompare(token, secret)) { return { status_code: 401, body: { error: "unauthorized" } }; } return null; }Note: Changed
split(/\s+/)tosplit(/ +/)to strictly match ASCII spaces per RFC 7235. Theparts.length !== 2check ensures tokens with embedded spaces are rejected.Also applies to: 127-128
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/triggers/api.ts` around lines 39 - 40, The current bearer parsing uses a permissive regex (/^bearer\s+(.+)$/i) that allows non-ASCII spaces and tokens with embedded spaces; replace it with an RFC‑7235/token68 compliant parse: split the Authorization header on a single-space delimiter (use split(/ +/) or equivalent that matches ASCII SP only), verify there are exactly two parts and the scheme equals "Bearer" (case-insensitive), then validate the token against token68 characters (allowed set [A-Za-z0-9\-._~+/=]) before calling timingSafeCompare(matchToken, secret); implement this as a small helper (e.g., parseBearerToken or validateToken68) and use it in place of the current match variable logic so malformed headers fail fast.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@src/triggers/api.ts`:
- Around line 39-40: The current bearer parsing uses a permissive regex
(/^bearer\s+(.+)$/i) that allows non-ASCII spaces and tokens with embedded
spaces; replace it with an RFC‑7235/token68 compliant parse: split the
Authorization header on a single-space delimiter (use split(/ +/) or equivalent
that matches ASCII SP only), verify there are exactly two parts and the scheme
equals "Bearer" (case-insensitive), then validate the token against token68
characters (allowed set [A-Za-z0-9\-._~+/=]) before calling
timingSafeCompare(matchToken, secret); implement this as a small helper (e.g.,
parseBearerToken or validateToken68) and use it in place of the current match
variable logic so malformed headers fail fast.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: c3f8a15c-d623-4a8b-ae5a-d98769f51427
📒 Files selected for processing (9)
src/auth.tssrc/functions/claude-bridge.tssrc/functions/snapshot.tssrc/index.tssrc/mcp/server.tssrc/triggers/api.tssrc/viewer/server.tstest/claude-bridge.test.tstest/snapshot.test.ts
✅ Files skipped from review due to trivial changes (1)
- test/claude-bridge.test.ts
🚧 Files skipped from review as they are similar to previous changes (7)
- src/index.ts
- src/functions/claude-bridge.ts
- src/functions/snapshot.ts
- src/mcp/server.ts
- src/viewer/server.ts
- test/snapshot.test.ts
- src/auth.ts
…gets Both used plain writeFileSync. Write a temp file in the same directory (exclusive create) and rename over the target, and refuse a target that is a symlink. Ref rohitg00#264. Generated-By: Claude Sonnet 5.5
|
Closing: main has |
Several architectural hardening measures have been implemented to improve the system's resilience against common exploit vectors. These changes focus on the internal viewer's proxy security and file system integrity during persistence operations.
Key updates:
snapshot.tsandclaude-bridge.ts. UsingO_NOFOLLOWduring file creation ensures that memory exports and state snapshots cannot be redirected to overwrite sensitive system files.Summary by CodeRabbit
Security
Bug Fixes / Reliability
Tests