fix(security): use constant-time token comparison to prevent timing attacks
Summary
Replaces non-constant-time string comparison (!== / ===) with crypto.timingSafeEqual at all three secret-token validation boundaries in Orca, closing a timing-attack vector that could let a local attacker recover tokens byte-by-byte.
The vulnerability
All three token checks used direct string equality, which short-circuits on the first differing byte. A local attacker measuring response timing could infer how many leading bytes of a token match and iteratively recover the full token:
| Boundary | File | Original comparison |
|---|---|---|
| Agent-hook HTTP server | src/main/agent-hooks/server.ts |
req.headers['x-orca-agent-hook-token'] !== this.token |
| Runtime RPC Unix socket | src/main/runtime/runtime-rpc.ts |
request.authToken !== this.authToken |
| Daemon socket handshake | src/main/daemon/daemon-server.ts |
hello.token !== this.token |
Mitigating factors (already in place): all three servers bind to loopback (127.0.0.1 or a 0o600-permissioned Unix socket), and tokens are stored in 0o600 files, so exploitation requires local code execution. This is a defense-in-depth hardening, not a remotely-exploitable fix.
The fix
- New helper:
src/shared/timing-safe-token-compare.ts— wrapscrypto.timingSafeEqualwith length-mismatch handling that preserves constant-time behavior (a dummy self-comparison runs when lengths differ so the call count stays constant). - 3 call sites updated to use
timingSafeTokenCompare(expected, actual)instead of!==. - 8 unit tests covering identical tokens, same-length mismatches, prefix/truncation cases, empty strings, UUID-shaped tokens, and different-length inputs (ensuring no
RangeError).
No visual change
This is a security hardening with no UI or interaction behavior change.
Code review summary
- Cross-platform compatibility:
crypto.timingSafeEqualis a Node.js builtin available on all three target platforms (macOS, Linux, Windows). No platform-specific behavior. TheBuffer.fromencoding is explicitly set toutf8for deterministic byte representation. - SSH/remote/local compatibility: The agent-hooks server and daemon socket run on both local and remote (relay) hosts — the shared helper is imported from
src/shared/which is Electron-free, so it works identically in the relay context. The runtime RPC token is local-only (Unix socket / named pipe). - Agent/integration compatibility: No change to any agent, CLI, or git-provider integration surface. Token validation logic returns the same boolean result as before.
- Performance risk: Negligible.
timingSafeEqualis a single native call over a 36–48 byte buffer (UUID / hex token). The length-mismatch path adds one extratimingSafeEqual(expected, expected)call only for invalid tokens — valid tokens take the fast path. - Security risk: This change reduces security risk. The helper is the single source of truth for token comparison, making future boundaries easy to audit.
Testing
npx vitest run src/shared/timing-safe-token-compare.test.ts # 8/8 passed
npx vitest run src/main/daemon/daemon-server.test.ts # 21/21 passed
npx vitest run src/main/agent-hooks/server.test.ts # 224/224 passed
npx tsgo --noEmit -p config/tsconfig.node.json # no errors
npx oxlint <changed files> # 0 warnings, 0 errors
runtime-rpc.test.ts (3181 lines) was not run locally due to test-runner timeout, but the change is a single-line replacement where request.authToken is already type-checked as string two lines above, so timingSafeTokenCompare receives the same input and returns the same boolean result. CI will run the full suite.
ELI5
Secret token checks used normal string equality that can leak timing information. Comparisons use constant-time crypto so local attackers can’t recover tokens byte-by-byte.
📝 Walkthrough
Walkthrough
This change introduces a new shared utility, timingSafeTokenCompare, which performs constant-time string comparison for tokens using Node's crypto.timingSafeEqual, handling length mismatches by comparing the expected buffer against itself before returning false. A test suite covers equality, mismatch, prefix, empty-string, UUID, and hex-length cases. The utility is then integrated into three existing authorization checks—agent-hooks server HTTP request validation, daemon server hello-token validation, and runtime RPC authentication—replacing direct string equality/inequality comparisons.
Sequence Diagram(s)
Not applicable; changes are limited to utility integration into existing authorization checks without altering interaction flow structure.
Related PRs: None specified.
Suggested labels: security, refactor
Suggested reviewers: None specified.
🥕 A token compared byte by byte, No shortcuts taken, no timing to spy, Three servers now share this quiet defense, Constant in time, and firm in intent.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | ✅ Passed | The title clearly matches the main change: constant-time token comparison for security hardening. |
| Description check | ✅ Passed | The description covers the required sections and includes testing, security, and review details. |
| Docstring Coverage | ✅ Passed | No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. |
| Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
| Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
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 @coderabbitai help to get the list of available commands.
Greptile Summary
This PR replaces direct string equality (!==) with a new timingSafeTokenCompare helper (backed by crypto.timingSafeEqual) at all secret-token validation boundaries, closing a timing-attack vector where short-circuit comparison could allow byte-by-byte token recovery. All three originally identified boundaries plus DeviceRegistry, mobile-e2ee-auth-validation, and local-build-feed-server are updated.
src/shared/timing-safe-token-compare.ts: New helper always executestimingSafeEqualbefore the return expression's&&chains, so the constant-time path is taken regardless of length mismatches or non-string inputs.DeviceRegistry.validateToken: Switched fromArray.find(early-exit on first match) to a full loop so all devices are always scanned, preventing match-position leakage.- Tests: 8 unit tests for the new helper, plus integration tests for the daemon handshake (array token rejection) and device registry (same-length mismatch).
Confidence Score: 5/5
Safe to merge — the helper is correct for all ASCII token formats in use, the timingSafeEqual call always executes before any short-circuit logic, and all changed call sites preserve the original boolean semantics.
The implementation is straightforward: timingSafeEqual is unconditionally called at line 10 so the constant-time path always runs. All token formats in use are ASCII, the DeviceRegistry loop correctly avoids early-exit, and no behavioral regressions were identified across any of the seven updated call sites.
Files Needing Attention: No files require special attention.
Important Files Changed
| Filename | Overview |
|---|---|
| src/shared/timing-safe-token-compare.ts | New core helper wrapping crypto.timingSafeEqual; always executes the constant-time call before any short-circuit logic in the return expression; correct for ASCII (UUID/hex) tokens |
| src/main/runtime/device-registry.ts | validateToken changed from Array.find (early-exit) to a full loop so all devices are always scanned regardless of match position — correct timing-safe pattern for multi-entry lookups |
| src/main/local-builds/local-build-feed-server.ts | Token extracted from URL path and compared with timingSafeTokenCompare; also introduces decodeURIComponent on the pathname (noted in a previous review comment) |
| src/main/runtime/rpc/mobile-e2ee-auth-validation.ts | Post-lookup comparison replaced with timingSafeTokenCompare; timing protection for this path comes from resolveDevice (DeviceRegistry.validateToken) |
| src/main/daemon/daemon-server.ts | Single-line replacement for Unix-socket daemon handshake token check; companion test verifies array-typed tokens are rejected |
| src/main/runtime/runtime-rpc.ts | Two token comparisons updated — authToken check and per-request deviceToken cross-check; both replacements are semantically equivalent to the originals |
Reviews (2): Last reviewed commit: "fix(security): cover current token bound..." | Re-trigger Greptile