🌊 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(mcp): network transports start with a per-user token by default; WebSocket tokens work (#4516)
rUvfc323f5108df
diff --git a/v3/@claude-flow/cli/__tests__/hive-mind-gate-transport-e2e.test.ts b/v3/@claude-flow/cli/__tests__/hive-mind-gate-transport-e2e.test.tsindex 606ac873e3..f43490691d 100644--- a/v3/@claude-flow/cli/__tests__/hive-mind-gate-transport-e2e.test.ts+++ b/v3/@claude-flow/cli/__tests__/hive-mind-gate-transport-e2e.test.ts@@ -139,7 +139,7 @@ describe('hive-mind gate end to end (ADR-476)', () => {let lastFailure = '';for (let attempt = 1; attempt <= 4 && !port; attempt++) {const candidate = 34000 + Math.floor(Math.random() * 4000);- const e = env({ RUFLO_HIVE_BOOTSTRAP_SECRET: SECRET });+ const e = env({ RUFLO_HIVE_BOOTSTRAP_SECRET: SECRET, RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: '1' });child = spawn('node', [path.join(BIN, 'cli.js'), 'mcp', 'start', '-t', 'http', '--port', String(candidate)], {cwd: dir, env: e, stdio: ['ignore', 'pipe', 'pipe'],});diff --git a/v3/@claude-flow/cli/__tests__/mcp-default-token-sec.test.ts b/v3/@claude-flow/cli/__tests__/mcp-default-token-sec.test.tsnew file mode 100644index 0000000000..6cfbad6a4e--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/mcp-default-token-sec.test.ts@@ -0,0 +1,27 @@+import { describe, it, expect, afterEach } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { ensureDefaultMcpToken } from '../src/mcp-server.js';++const dirs: string[] = [];+afterEach(() => { for (const d of dirs.splice(0)) fs.rmSync(d, { recursive: true, force: true }); });+const home = () => { const d = fs.mkdtempSync(path.join(os.tmpdir(), 'ruflo-token-')); dirs.push(d); return d; };++describe('the per-user MCP token used when none is given', () => {+ it('is created once, readable only by the user, and reused', () => {+ const h = home();+ const first = ensureDefaultMcpToken(h);+ expect(first.token).toMatch(/^[0-9a-f]{64}$/);+ expect(first.file).toBe(path.join(h, '.claude-flow', 'mcp-http-token'));+ if (process.platform !== 'win32') expect(fs.statSync(first.file).mode & 0o777).toBe(0o600);+ expect(ensureDefaultMcpToken(h).token).toBe(first.token);+ });++ it('replaces a file that does not hold a usable token', () => {+ const h = home();+ fs.mkdirSync(path.join(h, '.claude-flow'));+ fs.writeFileSync(path.join(h, '.claude-flow', 'mcp-http-token'), 'short\n');+ expect(ensureDefaultMcpToken(h).token).toMatch(/^[0-9a-f]{64}$/);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/mcp-http-foreground-2984.test.ts b/v3/@claude-flow/cli/__tests__/mcp-http-foreground-2984.test.tsindex 785717a28a..b5f6eef9e5 100644--- a/v3/@claude-flow/cli/__tests__/mcp-http-foreground-2984.test.ts+++ b/v3/@claude-flow/cli/__tests__/mcp-http-foreground-2984.test.ts@@ -74,6 +74,7 @@ describe.skipIf(!CLI_BUILT)('mcp start -t http stays running (#2984, end-to-end)const host = '127.0.0.1';child = spawn('node', [CLI, 'mcp', 'start', '-t', 'http', '--port', String(port), '--host', host], {+ env: { ...process.env, RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: '1' },stdio: ['ignore', 'pipe', 'pipe'],});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.tsindex 8199b43cc5..0fd01b5f20 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@@ -121,10 +121,9 @@ describe('MCPServerManager.start() - non-loopback hosts are refused without authexpect(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('a token is accepted with the standalone websocket transport (checked at upgrade)', async () => {+ await manager({ transport: 'websocket', host: '0.0.0.0', authToken: TOKEN }).start();+ expect(createMCPServer).toHaveBeenCalled();});it('websocket transport on a non-loopback host is still refused without the opt-out', async () => {diff --git a/v3/@claude-flow/cli/__tests__/mcp-http-protocol-tools-2990.test.ts b/v3/@claude-flow/cli/__tests__/mcp-http-protocol-tools-2990.test.tsindex a737101a8a..bac6ca4f7e 100644--- a/v3/@claude-flow/cli/__tests__/mcp-http-protocol-tools-2990.test.ts+++ b/v3/@claude-flow/cli/__tests__/mcp-http-protocol-tools-2990.test.ts@@ -69,6 +69,7 @@ async function startHttpCli(port: number, tools: string): Promise<void> {child = spawn('node', [CLI, 'mcp', 'start', '-t', 'http', '--port', String(port)], {env: {...process.env,+ RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: '1',CLAUDE_FLOW_MCP_TOOLS: tools,RUFLO_DAEMON_AUTOSTART: '0',TEMP: TEST_TMP,diff --git a/v3/@claude-flow/cli/__tests__/mcp-start-rate-limit-3157.test.ts b/v3/@claude-flow/cli/__tests__/mcp-start-rate-limit-3157.test.tsindex f17213d5e6..860e200c9c 100644--- a/v3/@claude-flow/cli/__tests__/mcp-start-rate-limit-3157.test.ts+++ b/v3/@claude-flow/cli/__tests__/mcp-start-rate-limit-3157.test.ts@@ -27,6 +27,8 @@ vi.mock('../src/mcp-server.js', () => ({filterAdvertisedMcpTools: (tools: unknown[]) => tools,parseMcpToolSelection: () => 'all',resolveMcpHttpAuthToken: () => undefined,+ ensureDefaultMcpToken: () => ({ token: 'x'.repeat(32), file: '/nowhere' }),+ isUnauthenticatedHttpAllowed: (env: NodeJS.ProcessEnv = process.env) => env.RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP === '1',}));vi.mock('../src/mcp-client.js', () => ({@@ -60,6 +62,7 @@ describe('mcp start rate limit options (#3157)', () => {start.action!({ args: [], flags, interactive: false } as never);beforeEach(() => {+ vi.stubEnv("RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP", "1"); // these cases are about rate limits, not the default tokenh.manager.start.mockReset().mockImplementation(() => new Promise(() => {}));h.getServerManager.mockReset().mockReturnValue(h.manager);});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.tsindex bba0e164c8..c3573c8e6d 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@@ -58,6 +58,8 @@ vi.mock('../src/mcp-server.js', () => ({filterAdvertisedMcpTools: (tools: unknown[]) => tools,parseMcpToolSelection: () => 'all',resolveMcpHttpAuthToken: () => undefined,+ ensureDefaultMcpToken: () => ({ token: 'x'.repeat(32), file: '/nowhere' }),+ isUnauthenticatedHttpAllowed: () => false,isLoopbackHost: () => true,}));diff --git a/v3/@claude-flow/cli/src/commands/mcp.ts b/v3/@claude-flow/cli/src/commands/mcp.tsindex 75dd584fd2..95903c1be9 100644--- a/v3/@claude-flow/cli/src/commands/mcp.ts+++ b/v3/@claude-flow/cli/src/commands/mcp.ts@@ -19,6 +19,8 @@ import {getMCPServerStatus,type MCPServerOptions,resolveMcpHttpAuthToken,+ ensureDefaultMcpToken,+ isUnauthenticatedHttpAllowed,isLoopbackHost,type MCPServerStatus,filterAdvertisedMcpTools,@@ -206,6 +208,13 @@ const startCommand: Command = {output.printError((error as Error).message);return { success: false, exitCode: 1 };}+ // Network transports never start open by default: with no token given, use the per-user one.+ let defaultTokenFile: string | undefined;+ if (!authToken && (transport === 'http' || transport === 'websocket') && !isUnauthenticatedHttpAllowed()) {+ const made = ensureDefaultMcpToken();+ authToken = made.token;+ defaultTokenFile = made.file;+ }const daemon = (ctx.flags.daemon as boolean) ?? false;const force = (ctx.flags.force as boolean) ?? false;@@ -334,6 +343,7 @@ const startCommand: Command = {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'));+ if (defaultTokenFile) output.writeln(output.dim(` Token (none was given): ${defaultTokenFile} - set RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP=1 to run without one`));} 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 {@@ -341,6 +351,7 @@ const startCommand: Command = {}} else if (transport === 'websocket') {output.writeln(output.dim(` WebSocket: ws://${host}:${port}/ws`));+ if (authToken) output.writeln(output.dim(` Auth: bearer token required (Authorization: Bearer <token> or ?token=)${defaultTokenFile ? `; token in ${defaultTokenFile}` : ''}`));}if (daemon) {diff --git a/v3/@claude-flow/cli/src/mcp-server.ts b/v3/@claude-flow/cli/src/mcp-server.tsindex 615fa78bac..8bfafdc3f3 100644--- a/v3/@claude-flow/cli/src/mcp-server.ts+++ b/v3/@claude-flow/cli/src/mcp-server.ts@@ -20,7 +20,7 @@import { EventEmitter } from 'events';import { spawn, ChildProcess, execFileSync } from 'child_process';import { createServer, Server, request as httpRequestFn } from 'http';-import { randomUUID } from 'crypto';+import { randomUUID, randomBytes } from 'crypto';import * as path from 'path';import * as fs from 'fs';import * as os from 'os';@@ -258,6 +258,27 @@ function raisedRateLimits(options: Pick<MCPServerOptions, RateLimitOption>): Ratreturn raised;}+/**+ * The bearer token a token-less `mcp start -t http|websocket` falls back to, so that a loopback+ * server is never open to every local process. Kept in `~/.claude-flow/mcp-http-token` (mode 0600)+ * so clients can read it; created on first use. Exported for tests.+ */+export function ensureDefaultMcpToken(homeDir: string = os.homedir()): { token: string; file: string } {+ const dir = path.join(homeDir, '.claude-flow');+ const file = path.join(dir, 'mcp-http-token');+ try {+ const existing = fs.readFileSync(file, 'utf8').trim();+ if (AUTH_TOKEN_PATTERN.test(existing)) return { token: existing, file };+ } catch {+ // none yet+ }+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });+ const token = randomBytes(32).toString('hex');+ fs.writeFileSync(file, token + '\n', { mode: 0o600 });+ fs.chmodSync(file, 0o600);+ return { token, file };+}+/** Printable ASCII without space (RFC 6750 token-ish), 16-512 chars. */const AUTH_TOKEN_PATTERN = /^[\x21-\x7e]{16,512}$/;@@ -1051,11 +1072,6 @@ export class MCPServerManager extends EventEmitter {// 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),diff --git a/v3/@claude-flow/mcp/__tests__/open-transport-origin-host-guard.test.ts b/v3/@claude-flow/mcp/__tests__/open-transport-origin-host-guard.test.tsindex 2a2e312617..04334c6197 100644--- a/v3/@claude-flow/mcp/__tests__/open-transport-origin-host-guard.test.ts+++ b/v3/@claude-flow/mcp/__tests__/open-transport-origin-host-guard.test.ts@@ -100,3 +100,25 @@ describe('listening beyond loopback', () => {expect(originAllowed('https://a.example', ['https://a.example'])).toBe(true);});});++describe('the standalone WebSocket transport with a token', () => {+ it('serves a client that presents it, and refuses one that does not or sends a wrong one', async () => {+ const TOKEN = 'a-long-enough-token-1234';+ const t = new WebSocketTransport(logger, { host: '127.0.0.1', port: 0, auth: { enabled: true, method: 'token', tokens: [TOKEN] } });+ t.onRequest(async (r) => ({ jsonrpc: '2.0', id: r.id, result: { ok: true } }));+ await t.start();+ stop = () => t.stop();+ const port = ((t as unknown as { server: Server }).server.address() as AddressInfo).port;+ const url = `ws://127.0.0.1:${port}/ws`;+ expect(await upgrades(url, {})).toBe(false);+ expect(await upgrades(url, { authorization: 'Bearer wrong-wrong-wrong-wrong' })).toBe(false);+ expect(await upgrades(`${url}?token=${TOKEN}`, {})).toBe(true);+ const reply = await new Promise<unknown>((resolve, reject) => {+ const ws = new WebSocket(url, { headers: { authorization: `Bearer ${TOKEN}` } });+ ws.on('open', () => ws.send(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' })));+ ws.on('message', (m) => { resolve(JSON.parse(m.toString())); ws.close(); });+ ws.on('error', reject);+ });+ expect(reply).toMatchObject({ id: 1, result: { ok: true } });+ });+});diff --git a/v3/@claude-flow/mcp/src/transport/websocket.ts b/v3/@claude-flow/mcp/src/transport/websocket.tsindex d32c767808..bceae63124 100644--- a/v3/@claude-flow/mcp/src/transport/websocket.ts+++ b/v3/@claude-flow/mcp/src/transport/websocket.ts@@ -7,6 +7,7 @@import { EventEmitter } from 'events';import { WebSocketServer, WebSocket, RawData } from 'ws';import { createServer, Server, type IncomingMessage } from 'http';+import { createHash, timingSafeEqual } from 'node:crypto';import { assertSafeBind, refuseOpenRequest } from './guard.js';import type {ITransport,@@ -82,7 +83,7 @@ export class WebSocketTransport extends EventEmitter implements ITransport {path: this.config.path || '/ws',});- assertSafeBind(this.config.host, false, this.config.allowUnauthenticated);+ assertSafeBind(this.config.host, this.config.auth?.enabled === true, this.config.allowUnauthenticated);this.server = createServer((req, res) => {res.writeHead(426, { 'Content-Type': 'text/plain' });@@ -95,7 +96,10 @@ export class WebSocketTransport extends EventEmitter implements ITransport {maxPayload: this.config.maxMessageSize || 10 * 1024 * 1024,perMessageDeflate: true,// This transport has no token, so it refuses web pages and rebound hostnames.- verifyClient: (info: { req: IncomingMessage }) => refuseOpenRequest(info.req, this.config.host, this.config.allowedOrigins) === undefined,+ verifyClient: (info: { req: IncomingMessage }) =>+ this.config.auth?.enabled === true+ ? this.upgradeHasValidToken(info.req)+ : refuseOpenRequest(info.req, this.config.host, this.config.allowedOrigins) === undefined,});this.setupWebSocketHandlers();@@ -242,7 +246,9 @@ export class WebSocketTransport extends EventEmitter implements ITransport {lastActivity: new Date(),messageCount: 0,isAlive: true,- isAuthenticated: !this.config.auth?.enabled,+ // With a token configured the upgrade itself was authenticated (verifyClient), so every+ // connection that reaches here is; there is no later `authenticate` message to wait for.+ isAuthenticated: true,};this.clients.set(clientId, client);@@ -282,6 +288,21 @@ export class WebSocketTransport extends EventEmitter implements ITransport {});}+ /** Token from `Authorization: Bearer` or `?token=`, compared in constant time. */+ private upgradeHasValidToken(req: IncomingMessage): boolean {+ const header = req.headers.authorization;+ const fromHeader = typeof header === 'string' ? header.match(/^Bearer\s+(.+)$/i)?.[1] : undefined;+ const fromQuery = new URL(req.url ?? '', 'http://localhost').searchParams.get('token') ?? undefined;+ const given = fromHeader ?? fromQuery;+ if (!given) return false;+ const digest = (v: string) => createHash('sha256').update(v, 'utf8').digest();+ let ok = false;+ for (const valid of this.config.auth?.tokens ?? []) {+ if (timingSafeEqual(digest(given), digest(valid))) ok = true;+ }+ return ok;+ }+private async handleMessage(client: ClientConnection, data: RawData): Promise<void> {client.lastActivity = new Date();client.messageCount++;