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(shared): MCP transports refuse web pages, rebound hosts and open non-loopback binds (#4517)

rUvd3cd2e2871b3
diff --git a/package-lock.json b/package-lock.json
index f22911fd4d..9fb37029e5 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -27,7 +27,7 @@
"@claude-flow/neural": "3.0.0",
"@claude-flow/plugin-agent-federation": "1.0.1",
"@claude-flow/security": "3.0.5",
- "@claude-flow/shared": "3.0.5",
+ "@claude-flow/shared": "3.0.6",
"@electron/asar": "^4.3.1",
"@iarna/toml": "^2.2.5",
"@noble/ed25519": "2.3.0",
@@ -230,9 +230,9 @@
"link": true
},
"node_modules/@claude-flow/shared": {
- "version": "3.0.5",
- "resolved": "https://registry.npmjs.org/@claude-flow/shared/-/shared-3.0.5.tgz",
- "integrity": "sha512-7iL7qWYGgYNByWlsrvANzo+7wTaK87F+Md5scE5HQy3GuFr7fSmZHXaZOxSscr6W90LllTFxx0edev6wdFl6aQ==",
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@claude-flow/shared/-/shared-3.0.6.tgz",
+ "integrity": "sha512-H/JhKWSuQ7Jw6i+hb1YOrCaHUtMRgFFfM/PH44GO8w0S+0H/2iTACkolqcU7hepBHVajf+suLiKn6ZXcZjpMZg==",
"dependencies": {
"sql.js": "^1.10.3"
}
@@ -14747,7 +14747,7 @@
}
},
"v3/@claude-flow/shared": {
- "version": "3.0.5",
+ "version": "3.0.6",
"dev": true,
"dependencies": {
"@types/ws": "^8.5.10",
diff --git a/package.json b/package.json
index fd63329440..b437d49585 100644
--- a/package.json
+++ b/package.json
@@ -75,7 +75,7 @@
"@claude-flow/neural": "3.0.0",
"@claude-flow/plugin-agent-federation": "1.0.2",
"@claude-flow/security": "3.0.5",
- "@claude-flow/shared": "3.0.5",
+ "@claude-flow/shared": "3.0.6",
"@electron/asar": "^4.3.1",
"@iarna/toml": "^2.2.5",
"@noble/ed25519": "2.3.0",
diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.json
index 8c5a965f73..4ac2918a88 100644
--- a/v3/@claude-flow/cli/package.json
+++ b/v3/@claude-flow/cli/package.json
@@ -106,7 +106,7 @@
"@claude-flow/neural": "3.0.0",
"@claude-flow/plugin-agent-federation": "1.0.2",
"@claude-flow/security": "3.0.5",
- "@claude-flow/shared": "3.0.5",
+ "@claude-flow/shared": "3.0.6",
"@iarna/toml": "^2.2.5",
"@noble/ed25519": "2.3.0",
"@ruvector/rabitq-wasm": "0.1.0",
diff --git a/v3/@claude-flow/shared/__tests__/mcp/open-transport-origin-host-guard.test.ts b/v3/@claude-flow/shared/__tests__/mcp/open-transport-origin-host-guard.test.ts
new file mode 100644
index 0000000000..981f3c1dde
--- /dev/null
+++ b/v3/@claude-flow/shared/__tests__/mcp/open-transport-origin-host-guard.test.ts
@@ -0,0 +1,102 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { AddressInfo } from 'node:net';
+import { request, type Server } from 'node:http';
+import { WebSocket } from 'ws';
+import { HttpTransport } from '../../src/mcp/transport/http.js';
+import { WebSocketTransport } from '../../src/mcp/transport/websocket.js';
+import { assertSafeBind, hostHeaderAllowed, originAllowed } from '../../src/mcp/transport/guard.js';
+import type { ILogger } from '../../src/mcp/types.js';
+
+const logger: ILogger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
+const RPC = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'terminal_execute' } };
+let stop: (() => Promise<void>) | undefined;
+afterEach(async () => { await stop?.(); stop = undefined; });
+
+async function openHttp(extra: Record<string, unknown> = {}): Promise<{ port: number; handled: () => number }> {
+ let handled = 0;
+ const t = new HttpTransport(logger, { host: '127.0.0.1', port: 0, corsEnabled: true, corsOrigins: ['*'], ...extra } as never);
+ t.onRequest(async (r) => { handled++; return { jsonrpc: '2.0', id: r.id, result: { ok: true } }; });
+ await t.start();
+ stop = () => t.stop();
+ return { port: ((t as unknown as { server: Server }).server.address() as AddressInfo).port, handled: () => handled };
+}
+
+const rpc = (port: number, headers: Record<string, string> = {}) =>
+ fetch(`http://127.0.0.1:${port}/rpc`, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(RPC) });
+
+/** Resolves true when the upgrade is accepted, false when it is refused. */
+const upgrades = (url: string, headers: Record<string, string>): Promise<boolean> =>
+ new Promise((resolve) => {
+ const ws = new WebSocket(url, { headers });
+ ws.on('open', () => { ws.close(); resolve(true); });
+ ws.on('unexpected-response', () => resolve(false));
+ ws.on('error', () => resolve(false));
+ });
+
+describe('a loopback MCP server with no token', () => {
+ it('still serves a client that sends no Origin, as every CLI and MCP client does', async () => {
+ const s = await openHttp();
+ expect((await rpc(s.port)).status).toBe(200);
+ expect(s.handled()).toBe(1);
+ });
+
+ it('refuses a web page, even when CORS is set to "*"', async () => {
+ const s = await openHttp();
+ const res = await rpc(s.port, { origin: 'https://evil.example' });
+ expect(res.status).toBe(403);
+ expect(s.handled()).toBe(0);
+ });
+
+ it('refuses a rebound hostname', async () => {
+ const s = await openHttp();
+ // fetch() will not let a caller set Host, so use a raw request.
+ const status = await new Promise<number>((resolve, reject) => {
+ const req = request({ port: s.port, host: '127.0.0.1', method: 'POST', path: '/rpc', headers: { host: 'evil.example', 'content-type': 'application/json' } }, (res) => { res.resume(); resolve(res.statusCode ?? 0); });
+ req.on('error', reject);
+ req.end(JSON.stringify(RPC));
+ });
+ expect(status).toBe(403);
+ expect(s.handled()).toBe(0);
+ });
+
+ it('lets an origin the operator listed by name through', async () => {
+ const s = await openHttp({ corsOrigins: ['https://app.example'] });
+ expect((await rpc(s.port, { origin: 'https://app.example' })).status).toBe(200);
+ });
+
+ it('refuses a cross-origin WebSocket upgrade on the HTTP transport, and accepts a plain one', async () => {
+ const s = await openHttp();
+ expect(await upgrades(`ws://127.0.0.1:${s.port}/ws`, { origin: 'https://evil.example' })).toBe(false);
+ expect(await upgrades(`ws://127.0.0.1:${s.port}/ws`, { host: 'evil.example' })).toBe(false);
+ expect(await upgrades(`ws://127.0.0.1:${s.port}/ws`, {})).toBe(true);
+ });
+
+ it('refuses a cross-origin upgrade on the standalone WebSocket transport', async () => {
+ const t = new WebSocketTransport(logger, { host: '127.0.0.1', port: 0 });
+ await t.start();
+ stop = () => t.stop();
+ const port = ((t as unknown as { server: Server }).server.address() as AddressInfo).port;
+ expect(await upgrades(`ws://127.0.0.1:${port}/ws`, { origin: 'https://evil.example' })).toBe(false);
+ expect(await upgrades(`ws://127.0.0.1:${port}/ws`, {})).toBe(true);
+ });
+});
+
+describe('listening beyond loopback', () => {
+ it('is refused by both transports without a token unless the operator opts in', async () => {
+ await expect(new HttpTransport(logger, { host: '0.0.0.0', port: 0 } as never).start()).rejects.toThrow(/non-loopback/);
+ await expect(new WebSocketTransport(logger, { host: '0.0.0.0', port: 0 }).start()).rejects.toThrow(/non-loopback/);
+ expect(() => assertSafeBind('0.0.0.0', true, undefined)).not.toThrow();
+ expect(() => assertSafeBind('0.0.0.0', false, true)).not.toThrow();
+ expect(() => assertSafeBind('::1', false, undefined)).not.toThrow();
+ });
+
+ it('judges Host and Origin by exact name', () => {
+ expect(hostHeaderAllowed('localhost:3000', '127.0.0.1')).toBe(true);
+ expect(hostHeaderAllowed('[::1]:3000', '127.0.0.1')).toBe(true);
+ expect(hostHeaderAllowed('localhost.evil.example', '127.0.0.1')).toBe(false);
+ expect(hostHeaderAllowed(undefined, '127.0.0.1')).toBe(false);
+ expect(originAllowed(undefined, undefined)).toBe(true);
+ expect(originAllowed('https://a.example', ['*'])).toBe(false);
+ expect(originAllowed('https://a.example', ['https://a.example'])).toBe(true);
+ });
+});
diff --git a/v3/@claude-flow/shared/package.json b/v3/@claude-flow/shared/package.json
index 7bfdc6b889..9e8562d967 100644
--- a/v3/@claude-flow/shared/package.json
+++ b/v3/@claude-flow/shared/package.json
@@ -1,6 +1,6 @@
{
"name": "@claude-flow/shared",
- "version": "3.0.5",
+ "version": "3.0.6",
"type": "module",
"description": "Shared module - common types, events, utilities, core interfaces",
"main": "dist/index.js",
diff --git a/v3/@claude-flow/shared/src/mcp/transport/guard.ts b/v3/@claude-flow/shared/src/mcp/transport/guard.ts
new file mode 100644
index 0000000000..dc372242fb
--- /dev/null
+++ b/v3/@claude-flow/shared/src/mcp/transport/guard.ts
@@ -0,0 +1,53 @@
+/**
+ * Checks for transports that carry no bearer token. A browser always sends an
+ * `Origin` header and cannot be stopped by CORS on a WebSocket upgrade, and a
+ * rebinding page reaches 127.0.0.1 under its own hostname, so an open loopback
+ * server must look at both. Non-browser clients send no `Origin`.
+ */
+import type { IncomingMessage } from 'node:http';
+
+const LOOPBACK = new Set(['localhost', '127.0.0.1', '::1', '0:0:0:0:0:0:0:1']);
+
+export function isLoopbackName(host: string): boolean {
+ return LOOPBACK.has(host.trim().toLowerCase().replace(/^\[|\]$/g, ''));
+}
+
+/** The hostname of a `Host` header value: no port, no IPv6 brackets, lower case. */
+function hostnameOf(header: string): string {
+ const value = header.trim().toLowerCase();
+ const bracket = value.match(/^\[([^\]]*)\](?::\d*)?$/);
+ if (bracket) return bracket[1];
+ return value.replace(/:\d*$/, '');
+}
+
+/** Whether the `Host` header names this server (a loopback name or the bound host). */
+export function hostHeaderAllowed(header: string | undefined, boundHost: string): boolean {
+ if (!header) return false;
+ const name = hostnameOf(header);
+ return isLoopbackName(name) || name === boundHost.trim().toLowerCase().replace(/^\[|\]$/g, '');
+}
+
+/** Whether a request's `Origin` may talk to an unauthenticated server: none at all, or one listed by name (`*` does not count). */
+export function originAllowed(origin: string | undefined, allowed: readonly string[] | undefined): boolean {
+ if (origin === undefined || origin === '') return true;
+ return (allowed ?? []).some((entry) => entry !== '*' && entry === origin);
+}
+
+/** Why an unauthenticated request must be refused, or `undefined` when it may proceed. */
+export function refuseOpenRequest(req: Pick<IncomingMessage, 'headers'>, boundHost: string, allowedOrigins: readonly string[] | undefined): string | undefined {
+ // Rebinding only reaches a loopback bind; behind a proxy on another address the Host is the proxy's.
+ if (isLoopbackName(boundHost) && !hostHeaderAllowed(req.headers.host, boundHost)) return 'Host header does not name this server';
+ const origin = req.headers.origin;
+ if (!originAllowed(Array.isArray(origin) ? origin[0] : origin, allowedOrigins)) return 'cross-origin requests are refused without a token';
+ return undefined;
+}
+
+/** Refuse to listen beyond loopback with no token unless the operator said so. */
+export function assertSafeBind(host: string, authenticated: boolean, allowUnauthenticated: boolean | undefined): void {
+ if (!isLoopbackName(host) && !authenticated && allowUnauthenticated !== true) {
+ throw new Error(
+ `Refusing to listen on non-loopback host "${host}" without authentication: every registered tool would be reachable from the network. ` +
+ 'Configure a token, bind to a loopback host, or set allowUnauthenticated to accept the risk.',
+ );
+ }
+}
diff --git a/v3/@claude-flow/shared/src/mcp/transport/http.ts b/v3/@claude-flow/shared/src/mcp/transport/http.ts
index c38d8317e0..acac6bdb16 100644
--- a/v3/@claude-flow/shared/src/mcp/transport/http.ts
+++ b/v3/@claude-flow/shared/src/mcp/transport/http.ts
@@ -14,7 +14,8 @@
import { EventEmitter } from 'events';
import express, { Express, Request, Response, NextFunction } from 'express';
-import { createServer, Server } from 'http';
+import { createServer, Server, type IncomingMessage } from 'http';
+import { assertSafeBind, refuseOpenRequest } from './guard.js';
import { WebSocketServer, WebSocket } from 'ws';
import cors from 'cors';
import helmet from 'helmet';
@@ -43,6 +44,8 @@ export interface HttpTransportConfig {
corsEnabled?: boolean;
corsOrigins?: string[];
auth?: AuthConfig;
+ /** Accept a non-loopback bind with no token (the operator's own risk). */
+ allowUnauthenticated?: boolean;
maxRequestSize?: string;
requestTimeout?: number;
}
@@ -91,13 +94,17 @@ export class HttpTransport extends EventEmitter implements ITransport {
port: this.config.port,
});
+ assertSafeBind(this.config.host, this.config.auth?.enabled === true, this.config.allowUnauthenticated);
+
// Create HTTP server
this.server = createServer(this.app);
- // Create WebSocket server
+ // Create WebSocket server (CORS does not apply to upgrades, so a token-less server checks Host and Origin itself)
this.wss = new WebSocketServer({
server: this.server,
path: '/ws',
+ verifyClient: (info: { req: IncomingMessage }) =>
+ this.config.auth?.enabled === true || refuseOpenRequest(info.req, this.config.host, this.config.corsOrigins) === undefined,
});
this.setupWebSocketHandlers();
@@ -208,6 +215,18 @@ export class HttpTransport extends EventEmitter implements ITransport {
* Setup Express middleware
*/
private setupMiddleware(): void {
+ // A server with no token must not answer a web page or a rebound hostname.
+ if (this.config.auth?.enabled !== true) {
+ this.app.use((req: Request, res: Response, next: NextFunction) => {
+ const why = refuseOpenRequest(req, this.config.host, this.config.corsOrigins);
+ if (why === undefined) {
+ next();
+ return;
+ }
+ res.status(403).json({ jsonrpc: '2.0', id: null, error: { code: -32000, message: `Forbidden: ${why}` } });
+ });
+ }
+
// Security headers
this.app.use(helmet({
contentSecurityPolicy: false, // Allow for flexibility
diff --git a/v3/@claude-flow/shared/src/mcp/transport/websocket.ts b/v3/@claude-flow/shared/src/mcp/transport/websocket.ts
index d450646ee4..19319e44d8 100644
--- a/v3/@claude-flow/shared/src/mcp/transport/websocket.ts
+++ b/v3/@claude-flow/shared/src/mcp/transport/websocket.ts
@@ -14,7 +14,9 @@
import { EventEmitter } from 'events';
import { WebSocketServer, WebSocket, RawData } from 'ws';
-import { createServer, Server } from 'http';
+import { createServer, Server, type IncomingMessage } from 'http';
+import { createHash, timingSafeEqual } from 'node:crypto';
+import { assertSafeBind, refuseOpenRequest } from './guard.js';
import {
ITransport,
TransportType,
@@ -40,6 +42,10 @@ export interface WebSocketTransportConfig {
heartbeatTimeout?: number;
maxMessageSize?: number;
auth?: AuthConfig;
+ /** Accept a non-loopback bind with no token. */
+ allowUnauthenticated?: boolean;
+ /** Browser origins allowed to connect, by exact name. */
+ allowedOrigins?: string[];
enableBinaryMode?: boolean;
}
@@ -98,6 +104,8 @@ export class WebSocketTransport extends EventEmitter implements ITransport {
path: this.config.path || '/ws',
});
+ assertSafeBind(this.config.host, this.config.auth?.enabled === true, this.config.allowUnauthenticated);
+
// Create HTTP server for WebSocket upgrade
this.server = createServer((req, res) => {
// Simple HTTP response for non-WebSocket requests
@@ -111,6 +119,10 @@ export class WebSocketTransport extends EventEmitter implements ITransport {
path: this.config.path || '/ws',
maxPayload: this.config.maxMessageSize || 10 * 1024 * 1024,
perMessageDeflate: true, // Enable compression
+ 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();
@@ -292,7 +304,8 @@ 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).
+ isAuthenticated: true,
};
this.clients.set(clientId, client);
@@ -339,6 +352,21 @@ export class WebSocketTransport extends EventEmitter implements ITransport {
/**
* Handle incoming message
*/
+ /** 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++;
diff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yaml
index 9873fd41af..7c58453756 100644
--- a/v3/pnpm-lock.yaml
+++ b/v3/pnpm-lock.yaml
@@ -136,7 +136,7 @@ importers:
specifier: 3.0.5
version: link:../security
'@claude-flow/shared':
- specifier: 3.0.5
+ specifier: 3.0.6
version: link:../shared
'@electron/asar':
specifier: ^4.3.1