Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix(mcp): refuse unauthenticated HTTP on non-loopback hosts; optional bearer-token auth

ruvf54359456e6b
diff --git a/docs/dream-cycle/LEDGER.md b/docs/dream-cycle/LEDGER.md
index 4f65fa2459..16fc6f4567 100644
--- a/docs/dream-cycle/LEDGER.md
+++ b/docs/dream-cycle/LEDGER.md
@@ -215,7 +215,3 @@ as a first-class, high-priority candidate, not a background note.
**Note (2026-09-20):** the pre-09-14 backlog (#3086 through #3302, ~18 PRs) was fully cleared by human review on 2026-09-14 (confirmed via `search_pull_requests`: every one now shows `state: closed`) — the "0 of last 14 merged" bias condition from earlier nights no longer applies. Nights 09-15 (performance, #3330), 09-16 (security, #3339), 09-17 (intelligence, #3350), 09-18 (memory, #3352), and 09-19 (swarm, #3357) all ran and produced real branches/issues/draft PRs (verified via `git ls-remote`/`search_pull_requests`, not inferred) but aren't transcribed as rows here — same "ledger rows only reach `main` via PR merge" structural gap noted since 2026-08-19/09-03/09-05/09-09; none of the five is stale (>14d) as of tonight. Not backfilling their full rows here to avoid yet another copy stranded on yet another unmerged branch (per the 2026-09-03 note's own reasoning) — see their own PR bodies (#3330/#3339/#3350/#3352/#3357) for full detail.
| 2026-09-20 | performance | `UnifiedSwarmCoordinator.waitForTaskCompletion()`/`waitForQueuedTask()` busy-polled `state.tasks` via `setInterval(...,100)` despite the coordinator already extending `EventEmitter` and already firing `task.completed`/`task.failed` at every terminal task-status transition (`handleTaskComplete`, `handleTaskFail`'s non-retry branch, `cancelTask`) — the exact candidate 2026-09-15 scored 4.45/5 but deferred; tonight's independent research re-scored it 4.75/5 and selected it | #3377 | #3378 | yes | ACCEPT | 4 new discriminating tests, baseline-fails-3-of-4/candidate-passes-4-of-4 via stash isolation; real wall-clock benchmark 100.359ms→0.206ms mean (~487x, N=20); 234/234 full-suite both ways (230 pre-existing + 4 new), `tsc` clean; independent adversarial critique CONFIRMED-WITH-CAVEATS→fixed (missing `setMaxListeners` would have spammed `MaxListenersExceededWarning` at >10 concurrent waiters; fixed same session, re-verified) | 12f7a08e... | 09-15..09-19 (5 nights) all open/draft, none stale; pre-09-14 backlog (18 PRs) fully cleared 2026-09-14 |
-
-**Note (2026-10-01):** nights since the last transcribed row ran as follows (verified via `git ls-remote --heads origin "dream/*"` + `pull_request_read`, not inferred): 09-21 (security, #3384/#3385) **MERGED** 09-26; 09-22 (intelligence, #3394/#3395) **MERGED** 09-26; confirmed no-run gaps at 09-23, 09-25, 09-26 (no branch for any); 09-24 (off-cycle, non-rotation `github-safe.js` disclosure fix for issue #3411, #3412) **MERGED** 09-26; 09-27 (intelligence, #3475/#3476), 09-28 (memory, #3516/#3517), 09-29 (swarm, #3538/#3539), 09-30 (performance, #3562/#3563) all OPEN/draft, none stale. Scored 09-30's gist (STEP 1.2, embedded in #3562 since no gist tool was available that night either): 9/10 (lost 1 point for exceeding 1500 words). Tonight directly actions a HIGH-severity finding 09-30's own security scan flagged and deferred ("a strong candidate for a future security-DEEP night") — same-night research-to-fix turnaround one rotation later.
-
-| 2026-10-01 | security | `startHttpServer()` constructed `@claude-flow/mcp`'s `MCPServer` without ever setting `requireToolAuthorization`/`toolAuthorizer` — `ToolRegistry`'s auth check is `if (this.authorizer)`-gated and thus a no-op, so every one of 300+ registered MCP tools was callable unauthenticated whenever the HTTP server was reachable (`--host` is a live flag that can bind off loopback); same shape as CVE-2026-81735 (CVSS 10/10). Refuse to start on a non-loopback host unless `RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP=1` is explicitly set; loopback/stdio unaffected | #3598 | #3599 | yes | ACCEPT | 8/8 new discriminating unit tests (candidate) vs 5/8 fail (baseline, rebuilt dist) — baseline demonstrably starts serving `/health` unauthenticated on `--host 0.0.0.0`; 72/72 broader mcp-* sweep; full `@claude-flow/cli` local suite 4367/4505 (9 pre-existing failures, all 4 failing files confirmed pre-existing via stash-isolation); `@claude-flow/mcp` 81/81 unchanged; `tsc` clean both; independent adversarial critique CONFIRMED; `metaharness mcp-scan --fail-on high` clean. CI round-trip (disclosed, not hidden): the original e2e-CLI-spawn test design (same pattern as #2984/#2990, both already in `scripts/ci-test-baseline.txt`) failed in CI twice for environment reasons unrelated to the fix logic — resolved by rewriting as pure unit tests against the exported gate functions (no process spawn); CI green on the final commit after one confirmed-flake re-run (`@claude-flow/performance` benchmark, unrelated package) | f62fa76e... | 09-21/09-22/09-24 MERGED 09-26; 09-27..09-30 (4 nights) open/draft, none stale |
diff --git a/docs/dream-cycle/dream-gist-2026-10-01.md b/docs/dream-cycle/dream-gist-2026-10-01.md
deleted file mode 100644
index c1ee224393..0000000000
--- a/docs/dream-cycle/dream-gist-2026-10-01.md
+++ /dev/null
@@ -1,81 +0,0 @@
-# Security SOTA Report — 2026-10-01
-
-TL;DR: Ruflo's MCP HTTP transport (`v3/@claude-flow/cli/src/mcp-server.ts`, `startHttpServer()`) constructs its `@claude-flow/mcp` server without ever setting `requireToolAuthorization` or installing a `toolAuthorizer`. Since `ToolRegistry`'s authorization check is fully opt-in (`if (this.authorizer)`), every one of the CLI's 300+ registered MCP tools (`memory_*`, `hooks_*`, `agentdb_*`, `hive-mind_*`, ...) is callable with zero authorization whenever the server is reachable — and `--host` is a live, documented CLI flag that can bind it off loopback. This is structurally identical to CVE-2026-81735 (CVSS 10/10, disclosed against UI-TARS-desktop's `mcp-http-server` within the last 12 months): an optional auth hook the integrating CLI never wired, combined with a non-loopback-capable bind address. Tonight wires a fail-closed-by-default gate: the HTTP server now refuses to start on a non-loopback host unless the operator explicitly acknowledges the risk via `RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP=1`. Default (loopback) behavior is completely unchanged.
-
-## What's New in 2026
-
-| Finding | Source | Confidence |
-|---|---|---|
-| MCP spec (2026-07-28 rev.) leaves authorization OPTIONAL at the protocol/transport level ("SHOULD", not "MUST") | modelcontextprotocol.io/specification/2026-07-28/basic/authorization | A |
-| MCP Security Best Practices doc: once a server *does* implement authorization, it MUST verify every inbound request; local/HTTP servers SHOULD require an auth token | modelcontextprotocol.io/.../security_best_practices | A |
-| CVE-2026-81735 (CVSS 10/10): UI-TARS-desktop `mcp-http-server` defaulted to bind `::`, applied auth middleware only when a caller supplied it, exposing unauthenticated `run_command`/file-write MCP tools | Mend.io / OpenCVE / INCIBE-CERT, 2026 (cross-corroborated) | B |
-| CVE-2025-49596: MCP Inspector's unauthenticated `/sse` endpoint allowed remote RCE via unauthenticated proxy-to-stdio launch | crowdsec.net + trackers, 2025 | B |
-| OWASP LLM06 (Excessive Agency) + new OWASP Agentic Top 10 ASI02 "Tool Misuse and Exploitation" (2025-12-09) both prescribe per-call runtime authorization and least-privilege tool access as core mitigations | OWASP GenAI Security Project | A |
-
-## Ruflo Current Capability
-
-`@claude-flow/mcp`'s `ToolRegistry`/`MCPServer` already has a **fully-built, tested, opt-in fail-closed path**: `requireToolAuthorization: true` with no `toolAuthorizer` throws at construction (`server.ts:126-128`, exercised today only by the package's own `__tests__/mcp.test.ts`). Zero production callers anywhere in `v3/` ever set it. The CLI's stdio transport (the default) goes through a separate dispatcher with its own opt-in `PolicyEnforcer` (audit log + rate limit only, env-gated `RUFLO_MCP_ENFORCE_POLICY=1`, explicitly *not* an identity/authorization check, and explicitly *not* wired into the HTTP path per its own header comment) — so stdio has an audit trail but no permission check, and HTTP (the more exposure-prone path, given `--host`) had neither.
-
-## Competitor Comparison
-
-| Capability | LangGraph | AutoGen (MS) | CrewAI | OpenAI Agents SDK | Ruflo (before tonight) |
-|---|---|---|---|---|---|
-| Default tool-call authorization | Default-allow; HITL is a pattern you build (`interrupt_before`), not a default gate [B] | Default-allow; `approval_func` only vets if you supply one, logs a warning if you don't [B] | Default-allow; `human_input=True` is per-task opt-in, stdin-only (unattended-useless) [B] | Default-allow; `needsApproval` is an opt-in per-tool predicate (AI SDK 6, 2025) [B] | Default-allow (fail-open) — same industry norm, now closed for the HTTP transport |
-| Has the authorizer *hook* built at all | No dedicated tool-auth hook found | `approval_func` callback exists | `human_input` flag exists (interactive-only) | `needsApproval` predicate exists | `ToolAuthorizer` type + fail-closed constructor path exist — ruflo is ahead on primitives, behind on wiring them by default |
-| Documented CVE/incident for this exact shape | None found | None found | None found | None found | CVE-2026-81735 (closest external analog, different codebase) |
-
-Synthesis: **every framework researched is default-allow at the tool-execution layer** — this is a genuine industry-wide gap, not something ruflo is uniquely behind on. The MCP spec is the one place "secure by default" is explicitly normative, and it targets transport-level OAuth, leaving in-process tool-dispatch authorization (exactly `ToolAuthorizer`) unstandardized everywhere. Ruflo is unusual only in having *already built* the fail-closed hook and never wiring it — most peers never built the hook at all. That makes tonight's fix unusually cheap: no new primitive, just correct default wiring at one call site.
-
-## Hypothesis
-
-> Given an operator starts Ruflo's MCP server over HTTP transport with a non-loopback `--host`, when `startHttpServer()` is made to refuse to start (throw a clear, actionable error) instead of silently constructing an authorization-free `MCPServer`, then an unauthenticated remote client should no longer be able to reach any of the ~300+ registered MCP tools over the network by default, subject to: (1) default/loopback-host behavior is completely unchanged, (2) an explicit, documented env-var opt-out preserves today's behavior for operators who intentionally expose it behind their own auth layer, (3) the stdio transport (default, pipe-local, already governed by its own opt-in audit/rate-limit layer) is unaffected by this change.
-
-Frozen before evaluation began; not modified afterward.
-
-## Benchmarks
-
-Candidate: `v3/@claude-flow/cli/src/mcp-server.ts`, +36/-0 lines (one file, one conceptual change — adds a `LOOPBACK_HOSTS` set, an exported `isUnauthenticatedHttpAllowed()` helper, and a pre-construction guard in `startHttpServer()`). New test file `__tests__/mcp-http-nonloopback-auth-gate.test.ts` (6 tests: 3 unit tests on the helper, 3 end-to-end tests spawning the built CLI).
-
-Stash-isolated (baseline = `git stash` + rebuild `dist/` on just `mcp-server.ts`, new tests kept):
-- Baseline: 4/6 new tests fail — critically, the server **actually starts and serves `/health`** on `--host 0.0.0.0` with no authorization and no opt-out (the live vulnerability, reproduced directly, not inferred) — plus `isUnauthenticatedHttpAllowed` doesn't exist yet (import error) for the 3 unit tests.
-- Candidate: 6/6 pass — non-loopback host refused before the port ever opens; non-loopback host starts when `RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP=1`; loopback host (127.0.0.1) unaffected.
-- Broader sweep: 72/72 pass across 7 related `__tests__/mcp-*` files. `@claude-flow/mcp` package's own suite: 81/81 unchanged (zero changes made to that package — the fix is entirely at the CLI's one call site).
-- Full `@claude-flow/cli` suite: 4505 tests, 4367 passed, 9 failed, 129 skipped, across 329 files (4 files failed). All 4 failing files confirmed pre-existing via stash-isolation, unrelated to this candidate: `mcp-http-protocol-tools-2990.test.ts` (3 tests — this sandbox has no IPv6 support, `EAFNOSUPPORT` on `::1`, breaks an unrelated pre-existing dual-stack test identically on baseline); `mcp-policy-enforcer.test.ts` (3 tests — an "unwritable path" assumption that doesn't hold under this sandbox's filesystem permissions); `commands.test.ts` (3 tests — stale expectations tied to pre-existing issue #1425, "config reset/export not yet implemented"); `init-dual-native-2636-2637.test.ts` (fails to resolve the unbuilt sibling `@claude-flow/codex` package, the same "unbuilt sibling package" class of pre-existing environmental failure the ledger has logged repeatedly since 08-26). `tsc` clean on both `@claude-flow/cli` and `@claude-flow/mcp`.
-- Independent adversarial critique: **CONFIRMED**. Verified the gate is the sole `createMCPServer()` call site and covers both HTTP and WebSocket transports; verified `0.0.0.0`/non-canonical loopback spellings fail closed (conservative direction); verified the `RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP` self-bypass requires process-environment control, which already implies a stronger foothold than the vulnerability being closed; confirmed stdio's separate, lower-urgency scope (opt-in audit+rate-limit, no identity check, pipe-local) is a disclosed boundary, not a gap in tonight's fix. One process question raised (whether the stash-isolated e2e baseline was run against a rebuilt `dist/`, not a stale compiled binary) — confirmed yes, `npm run build` was run immediately after `git stash` and before the baseline test run.
-- `npx ruflo metaharness mcp-scan --fail-on high`: 3 pre-existing findings (2 medium risky-bash-allow-rules, 1 low unpinned-deps), none related to this change, no high-severity findings — reward-hack / policy-regression check clean.
-
-## Evaluation
-
-**Verdict: ACCEPT.** `evaluation_complete=true`, `effect_positive=true` (fail-open → fail-closed-by-default on the demonstrated vulnerable path), `no_material_regression=true` (all 9 full-suite failures confirmed pre-existing via stash-isolation), `tests_green=true` for the candidate's own discriminating tests, `reward_hack_clear=true` (metaharness mcp-scan clean, diff scope matches claim), `critic_clear=true` (independent adversarial critique CONFIRMED, no blocking issues), `witness_valid=true` (below), `receipt_reproducible=true` (stash-isolation procedure documented above, independently spot-checked by the critic for current-state behavior). Per STEP 14, this is evidence for human review, not autonomous promotion — PR opened as draft.
-
-## Darwin Results
-
-Not run. This is a binary security gate (refuse-to-start vs. start), not a continuous metric with tunable parameters worth a 3-generation search — the one knob (which hosts count as loopback) is a fixed, well-known set (`127.0.0.1`/`::1`/`localhost`), not something to evolve. Recorded as considered-and-declined, matching the same judgment call made on 2026-09-30's performance candidate.
-
-## SOTA Proof & Witness
-
-```
-Session commit: 0bd8e3142e5de68ca6075dad11b4ae2cfdaa0bec
-Report SHA256: 45577a1b72d89ff41afdfc4e92f5b3e17cf4eb6be1bacd6622a629441ef03a29
-Witness stamp: f62fa76eb21e643cee0c21e1596917856534e658b95e3b9e68a398c58d1a0ced
-Evaluation receipt: @claude-flow/cli full suite 4367/4505 passed, 9 failed (all 4 failing
- files confirmed pre-existing via stash-isolation); new discriminating
- suite 6/6 (candidate) vs 4/6 fail (baseline, rebuilt dist); @claude-flow/mcp
- 81/81 unchanged; tsc clean both packages
-Flywheel evidence identity: embedded in this gist + the linked issue/PR (Evaluation section) —
- no separate signed receipt file this session (ruvector harness
- flywheel gate/verify requires a JSON evidence schema not populated
- this session; recorded as structured OBSERVATION/MEASUREMENT/
- INFERENCE/DECISION text instead of fabricating a receipt shape)
-Darwin lineage identity: not run (see Darwin Results — binary gate, no tunable parameter)
-```
-
-Verifier procedure: take the report content as it existed immediately before this Witness
-section was written in (the file `/tmp/dream-gist-2026-10-01.md`), compute SHA256, concatenate
-with the session commit, compute SHA256 again — result must equal the witness stamp above.
-
-## Recommended Next Steps
-
-1. Consider whether the stdio transport's `PolicyEnforcer` (audit+rate-limit only) should grow an actual identity/permission check analogous to `ToolAuthorizer` — today stdio has logging but no "who is allowed to call what," same gap class, lower urgency since stdio is pipe-local by construction.
-2. `createMCPServer()`'s `requireToolAuthorization`/`toolAuthorizer` parameters are production-ready but have zero real authorizer implementations anywhere in `v3/` (only the package's own tests exercise them) — a future night could build one real `ToolAuthorizer` (e.g., a shared-secret bearer-token check) for operators who need actual remote MCP access rather than just a refuse-to-start guard.
-3. Audit other `createMCPServer`/`MCPServerManager` call sites (programmatic API, tests, any future SDK entry point) to confirm none of them construct a non-loopback HTTP server bypassing tonight's CLI-level gate — tonight's fix is scoped to the one production call site in `mcp-server.ts`.
diff --git a/v3/@claude-flow/cli/README.md b/v3/@claude-flow/cli/README.md
index 0023469eb3..0cc9d6b37c 100644
--- a/v3/@claude-flow/cli/README.md
+++ b/v3/@claude-flow/cli/README.md
@@ -193,6 +193,28 @@ npm install -g ruflo@latest
claude mcp add claude-flow -- npx ruflo@latest mcp start
```
+#### HTTP transport security
+
+`ruflo mcp start -t http` exposes every registered tool over HTTP (`/rpc`, `/mcp`, `/ws`). The default `stdio` transport is not affected.
+
+| Setting | Effect |
+|---|---|
+| `RUFLO_MCP_HTTP_TOKEN=<token>` | Require `Authorization: Bearer <token>` on every request. Failure is a bare `401`. The token is compared in constant time and is never logged. Prefer this over `--auth-token`, which is visible in `ps`. |
+| `--auth-token-file <path>` | Read the token from a file (one line). Takes precedence over the env var. |
+| `--auth-token <token>` | Same, on the command line (visible in argv; highest precedence). |
+| `RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP=1` | Allow an unauthenticated bind to a non-loopback `--host`. Only for a trusted network boundary or an authenticating reverse proxy. |
+
+A token must be 16-512 printable ASCII characters (no spaces). `GET /health` stays public and returns only `{"status":"ok"}` when a token is set. Tokens are supported for `-t http` only; `-t websocket` rejects one.
+
+| `--host` | no token | token set |
+|---|---|---|
+| `localhost`, `127.0.0.1`, `::1` | starts, **unauthenticated** | starts, token required |
+| anything else (`0.0.0.0`, `::`, a LAN IP, `127.0.0.2`, `[::1]`, `LOCALHOST`) | **refuses to start** unless `RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP=1` | starts, token required |
+
+Without a token, a loopback server is still unauthenticated: any process on the machine, and any web page that can reach it via DNS rebinding, can call tools. Set `RUFLO_MCP_HTTP_TOKEN` whenever the HTTP transport is used.
+
+**Upgrading:** binding off loopback (for example `--host 0.0.0.0` in Docker) now needs a token or the opt-out above; otherwise the server exits with an error.
+
---
## What You Get
diff --git a/v3/@claude-flow/cli/__tests__/mcp-http-nonloopback-auth-gate.test.ts b/v3/@claude-flow/cli/__tests__/mcp-http-nonloopback-auth-gate.test.ts
index 9bd354ef4b..8199b43cc5 100644
--- a/v3/@claude-flow/cli/__tests__/mcp-http-nonloopback-auth-gate.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mcp-http-nonloopback-auth-gate.test.ts
@@ -1,100 +1,227 @@
-// Dream Cycle 2026-10-01 (security): the MCP HTTP transport's
-// `startHttpServer()` called `createMCPServer()` without ever setting
-// `requireToolAuthorization` or installing a `toolAuthorizer`. Since
-// @claude-flow/mcp's tool-call authorization is fully opt-in
-// (ToolRegistry.authorizer is only consulted `if (this.authorizer)`), every
-// one of the CLI's 300+ registered MCP tools (memory_*, hooks_*, agentdb_*,
-// hive-mind_*, ...) was callable with zero authorization check whenever the
-// server was reachable — and `--host` is a live, user-facing flag that can
-// bind it off loopback. This is the same shape as CVE-2026-81735 (CVSS
-// 10/10, UI-TARS-desktop mcp-http-server): an optional auth hook the
-// integrating CLI never wired, combined with a non-loopback-capable bind.
+// Dream Cycle 2026-10-01 (security) + follow-up: the MCP HTTP server
+// (`ruflo mcp start -t http`) used to start with no authentication at all on
+// any host. Two controls close that for the cases a configuration can express:
//
-// Fix: `startHttpServer()` now refuses to start when the configured host is
-// not loopback (localhost/127.0.0.1/::1) unless the operator explicitly sets
-// RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP=1. Default/loopback behavior (the
-// common case, exercised by mcp-http-foreground-2984 and
-// mcp-http-protocol-tools-2990) is unchanged.
+// 1. startHttpServer() refuses a NON-loopback --host unless the request path
+// is authenticated (RUFLO_MCP_HTTP_TOKEN / --auth-token-file) or the
+// operator explicitly sets RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP=1.
+// 2. With a token, @claude-flow/mcp's HTTP transport requires
+// `Authorization: Bearer <token>` on every request.
//
-// These are pure, synchronous unit tests against the three exported
-// functions that make up the gate's full decision contract. An earlier
-// version of this file instead spawned the built CLI end-to-end
-// (node bin/cli.js mcp start ...), matching the pattern
-// mcp-http-foreground-2984.test.ts/mcp-http-protocol-tools-2990.test.ts use
-// — but this repo's CI "Test Suite" job never builds @claude-flow/cli's own
-// dist/ (only @claude-flow/security and @claude-flow/cli-core get a
-// targeted build step there, per .github/workflows/ci.yml), which is why
-// those two existing files are both already listed in
-// scripts/ci-test-baseline.txt as known-failing in CI. Rather than add a
-// third entry to that baseline (its own header: "Never add entries to make
-// a regression green"), this file tests the real exported decision logic
-// directly — no process spawn, no port bind, no build dependency — which
-// fully pins down the behavior these manual end-to-end checks verified
-// during development (see the PR/issue evidence: baseline-fails/
-// candidate-passes via git-stash, a live spawned server demonstrably
-// serving /health unauthenticated pre-fix and refusing to start post-fix).
-
-import { describe, expect, it } from 'vitest';
+// Loopback WITHOUT a token stays unauthenticated by design (any local process
+// can call tools) - that is documented, not closed.
+//
+// The wiring tests drive the real MCPServerManager.start() (the entry the CLI
+// uses) with @claude-flow/mcp mocked, so they assert the actual decision made
+// in startHttpServer: delete the `throw` there and the refusal tests fail.
+// Transport-level enforcement is tested in
+// v3/@claude-flow/mcp/__tests__/http-transport-auth.test.ts.
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+const createMCPServer = vi.fn();
+
+vi.mock('@claude-flow/mcp', () => ({
+ createMCPServer: (...args: unknown[]) => createMCPServer(...args),
+}));
+vi.mock('../src/mcp-client.js', () => ({
+ listMCPTools: () => [],
+ callMCPTool: async () => ({}),
+}));
+
import {
+ MCPServerManager,
isLoopbackHost,
isUnauthenticatedHttpAllowed,
+ resolveMcpHttpAuthToken,
shouldRefuseUnauthenticatedHttp,
} from '../src/mcp-server.js';
+const TOKEN = 'correct-horse-battery-staple-42';
+const OPT_OUT = 'RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP';
+
+let tmp: string;
+let managers: MCPServerManager[] = [];
+const savedEnv = { ...process.env };
+
+function lanIp(): string {
+ for (const addrs of Object.values(os.networkInterfaces())) {
+ for (const a of addrs ?? []) if (a.family === 'IPv4' && !a.internal) return a.address;
+ }
+ return '192.168.1.5';
+}
+
+function manager(options: ConstructorParameters<typeof MCPServerManager>[0]): MCPServerManager {
+ const m = new MCPServerManager({
+ transport: 'http',
+ port: 39000 + Math.floor(Math.random() * 1000),
+ pidFile: path.join(tmp, 'mcp.pid'),
+ logFile: path.join(tmp, 'mcp.log'),
+ ...options,
+ });
+ m.on('error', () => { /* start() rethrows; this only stops the EventEmitter 'error' rethrow */ });
+ managers.push(m);
+ return m;
+}
+
+beforeEach(() => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-auth-gate-'));
+ delete process.env[OPT_OUT];
+ delete process.env.RUFLO_MCP_HTTP_TOKEN;
+ createMCPServer.mockReset();
+ createMCPServer.mockImplementation(() => ({
+ registerTools: () => ({ failed: [] }),
+ start: async () => {},
+ stop: async () => {},
+ }));
+});
+
+afterEach(async () => {
+ for (const m of managers) { try { await m.stop(); } catch { /* not started */ } }
+ managers = [];
+ process.env = { ...savedEnv };
+ fs.rmSync(tmp, { recursive: true, force: true });
+});
+
+describe('MCPServerManager.start() - non-loopback hosts are refused without auth', () => {
+ const hosts = ['0.0.0.0', '::', lanIp()];
+
+ for (const host of hosts) {
+ it(`refuses host ${host} with the documented message and never builds a server`, async () => {
+ await expect(manager({ host }).start()).rejects.toThrow(/Refusing to start the MCP HTTP server on non-loopback host/);
+ await expect(manager({ host }).start()).rejects.toThrow(/RUFLO_MCP_HTTP_TOKEN/);
+ await expect(manager({ host }).start()).rejects.toThrow(/RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP=1/);
+ expect(createMCPServer).not.toHaveBeenCalled();
+ });
+
+ it(`starts host ${host} when the explicit opt-out is set (no auth configured)`, async () => {
+ process.env[OPT_OUT] = '1';
+ await manager({ host }).start();
+ expect(createMCPServer).toHaveBeenCalledTimes(1);
+ expect(createMCPServer.mock.calls[0][0].auth).toBeUndefined();
+ });
+
+ it(`starts host ${host} with a token and no opt-out, and wires the token into the transport`, async () => {
+ await manager({ host, authToken: TOKEN }).start();
+ expect(createMCPServer).toHaveBeenCalledTimes(1);
+ const cfg = createMCPServer.mock.calls[0][0];
+ expect(cfg.host).toBe(host);
+ expect(cfg.auth).toEqual({ enabled: true, method: 'token', tokens: [TOKEN] });
+ });
+ }
+
+ it('an invalid opt-out value does not lift the gate', async () => {
+ for (const v of ['0', 'false', 'yes', '']) {
+ process.env[OPT_OUT] = v;
+ await expect(manager({ host: '0.0.0.0' }).start()).rejects.toThrow(/Refusing to start/);
+ }
+ expect(createMCPServer).not.toHaveBeenCalled();
+ });
+
+ it('a token with the standalone websocket transport is rejected (no working check there)', async () => {
+ await expect(manager({ transport: 'websocket', host: '0.0.0.0', authToken: TOKEN }).start())
+ .rejects.toThrow(/only supported with --transport http/);
+ expect(createMCPServer).not.toHaveBeenCalled();
+ });
+
+ it('websocket transport on a non-loopback host is still refused without the opt-out', async () => {
+ await expect(manager({ transport: 'websocket', host: '0.0.0.0' }).start()).rejects.toThrow(/Refusing to start/);
+ });
+});
+
+describe('MCPServerManager.start() - loopback hosts start', () => {
+ for (const host of ['localhost', '127.0.0.1', '::1']) {
+ it(`starts ${host} with no token and no opt-out (unauthenticated, as documented)`, async () => {
+ await manager({ host }).start();
+ expect(createMCPServer).toHaveBeenCalledTimes(1);
+ expect(createMCPServer.mock.calls[0][0].auth).toBeUndefined();
+ });
+
+ it(`starts ${host} with a token and enforces it`, async () => {
+ await manager({ host, authToken: TOKEN }).start();
+ expect(createMCPServer.mock.calls[0][0].auth).toMatchObject({ enabled: true, tokens: [TOKEN] });
+ });
+ }
+
+ it('does not leak the token through the "starting" event', async () => {
+ const m = manager({ host: '127.0.0.1', authToken: TOKEN });
+ const seen: string[] = [];
+ m.on('starting', (d) => seen.push(JSON.stringify(d)));
+ await m.start();
+ expect(seen.join('')).not.toContain(TOKEN);
+ expect(seen.join('')).toContain('[redacted]');
+ });
+});
+
describe('isLoopbackHost', () => {
it('is true for exactly the three recognized loopback spellings', () => {
- expect(isLoopbackHost('localhost')).toBe(true);
- expect(isLoopbackHost('127.0.0.1')).toBe(true);
- expect(isLoopbackHost('::1')).toBe(true);
+ for (const h of ['localhost', '127.0.0.1', '::1']) expect(isLoopbackHost(h)).toBe(true);
});
- it('is false (fails closed) for anything not spelled exactly one of those three', () => {
- expect(isLoopbackHost('0.0.0.0')).toBe(false);
- expect(isLoopbackHost('::')).toBe(false);
- expect(isLoopbackHost('192.168.1.5')).toBe(false);
- // Case variants and bracketed forms are NOT normalized — conservative
- // (fail-closed) direction: an operator relying on one of these would
- // need the explicit opt-out, not a silent bypass of the gate.
- expect(isLoopbackHost('LOCALHOST')).toBe(false);
- expect(isLoopbackHost('[::1]')).toBe(false);
- expect(isLoopbackHost('0:0:0:0:0:0:0:1')).toBe(false);
+ it('fails closed for everything else, including other loopback spellings', () => {
+ // 127.0.0.2, [::1], LOCALHOST and 0:0:0:0:0:0:0:1 are loopback to the OS
+ // but are not normalized: they need the token or the opt-out.
+ for (const h of ['0.0.0.0', '::', '192.168.1.5', '127.0.0.2', '[::1]', 'LOCALHOST', '0:0:0:0:0:0:0:1', '']) {
+ expect(isLoopbackHost(h)).toBe(false);
+ }
});
});
describe('isUnauthenticatedHttpAllowed', () => {
- it('is false when unset', () => {
+ it('only the documented values opt out', () => {
expect(isUnauthenticatedHttpAllowed({})).toBe(false);
+ for (const v of ['yes', '0', 'false', 'TRUE', ' 1']) {
+ expect(isUnauthenticatedHttpAllowed({ [OPT_OUT]: v })).toBe(false);
+ }
+ expect(isUnauthenticatedHttpAllowed({ [OPT_OUT]: '1' })).toBe(true);
+ expect(isUnauthenticatedHttpAllowed({ [OPT_OUT]: 'true' })).toBe(true);
});
+});
- it('is false for arbitrary truthy-looking strings', () => {
- expect(isUnauthenticatedHttpAllowed({ RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: 'yes' })).toBe(false);
- expect(isUnauthenticatedHttpAllowed({ RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: '0' })).toBe(false);
- expect(isUnauthenticatedHttpAllowed({ RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: 'false' })).toBe(false);
- });
-
- it('is true only for the documented opt-out values', () => {
- expect(isUnauthenticatedHttpAllowed({ RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: '1' })).toBe(true);
- expect(isUnauthenticatedHttpAllowed({ RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: 'true' })).toBe(true);
+describe('shouldRefuseUnauthenticatedHttp - the decision matrix', () => {
+ it.each([
+ // host, optOut, authenticated, refuse?
+ ['0.0.0.0', false, false, true],
+ ['0.0.0.0', true, false, false],
+ ['0.0.0.0', false, true, false],
+ ['0.0.0.0', true, true, false],
+ ['127.0.0.1', false, false, false],
+ ['localhost', false, false, false],
+ ['::1', false, false, false],
+ ['127.0.0.2', false, false, true],
+ ])('host=%s optOut=%s authenticated=%s -> refuse=%s', (host, optOut, authenticated, refuse) => {
+ const env = optOut ? { [OPT_OUT]: '1' } : {};
+ expect(shouldRefuseUnauthenticatedHttp(host, env, authenticated)).toBe(refuse);
});
});
-describe('shouldRefuseUnauthenticatedHttp (the full startHttpServer gate)', () => {
- it('refuses a non-loopback host with no opt-out — the vulnerability this candidate closes', () => {
- expect(shouldRefuseUnauthenticatedHttp('0.0.0.0', {})).toBe(true);
+describe('resolveMcpHttpAuthToken', () => {
+ it('returns undefined when nothing is configured (env unset or empty)', () => {
+ expect(resolveMcpHttpAuthToken({}, {})).toBeUndefined();
+ expect(resolveMcpHttpAuthToken({}, { RUFLO_MCP_HTTP_TOKEN: '' })).toBeUndefined();
});
- it('allows a non-loopback host when the explicit opt-out is set', () => {
- expect(
- shouldRefuseUnauthenticatedHttp('0.0.0.0', { RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: '1' }),
- ).toBe(false);
+ it('reads the env var, a file (trailing newline stripped), or an explicit flag, in flag > file > env order', () => {
+ expect(resolveMcpHttpAuthToken({}, { RUFLO_MCP_HTTP_TOKEN: TOKEN })).toBe(TOKEN);
+ expect(resolveMcpHttpAuthToken({ tokenFile: '/x' }, { RUFLO_MCP_HTTP_TOKEN: 'e'.repeat(20) }, () => `${TOKEN}\n`)).toBe(TOKEN);
+ expect(resolveMcpHttpAuthToken({ token: TOKEN, tokenFile: '/x' }, {}, () => 'f'.repeat(20))).toBe(TOKEN);
});
- it('allows every loopback host regardless of the opt-out — default behavior is unchanged', () => {
- for (const host of ['localhost', '127.0.0.1', '::1']) {
- expect(shouldRefuseUnauthenticatedHttp(host, {})).toBe(false);
- expect(
- shouldRefuseUnauthenticatedHttp(host, { RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: '1' }),
- ).toBe(false);
+ it('rejects malformed tokens without echoing them (fail closed, never "no auth")', () => {
+ for (const bad of ['short', 'has space in the middle of it', 'ünïcödé-token-ünïcödé-token', 'x'.repeat(513), 'tab\there-and-more-chars']) {
+ let message = '';
+ try { resolveMcpHttpAuthToken({}, { RUFLO_MCP_HTTP_TOKEN: bad }); } catch (e) { message = (e as Error).message; }
+ expect(message).toMatch(/Invalid MCP HTTP auth token from RUFLO_MCP_HTTP_TOKEN/);
+ expect(message).not.toContain(bad);
}
+ expect(() => resolveMcpHttpAuthToken({ token: '' }, {})).toThrow(/Invalid MCP HTTP auth token/);
+ });
+
+ it('an unreadable token file is an error, not "no token"', () => {
+ expect(() => resolveMcpHttpAuthToken({ tokenFile: '/nope' }, {}, () => { throw new Error('ENOENT /nope'); }))
+ .toThrow(/Could not read the MCP HTTP auth token file/);
});
});
diff --git a/v3/@claude-flow/cli/__tests__/mcp-stdio-no-sibling-kill.test.ts b/v3/@claude-flow/cli/__tests__/mcp-stdio-no-sibling-kill.test.ts
index 4cd59551c7..bba0e164c8 100644
--- a/v3/@claude-flow/cli/__tests__/mcp-stdio-no-sibling-kill.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mcp-stdio-no-sibling-kill.test.ts
@@ -57,6 +57,8 @@ vi.mock('../src/mcp-server.js', () => ({
getMCPServerStatus: vi.fn(async () => h.status),
filterAdvertisedMcpTools: (tools: unknown[]) => tools,
parseMcpToolSelection: () => 'all',
+ resolveMcpHttpAuthToken: () => undefined,
+ isLoopbackHost: () => true,
}));
// mcp-client.js pulls in the full tool registry; the start path never needs it.
diff --git a/v3/@claude-flow/cli/src/commands/mcp.ts b/v3/@claude-flow/cli/src/commands/mcp.ts
index 40291b85fc..fb4285ff0d 100644
--- a/v3/@claude-flow/cli/src/commands/mcp.ts
+++ b/v3/@claude-flow/cli/src/commands/mcp.ts
@@ -18,6 +18,8 @@ import {
stopMCPServer,
getMCPServerStatus,
type MCPServerOptions,
+ resolveMcpHttpAuthToken,
+ isLoopbackHost,
type MCPServerStatus,
filterAdvertisedMcpTools,
parseMcpToolSelection,
@@ -87,6 +89,16 @@ const startCommand: Command = {
description: 'HTTP request timeout in milliseconds (default 30000; env RUFLO_MCP_REQUEST_TIMEOUT_MS)',
type: 'number'
},
+ {
+ name: 'auth-token-file',
+ description: 'Read the HTTP bearer token from this file (http transport). Preferred over --auth-token; env RUFLO_MCP_HTTP_TOKEN also works',
+ type: 'string'
+ },
+ {
+ name: 'auth-token',
+ description: 'HTTP bearer token (16+ printable ASCII chars). Visible in argv/ps - prefer RUFLO_MCP_HTTP_TOKEN or --auth-token-file',
+ type: 'string'
+ },
{
name: 'daemon',
short: 'd',
@@ -106,6 +118,8 @@ const startCommand: Command = {
{ command: 'claude-flow mcp start', description: 'Start with defaults (stdio)' },
{ command: 'claude-flow mcp start -p 8080 -t http', description: 'Start HTTP server' },
{ command: 'claude-flow mcp start -t http --request-timeout-ms 120000', description: 'Allow slower cold-start HTTP tools' },
+ { command: 'RUFLO_MCP_HTTP_TOKEN=<16+ chars> claude-flow mcp start -t http', description: 'HTTP server requiring "Authorization: Bearer <token>" on every request (except GET /health)' },
+ { command: 'RUFLO_MCP_HTTP_TOKEN=<16+ chars> claude-flow mcp start -t http --host 0.0.0.0', description: 'Non-loopback bind: allowed only with a token (or RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP=1)' },
{ command: 'claude-flow mcp start -d', description: 'Start as daemon' },
{ command: 'claude-flow mcp start -f', description: 'Force restart (kill existing)' }
],
@@ -125,6 +139,16 @@ const startCommand: Command = {
output.printError('Request timeout must be an integer from 1 to 3600000 milliseconds');
return { success: false, exitCode: 1 };
}
+ let authToken: string | undefined;
+ try {
+ authToken = resolveMcpHttpAuthToken({
+ token: (ctx.flags.authToken ?? ctx.flags['auth-token']) as string | undefined,
+ tokenFile: (ctx.flags.authTokenFile ?? ctx.flags['auth-token-file']) as string | undefined,
+ });
+ } catch (error) {
+ output.printError((error as Error).message);
+ return { success: false, exitCode: 1 };
+ }
const daemon = (ctx.flags.daemon as boolean) ?? false;
const force = (ctx.flags.force as boolean) ?? false;
@@ -186,6 +210,7 @@ const startCommand: Command = {
port,
tools: !tools || tools === 'all' ? 'all' : tools.split(','),
...(requestTimeoutMs === undefined ? {} : { requestTimeoutMs }),
+ ...(authToken ? { authToken } : {}),
daemonize: daemon,
};
@@ -245,6 +270,13 @@ const startCommand: Command = {
if (transport === 'http') {
output.writeln(output.dim(` Health: http://${host}:${port}/health`));
output.writeln(output.dim(` RPC: http://${host}:${port}/rpc`));
+ if (authToken) {
+ output.writeln(output.dim(' Auth: bearer token required (Authorization: Bearer <token>); /health is public'));
+ } else if (isLoopbackHost(host)) {
+ output.printWarning('No auth token set: any local process (and DNS-rebinding web pages) can call tools. Set RUFLO_MCP_HTTP_TOKEN to require a bearer token.');
+ } else {
+ output.printWarning('Running UNAUTHENTICATED on a non-loopback host (RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP is set).');
+ }
} else if (transport === 'websocket') {
output.writeln(output.dim(` WebSocket: ws://${host}:${port}/ws`));
}
diff --git a/v3/@claude-flow/cli/src/mcp-server.ts b/v3/@claude-flow/cli/src/mcp-server.ts
index 984bf5cc31..9f6903bc5f 100644
--- a/v3/@claude-flow/cli/src/mcp-server.ts
+++ b/v3/@claude-flow/cli/src/mcp-server.ts
@@ -57,6 +57,12 @@ export interface MCPServerOptions {
daemonize?: boolean;
timeout?: number;
requestTimeoutMs?: number;
+ /**
+ * Bearer token every HTTP request must present (`Authorization: Bearer <token>`).
+ * http transport only. Prefer RUFLO_MCP_HTTP_TOKEN / a token file over this
+ * field's CLI flag so the secret stays out of argv. Never logged or emitted.
+ */
+ authToken?: string;
}
/**
@@ -198,22 +204,67 @@ export function isUnauthenticatedHttpAllowed(env: NodeJS.ProcessEnv = process.en
/**
* The full startHttpServer() authorization gate, as a pure function:
- * true means "refuse to start" (see the thrown error for why). Extracted
- * so the exact decision contract (not just its two inputs individually) is
- * directly unit-testable without spawning a process or binding a port.
- * Exported for tests.
+ * true means "refuse to start" (see the thrown error for why).
+ *
+ * A non-loopback bind is allowed when requests are authenticated (a bearer
+ * token is configured on the http transport) or the operator explicitly opts
+ * out with RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP=1. Loopback binds are never
+ * refused, with or without a token. Exported for tests.
*/
export function shouldRefuseUnauthenticatedHttp(
host: string,
env: NodeJS.ProcessEnv = process.env,
+ authenticated = false,
): boolean {
- return !isLoopbackHost(host) && !isUnauthenticatedHttpAllowed(env);
+ return !isLoopbackHost(host) && !authenticated && !isUnauthenticatedHttpAllowed(env);
+}
+
+/** Printable ASCII without space (RFC 6750 token-ish), 16-512 chars. */
+const AUTH_TOKEN_PATTERN = /^[\x21-\x7e]{16,512}$/;
+
+/**
+ * Resolve the HTTP bearer token. Precedence: explicit value (CLI flag), token
+ * file, then RUFLO_MCP_HTTP_TOKEN. An unset/empty env var means "no token";
+ * a token that is set but malformed throws, so a typo can never silently
+ * start the server unauthenticated. Exported for tests.
+ */
+export function resolveMcpHttpAuthToken(
+ input: { token?: string; tokenFile?: string } = {},
+ env: NodeJS.ProcessEnv = process.env,
+ readFile: (p: string) => string = (p) => fs.readFileSync(p, 'utf8'),
+): string | undefined {
+ let raw: string | undefined;
+ let source = '';
+ if (input.token !== undefined) {
+ raw = input.token;
+ source = '--auth-token';
+ } else if (input.tokenFile !== undefined) {
+ source = '--auth-token-file';
+ try {
+ raw = readFile(input.tokenFile).replace(/\r?\n$/, '');
+ } catch {
+ throw new Error('Could not read the MCP HTTP auth token file given to --auth-token-file');
+ }
+ } else if (env.RUFLO_MCP_HTTP_TOKEN !== undefined && env.RUFLO_MCP_HTTP_TOKEN !== '') {
+ raw = env.RUFLO_MCP_HTTP_TOKEN;
+ source = 'RUFLO_MCP_HTTP_TOKEN';
+ }
+ if (raw === undefined) return undefined;
+ if (!AUTH_TOKEN_PATTERN.test(raw)) {
+ // The value is deliberately not echoed.
+ throw new Error(
+ `Invalid MCP HTTP auth token from ${source}: it must be 16-512 printable ASCII characters with no spaces`
+ );
+ }
+ return raw;
}
/**
* Default configuration
*/
-const DEFAULT_OPTIONS: Required<MCPServerOptions> = {
+type ResolvedMCPServerOptions = Required<Omit<MCPServerOptions, 'authToken'>> & { authToken?: string };
+
+const DEFAULT_OPTIONS: ResolvedMCPServerOptions = {
transport: 'stdio',
host: 'localhost',
port: 3000,
@@ -295,7 +346,7 @@ export function assessMcpSchemaOverhead(
* Manages the lifecycle of the MCP server process
*/
export class MCPServerManager extends EventEmitter {
- private options: Required<MCPServerOptions>;
+ private options: ResolvedMCPServerOptions;
private process?: ChildProcess;
private server?: Server;
private startTime?: Date;
@@ -367,7 +418,7 @@ export class MCPServerManager extends EventEmitter {
const startTime = performance.now();
this.startTime = new Date();
- this.emit('starting', { options: this.options });
+ this.emit('starting', { options: { ...this.options, authToken: this.options.authToken ? '[redacted]' : undefined } });
try {
if (this.options.transport === 'stdio') {
@@ -945,6 +996,33 @@ export class MCPServerManager extends EventEmitter {
* Start HTTP server in-process
*/
private async startHttpServer(): Promise<void> {
+ // Authorization gate first, before any import or bind: a refused start must
+ // not depend on (or touch) anything else.
+ const authToken = this.options.authToken || undefined;
+ if (authToken && this.options.transport !== 'http') {
+ // The standalone websocket transport has no working token check, so a
+ // token there would be a false promise of protection.
+ throw new Error('An MCP HTTP auth token is only supported with --transport http');
+ }
+ if (shouldRefuseUnauthenticatedHttp(this.options.host, process.env, !!authToken)) {
+ // No ToolAuthorizer is wired below: @claude-flow/mcp's tool-call
+ // authorization is fully opt-in (requireToolAuthorization/toolAuthorizer),
+ // so without this check every registered tool (memory_*, hooks_*,
+ // agentdb_*, hive-mind_*, ...) would be callable by any client that can
+ // reach this host:port, unauthenticated — the same shape as
+ // CVE-2026-81735 (CVSS 10/10, UI-TARS-desktop mcp-http-server: optional
+ // auth middleware never wired by the integrating CLI + a non-loopback
+ // bind). Loopback stays unaffected; this only gates an explicit
+ // non-default `--host`. A configured bearer token (below) lifts the gate.
+ throw new Error(
+ `Refusing to start the MCP HTTP server on non-loopback host "${this.options.host}": ` +
+ 'this server is unauthenticated unless a token is set, so every registered MCP tool ' +
+ 'would be reachable over the network. Set RUFLO_MCP_HTTP_TOKEN (or --auth-token-file) ' +
+ 'to require a bearer token, bind to a loopback host (127.0.0.1, ::1, or localhost), or set ' +
+ 'RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP=1 to acknowledge the risk and proceed ' +
+ '(e.g. when a trusted reverse proxy or network boundary already enforces auth).'
+ );
+ }
// Dynamically import the MCP server package
// FIX for issue #942: Use proper package import instead of broken relative path
const { createMCPServer } = await import('@claude-flow/mcp');
@@ -986,25 +1064,6 @@ export class MCPServerManager extends EventEmitter {
// Use one MCP server with two HTTP transports for the localhost default.
// Both loopback sockets therefore share sessions, tools, and notifications.
const dualLoopback = this.options.host === 'localhost';
- if (shouldRefuseUnauthenticatedHttp(this.options.host)) {
- // No ToolAuthorizer is wired below: @claude-flow/mcp's tool-call
- // authorization is fully opt-in (requireToolAuthorization/toolAuthorizer),
- // so without this check every registered tool (memory_*, hooks_*,
- // agentdb_*, hive-mind_*, ...) would be callable by any client that can
- // reach this host:port, unauthenticated — the same shape as
- // CVE-2026-81735 (CVSS 10/10, UI-TARS-desktop mcp-http-server: optional
- // auth middleware never wired by the integrating CLI + a non-loopback
- // bind). Loopback stays unaffected; this only gates an explicit
- // non-default `--host`.
- throw new Error(
- `Refusing to start the MCP HTTP server on non-loopback host "${this.options.host}": ` +
- 'this server has no per-tool authorization by default, so every registered MCP tool ' +
- 'would be reachable unauthenticated over the network. Bind to a loopback host ' +
- '(127.0.0.1, ::1, or localhost) instead, or set ' +
- 'RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP=1 to acknowledge the risk and proceed ' +
- '(e.g. when a trusted reverse proxy or network boundary already enforces auth).'
- );
- }
const mcpServer = createMCPServer(
{
name: 'Claude-Flow MCP Server V3',
@@ -1016,6 +1075,9 @@ export class MCPServerManager extends EventEmitter {
enableMetrics: true,
enableCaching: true,
requestTimeout: this.options.requestTimeoutMs,
+ auth: authToken
+ ? { enabled: true, method: 'token', tokens: [authToken] }
+ : undefined,
},
logger
);
diff --git a/v3/@claude-flow/mcp/__tests__/http-transport-auth.test.ts b/v3/@claude-flow/mcp/__tests__/http-transport-auth.test.ts
new file mode 100644
index 0000000000..9da12213da
--- /dev/null
+++ b/v3/@claude-flow/mcp/__tests__/http-transport-auth.test.ts
@@ -0,0 +1,316 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import * as net from 'node:net';
+import type { AddressInfo } from 'node:net';
+import type { Server } from 'node:http';
+
+const cryptoSpy = vi.hoisted(() => ({ timingSafeEqual: vi.fn() }));
+vi.mock('crypto', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('crypto')>();
+ cryptoSpy.timingSafeEqual.mockImplementation(actual.timingSafeEqual);
+ return { ...actual, default: actual, timingSafeEqual: cryptoSpy.timingSafeEqual };
+});
+
+import { HttpTransport } from '../src/transport/http.js';
+import type { ILogger } from '../src/types.js';
+
+const TOKEN = 'correct-horse-battery-staple-42';
+const RPC = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'system_info' } };
+
+const logger: ILogger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
+let transport: HttpTransport | undefined;
+let handled: number;
+let base: string;
+let port: number;
+
+async function start(auth: unknown, extra: Record<string, unknown> = {}): Promise<void> {
+ handled = 0;
+ transport = new HttpTransport(logger, {
+ host: '127.0.0.1',
+ port: 0,
+ auth: auth as never,
+ corsEnabled: true,
+ corsOrigins: ['https://app.example'],
+ ...extra,
+ });
+ transport.onRequest(async (r) => {
+ handled++;
+ return { jsonrpc: '2.0', id: r.id, result: { ok: true } };
+ });
+ await transport.start();
+ port = ((transport as unknown as { server: Server }).server.address() as AddressInfo).port;
+ base = `http://127.0.0.1:${port}`;
+}
+
+const post = (headers: Record<string, string> = {}, path = '/rpc', body: unknown = RPC) =>
+ fetch(base + path, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...headers },
+ body: JSON.stringify(body),
+ });
+
+/** Raw HTTP/1.1 so we control header duplication, casing and odd bytes. */
+function raw(request: string): Promise<{ status: number; head: string; body: string }> {
+ return new Promise((resolve, reject) => {
+ const sock = net.connect(port, '127.0.0.1', () => sock.write(request));
+ let buf = '';
+ sock.on('data', (d) => (buf += d.toString('latin1')));
+ sock.on('error', reject);
+ sock.on('close', () => {
+ const [head, ...rest] = buf.split('\r\n\r\n');
+ resolve({ status: Number(/^HTTP\/1\.1 (\d+)/.exec(head)?.[1] ?? 0), head, body: rest.join('\r\n\r\n') });
+ });
+ setTimeout(() => sock.destroy(), 1500);
+ });
+}
+const rawPost = (headerLines: string[], path = '/rpc', method = 'POST') => {
+ const body = JSON.stringify(RPC);
+ return raw(
+ `${method} ${path} HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\n` +
+ `Content-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n${headerLines.join('\r\n')}${headerLines.length ? '\r\n' : ''}\r\n${body}`,
+ );
+};
+
+afterEach(async () => {
+ await transport?.stop();
+ transport = undefined;
+ vi.clearAllMocks();
+});
+
+describe('HTTP transport bearer auth', () => {
+ beforeEach(async () => {
+ await start({ enabled: true, method: 'token', tokens: [TOKEN] });
+ });
+
+ it('rejects a request with no Authorization header, without dispatching', async () => {
+ const res = await post();
+ expect(res.status).toBe(401);
+ expect(handled).toBe(0);
+ });
+
+ it('401 body has no detail about what was wrong and never echoes the token', async () => {
+ const bodies = await Promise.all([
+ post(),
+ post({ authorization: 'Bearer wrong-token-wrong-token' }),
+ post({ authorization: `Basic ${TOKEN}` }),
+ post({ authorization: 'Bearer' }),
+ ].map(async (p) => (await p).text()));
+ expect(new Set(bodies).size).toBe(1);
+ expect(JSON.parse(bodies[0])).toEqual({ jsonrpc: '2.0', id: null, error: { code: -32001, message: 'Unauthorized' } });
+ for (const b of bodies) expect(b).not.toContain(TOKEN);
+ expect(handled).toBe(0);
+ });
+
+ it('rejects a wrong token, including prefixes, extensions and case changes of the right one', async () => {
+ for (const t of ['wrong-token-wrong-token', TOKEN.slice(0, -1), `${TOKEN}x`, TOKEN.toUpperCase(), '']) {
+ expect((await post({ authorization: `Bearer ${t}` })).status).toBe(401);
+ }
+ expect(handled).toBe(0);
+ });
+
+ it('accepts the right token and dispatches', async () => {
+ const res = await post({ authorization: `Bearer ${TOKEN}` });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toMatchObject({ id: 1, result: { ok: true } });
+ expect(handled).toBe(1);
+ });
+
+ it('also guards /mcp (POST and the SSE GET) and /info', async () => {
+ expect((await post({}, '/mcp')).status).toBe(401);
+ expect((await fetch(`${base}/mcp`)).status).toBe(401);
+ expect((await fetch(`${base}/info`)).status).toBe(401);
+ expect((await fetch(`${base}/info`, { headers: { authorization: `Bearer ${TOKEN}` } })).status).toBe(200);
+ expect((await post({ authorization: `Bearer ${TOKEN}` }, '/mcp')).status).toBe(200);
+ });
+
+ it('rejects malformed Authorization headers', async () => {
+ for (const h of [`Bearer`, `Bearer `, `${TOKEN}`, `Token ${TOKEN}`, `Basic ${Buffer.from(TOKEN).toString('base64')}`, `Bearer${TOKEN}`, `Bearer `]) {
+ expect((await post({ authorization: h })).status).toBe(401);
+ }
+ expect(handled).toBe(0);
+ });
+
+ it('a unicode token never matches and never crashes the server', async () => {
+ // Sent as raw UTF-8 bytes (fetch itself refuses non-latin1 header values).
+ for (const t of ['tökén-tökén-tökén-tökén', '\u{1F511}'.repeat(8), `${TOKEN}́`]) {
+ const res = await raw(
+ `POST /rpc HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\nAuthorization: Bearer ${Buffer.from(t, 'utf8').toString('latin1')}\r\n\r\n{}`,
+ );
+ expect(res.status).toBe(401);
+ }
+ expect((await post({ authorization: `Bearer ${TOKEN}` })).status).toBe(200);
+ });
+
+ it('supports a unicode token configured in code: exact bytes match, near-misses do not', async () => {
+ await transport!.stop();
+ const unicode = 'pässwörd-☃-token-0123456789';
+ await start({ enabled: true, method: 'token', tokens: [unicode] });
+ const sendRaw = (t: string) => raw(
+ `POST /rpc HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(JSON.stringify(RPC))}\r\nConnection: close\r\nAuthorization: Bearer ${Buffer.from(t, 'utf8').toString('latin1')}\r\n\r\n${JSON.stringify(RPC)}`,
+ );
+ // Node decodes header bytes as latin1, so a UTF-8 client never matches a
+ // non-ASCII token; that is why the CLI only accepts printable-ASCII tokens.
+ expect((await sendRaw('pässwörd-☃-token-0123456780')).status).toBe(401);
+ expect((await sendRaw('password-token-0123456789')).status).toBe(401);
+ });
+
+ it('compares tokens with crypto.timingSafeEqual (once per configured token, even on failure)', async () => {
+ cryptoSpy.timingSafeEqual.mockClear();
+ await post({ authorization: 'Bearer nope-nope-nope-nope' });
+ expect(cryptoSpy.timingSafeEqual).toHaveBeenCalledTimes(1);
+ const [a, b] = cryptoSpy.timingSafeEqual.mock.calls[0];
+ expect(a.length).toBe(b.length); // equal-length digests: no length leak
+ cryptoSpy.timingSafeEqual.mockClear();
+ await post({ authorization: `Bearer ${TOKEN}` });
+ expect(cryptoSpy.timingSafeEqual).toHaveBeenCalled();
+ });
+
+ it('never logs the token or the Authorization header', async () => {
+ await post({ authorization: 'Bearer wrong-token-wrong-token' });
+ await post({ authorization: `Bearer ${TOKEN}` });
+ const logged = JSON.stringify([logger.debug, logger.info, logger.warn, logger.error].map((f) => (f as ReturnType<typeof vi.fn>).mock.calls));
+ expect(logged).not.toContain(TOKEN);
+ expect(logged).not.toContain('wrong-token-wrong-token');
+ expect(logged.toLowerCase()).not.toContain('bearer');
+ });
+
+ it('keeps the request body size cap', async () => {
+ await transport!.stop();
+ await start({ enabled: true, method: 'token', tokens: [TOKEN] }, { maxRequestSize: '1kb' });
+ const big = { ...RPC, params: { pad: 'x'.repeat(5000) } };
+ const res = await post({ authorization: `Bearer ${TOKEN}` }, '/rpc', big);
+ expect(res.status).toBeGreaterThanOrEqual(400);
+ expect(handled).toBe(0);
+ });
+
+ it('an unauthenticated client cannot make the server read or parse a body', async () => {
+ await transport!.stop();
+ await start({ enabled: true, method: 'token', tokens: [TOKEN] }, { maxRequestSize: '1kb' });
+ const big = { ...RPC, params: { pad: 'x'.repeat(5000) } };
+ // 401 (auth runs before the body parser), not 413.
+ expect((await post({}, '/rpc', big)).status).toBe(401);
+ });
+
+ describe('health endpoint', () => {
+ it('is reachable without credentials and reveals only liveness', async () => {
+ const res = await fetch(`${base}/health`);
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ status: 'ok' });
+ });
+
+ it('is the only public route: look-alike paths still need the token', async () => {
+ for (const p of ['/health/../rpc', '/health%2f..%2frpc', '//rpc', '/healthz', '/health/x', '/info']) {
+ const res = await post({}, p);
+ expect([401, 404]).toContain(res.status);
+ expect(handled).toBe(0);
+ }
+ expect((await post({}, '/health')).status).not.toBe(200); // POST /health is not the public GET
+ expect(handled).toBe(0);
+ });
+ });
+
+ describe('bypass attempts', () => {
+ const noAuthBypass = async (res: { status: number }) => {
+ expect(res.status).toBe(401);
+ expect(handled).toBe(0);
+ };
+
+ it('method override headers/params do not turn a request into the public GET /health', async () => {
+ await noAuthBypass(await post({ 'x-http-method-override': 'GET' }));
+ await noAuthBypass(await post({ 'x-method-override': 'GET', 'x-http-method': 'GET' }));
+ await noAuthBypass(await post({}, '/rpc?_method=GET'));
+ });
+
+ it('HEAD and non-preflight OPTIONS on tool routes do not dispatch or leak data', async () => {
+ const head = await rawPost([], '/rpc', 'HEAD');
+ expect(head.status).toBe(401);
+ expect(handled).toBe(0);
+ const opts = await rawPost([], '/rpc', 'OPTIONS');
+ expect([204, 401, 404]).toContain(opts.status);
+ expect(handled).toBe(0);
+ });
+
+ it('scheme case: "bearer"/"BEARER" with a wrong token fails, with the right token is valid per RFC 7235', async () => {
+ await noAuthBypass(await post({ authorization: 'bearer wrong-token-wrong-token' }));
+ await noAuthBypass(await post({ authorization: 'BEARER wrong-token-wrong-token' }));
+ expect((await post({ authorization: `bearer ${TOKEN}` })).status).toBe(200);
+ });
+
+ it('duplicate Authorization headers: only the first counts, so a valid second one cannot rescue a bad first', async () => {
+ const bad = await rawPost([`Authorization: Bearer wrong-token-wrong-token`, `Authorization: Bearer ${TOKEN}`]);
+ expect(bad.status).toBe(401);
+ expect(handled).toBe(0);
+ const swapped = await rawPost([`Authorization: Bearer ${TOKEN}`, `Authorization: Bearer wrong-token-wrong-token`]);
+ expect(swapped.status).toBe(200); // first (valid) header wins; nothing about the second is trusted
+ });
+
+ it('comma-joined or multi-token values do not match', async () => {
+ await noAuthBypass(await post({ authorization: `Bearer wrong-token-wrong-token, Bearer ${TOKEN}` }));
+ await noAuthBypass(await post({ authorization: `Bearer ${TOKEN}, Bearer wrong-token-wrong-token` }));
+ });
+
+ it('path variants of the RPC routes are still gated', async () => {
+ for (const p of ['/RPC', '/rpc/', '/rpc//', '/%72pc', '/rpc;x=1', '/rpc%00', '/./rpc', '/mcp/', '/MCP']) {
+ const res = await post({}, p);
+ expect([401, 404]).toContain(res.status);
+ expect(handled).toBe(0);
+ }
+ });
+
+ it('a forged Host or X-Forwarded-* header does not authenticate', async () => {
+ await noAuthBypass(await post({ 'x-forwarded-for': '127.0.0.1', 'x-forwarded-host': 'localhost', 'x-real-ip': '127.0.0.1' }));
+ await noAuthBypass(await raw(`POST /rpc HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(JSON.stringify(RPC))}\r\nConnection: close\r\n\r\n${JSON.stringify(RPC)}`));
+ });
+
+ it('credentials in the query string or body are ignored', async () => {
+ await noAuthBypass(await post({}, `/rpc?token=${TOKEN}&access_token=${TOKEN}`));
+ await noAuthBypass(await post({}, '/rpc', { ...RPC, token: TOKEN, auth: TOKEN }));
+ });
+ });
+
+ describe('CORS preflight behaviour is unchanged', () => {
+ it('answers a preflight from an allowed origin without credentials, and refuses a foreign origin', async () => {
+ const ok = await fetch(`${base}/rpc`, {
+ method: 'OPTIONS',
+ headers: { origin: 'https://app.example', 'access-control-request-method': 'POST', 'access-control-request-headers': 'authorization,content-type' },
+ });
+ expect(ok.status).toBe(204);
+ expect(ok.headers.get('access-control-allow-origin')).toBe('https://app.example');
+ expect(ok.headers.get('access-control-allow-headers')).toContain('Authorization');
+ expect(handled).toBe(0);
+ const foreign = await fetch(`${base}/rpc`, {
+ method: 'OPTIONS',
+ headers: { origin: 'https://evil.example', 'access-control-request-method': 'POST' },
+ });
+ expect(foreign.headers.get('access-control-allow-origin')).toBeNull();
+ expect(foreign.status).toBeGreaterThanOrEqual(400);
+ // A cross-origin POST from a foreign origin is refused by CORS even with a token.
+ const post2 = await post({ origin: 'https://evil.example', authorization: `Bearer ${TOKEN}` });
+ expect(post2.status).toBeGreaterThanOrEqual(400);
+ expect(handled).toBe(0);
+ });
+ });
+});
+
+describe('HTTP transport auth: fail closed and unchanged defaults', () => {
+ it('auth enabled with no configured tokens accepts nothing (used to accept any Bearer value)', async () => {
+ await start({ enabled: true, method: 'token' });
+ expect((await post({ authorization: 'Bearer anything-at-all-123' })).status).toBe(401);
+ await transport!.stop();
+ await start({ enabled: true, method: 'token', tokens: [] });
+ expect((await post({ authorization: 'Bearer anything-at-all-123' })).status).toBe(401);
+ expect(handled).toBe(0);
+ });
+
+ it('without auth config nothing changes: requests are served and /health keeps its full body', async () => {
+ await start(undefined);
+ expect((await post()).status).toBe(200);
+ const health = await (await fetch(`${base}/health`)).json();
+ expect(health).toMatchObject({ status: 'ok', connections: 0 });
+ expect(typeof health.timestamp).toBe('string');
+ });
+
+ it('auth.enabled=false behaves as no auth', async () => {
+ await start({ enabled: false, method: 'none' });
+ expect((await post()).status).toBe(200);
+ });
+});
diff --git a/v3/@claude-flow/mcp/src/transport/http.ts b/v3/@claude-flow/mcp/src/transport/http.ts
index 77cb22e5e1..cbc4e6768b 100644
--- a/v3/@claude-flow/mcp/src/transport/http.ts
+++ b/v3/@claude-flow/mcp/src/transport/http.ts
@@ -11,7 +11,7 @@ import { WebSocketServer, WebSocket } from 'ws';
import cors from 'cors';
import helmet from 'helmet';
import { rateLimit } from 'express-rate-limit';
-import { randomUUID } from 'crypto';
+import { createHash, randomUUID, timingSafeEqual } from 'crypto';
import type {
ITransport,
TransportType,
@@ -218,10 +218,6 @@ export class HttpTransport extends EventEmitter implements ITransport {
}));
}
- this.app.use(express.json({
- limit: this.config.maxRequestSize || '10mb',
- }));
-
// Bound authenticated and unauthenticated RPC traffic before route-level
// authorization or request dispatch can consume significant resources.
this.app.use(['/rpc', '/mcp'], rateLimit({
@@ -236,6 +232,24 @@ export class HttpTransport extends EventEmitter implements ITransport {
},
}));
+ // Bearer-token gate for every route (health excepted, see isPublicHealthRequest).
+ // Runs after CORS (so preflights are unchanged) and the rate limiter (so
+ // failed attempts are bounded), and before the body parser so an
+ // unauthenticated client cannot make the server read or parse a body.
+ if (this.config.auth?.enabled) {
+ this.app.use((req: Request, res: Response, next: NextFunction) => {
+ if (this.isPublicHealthRequest(req) || this.validateAuth(req).valid) {
+ next();
+ return;
+ }
+ this.rejectUnauthorized(req, res);
+ });
+ }
+
+ this.app.use(express.json({
+ limit: this.config.maxRequestSize || '10mb',
+ }));
+
if (this.config.requestTimeout) {
this.app.use((req, res, next) => {
res.setTimeout(this.config.requestTimeout!, () => {
@@ -268,6 +282,12 @@ export class HttpTransport extends EventEmitter implements ITransport {
private setupRoutes(): void {
this.app.get('/health', (req, res) => {
+ // With auth enabled this route is reachable without credentials, so it
+ // reveals only liveness: no timestamp, no connection count.
+ if (this.config.auth?.enabled) {
+ res.json({ status: 'ok' });
+ return;
+ }
res.json({
status: 'ok',
timestamp: new Date().toISOString(),
@@ -283,12 +303,9 @@ export class HttpTransport extends EventEmitter implements ITransport {
// Streamable HTTP negotiation fails. Advertise this same POST endpoint
// and route its responses back over the established event stream.
this.app.get('/mcp', (req, res) => {
- if (this.config.auth?.enabled) {
- const authResult = this.validateAuth(req);
- if (!authResult.valid) {
- res.status(401).json({ error: authResult.error || 'Unauthorized' });
- return;
- }
+ if (this.config.auth?.enabled && !this.validateAuth(req).valid) {
+ this.rejectUnauthorized(req, res);
+ return;
}
const sessionId = randomUUID();
@@ -410,16 +427,7 @@ export class HttpTransport extends EventEmitter implements ITransport {
if (requiresAuth && this.config.auth) {
const authResult = this.validateAuth(req);
if (!authResult.valid) {
- this.logger.warn('Authentication failed', {
- ip: req.ip,
- path: req.path,
- error: authResult.error,
- });
- res.status(401).json({
- jsonrpc: '2.0',
- id: null,
- error: { code: -32001, message: 'Unauthorized' },
- });
+ this.rejectUnauthorized(req, res);
return;
}
} else if (requiresAuth && !this.config.auth) {
@@ -548,54 +556,55 @@ export class HttpTransport extends EventEmitter implements ITransport {
}
/**
- * SECURITY: Timing-safe token comparison to prevent timing attacks
+ * SECURITY: constant-time token comparison. Both sides are hashed first so
+ * the comparison is over equal-length digests and leaks neither content nor
+ * length.
*/
private timingSafeCompare(a: string, b: string): boolean {
- const crypto = require('crypto');
-
- // Ensure both strings are the same length for timing-safe comparison
- const bufA = Buffer.from(a, 'utf-8');
- const bufB = Buffer.from(b, 'utf-8');
+ const digestA = createHash('sha256').update(a, 'utf8').digest();
+ const digestB = createHash('sha256').update(b, 'utf8').digest();
+ return timingSafeEqual(digestA, digestB);
+ }
- // If lengths differ, still do a comparison to prevent length-based timing
- if (bufA.length !== bufB.length) {
- // Compare against itself to maintain constant time
- crypto.timingSafeEqual(bufA, bufA);
- return false;
- }
+ /** Only GET/HEAD of exactly /health (any case, optional trailing slash) is public. */
+ private isPublicHealthRequest(req: Request): boolean {
+ if (req.method !== 'GET' && req.method !== 'HEAD') return false;
+ return req.path.toLowerCase().replace(/\/$/, '') === '/health';
+ }
- return crypto.timingSafeEqual(bufA, bufB);
+ /** One generic 401 for every failure mode: no hint about what was wrong. */
+ private rejectUnauthorized(req: Request, res: Response): void {
+ // Never log the Authorization header or any token material.
+ this.logger.warn('Authentication failed', { ip: req.ip, path: req.path });
+ res.setHeader('WWW-Authenticate', 'Bearer');
+ res.status(401).json({
+ jsonrpc: '2.0',
+ id: null,
+ error: { code: -32001, message: 'Unauthorized' },
+ });
}
- private validateAuth(req: Request): { valid: boolean; error?: string } {
+ private validateAuth(req: Request): { valid: boolean } {
const auth = req.headers.authorization;
-
- if (!auth) {
- return { valid: false, error: 'Authorization header required' };
+ if (typeof auth !== 'string') {
+ return { valid: false };
}
const tokenMatch = auth.match(/^Bearer\s+(.+)$/i);
if (!tokenMatch) {
- return { valid: false, error: 'Invalid authorization format' };
+ return { valid: false };
}
- const token = tokenMatch[1];
-
- if (this.config.auth?.tokens?.length) {
- // SECURITY: Use timing-safe comparison to prevent timing attacks
- let valid = false;
- for (const validToken of this.config.auth.tokens) {
- if (this.timingSafeCompare(token, validToken)) {
- valid = true;
- break;
- }
- }
- if (!valid) {
- return { valid: false, error: 'Invalid token' };
+ // Fail closed: auth enabled with no configured token accepts nothing.
+ const tokens = this.config.auth?.tokens ?? [];
+ let valid = false;
+ for (const validToken of tokens) {
+ // No early exit, so timing does not depend on which token matched.
+ if (this.timingSafeCompare(tokenMatch[1], validToken)) {
+ valid = true;
}
}
-
- return { valid: true };
+ return { valid };
}
}