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): token-less HTTP/WebSocket transports refuse web pages, rebound hosts and open non-loopback binds (#4510)

rUvc0f205629bce
diff --git a/v3/@claude-flow/cli/src/mcp-server.ts b/v3/@claude-flow/cli/src/mcp-server.ts
index ef0a80f4f7..615fa78bac 100644
--- a/v3/@claude-flow/cli/src/mcp-server.ts
+++ b/v3/@claude-flow/cli/src/mcp-server.ts
@@ -1147,6 +1147,7 @@ export class MCPServerManager extends EventEmitter {
auth: authToken
? { enabled: true, method: 'token', tokens: [authToken] }
: undefined,
+ allowUnauthenticated: isUnauthenticatedHttpAllowed(),
},
logger
);
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.ts
new file mode 100644
index 0000000000..2a2e312617
--- /dev/null
+++ b/v3/@claude-flow/mcp/__tests__/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/transport/http.js';
+import { WebSocketTransport } from '../src/transport/websocket.js';
+import { assertSafeBind, hostHeaderAllowed, originAllowed } from '../src/transport/guard.js';
+import type { ILogger } from '../src/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/mcp/src/server.ts b/v3/@claude-flow/mcp/src/server.ts
index 71865a9c68..e4643c12cf 100644
--- a/v3/@claude-flow/mcp/src/server.ts
+++ b/v3/@claude-flow/mcp/src/server.ts
@@ -228,6 +228,8 @@ export class MCPServer extends EventEmitter implements IMCPServer {
corsEnabled: this.config.corsEnabled,
corsOrigins: this.config.corsOrigins,
auth: this.config.auth,
+ allowUnauthenticated: this.config.allowUnauthenticated,
+ allowedOrigins: this.config.corsOrigins,
maxRequestSize: String(this.config.maxRequestSize),
requestTimeout: this.config.requestTimeout,
rateLimit: this.config.rateLimit,
diff --git a/v3/@claude-flow/mcp/src/transport/guard.ts b/v3/@claude-flow/mcp/src/transport/guard.ts
new file mode 100644
index 0000000000..dc372242fb
--- /dev/null
+++ b/v3/@claude-flow/mcp/src/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/mcp/src/transport/http.ts b/v3/@claude-flow/mcp/src/transport/http.ts
index cbc4e6768b..a8828772f3 100644
--- a/v3/@claude-flow/mcp/src/transport/http.ts
+++ b/v3/@claude-flow/mcp/src/transport/http.ts
@@ -6,7 +6,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';
@@ -34,6 +35,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;
rateLimit?: {
@@ -80,11 +83,16 @@ export class HttpTransport extends EventEmitter implements ITransport {
port: this.config.port,
});
+ assertSafeBind(this.config.host, this.config.auth?.enabled === true, this.config.allowUnauthenticated);
+
this.server = createServer(this.app);
this.wss = new WebSocketServer({
server: this.server,
path: '/ws',
+ // CORS does not apply to upgrades, so a token-less server checks Host and Origin itself.
+ verifyClient: (info: { req: IncomingMessage }) =>
+ this.config.auth?.enabled === true || refuseOpenRequest(info.req, this.config.host, this.config.corsOrigins) === undefined,
});
this.setupWebSocketHandlers();
@@ -183,6 +191,18 @@ export class HttpTransport extends EventEmitter implements ITransport {
}
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}` } });
+ });
+ }
+
this.app.use(helmet({
contentSecurityPolicy: false,
}));
diff --git a/v3/@claude-flow/mcp/src/transport/websocket.ts b/v3/@claude-flow/mcp/src/transport/websocket.ts
index a329f3256e..d32c767808 100644
--- a/v3/@claude-flow/mcp/src/transport/websocket.ts
+++ b/v3/@claude-flow/mcp/src/transport/websocket.ts
@@ -6,7 +6,8 @@
import { EventEmitter } from 'events';
import { WebSocketServer, WebSocket, RawData } from 'ws';
-import { createServer, Server } from 'http';
+import { createServer, Server, type IncomingMessage } from 'http';
+import { assertSafeBind, refuseOpenRequest } from './guard.js';
import type {
ITransport,
TransportType,
@@ -29,6 +30,10 @@ export interface WebSocketTransportConfig {
heartbeatTimeout?: number;
maxMessageSize?: number;
auth?: AuthConfig;
+ /** Accept a non-loopback bind (this transport has no token check at all). */
+ allowUnauthenticated?: boolean;
+ /** Browser origins allowed to connect, by exact name. */
+ allowedOrigins?: string[];
enableBinaryMode?: boolean;
}
@@ -77,6 +82,8 @@ export class WebSocketTransport extends EventEmitter implements ITransport {
path: this.config.path || '/ws',
});
+ assertSafeBind(this.config.host, false, this.config.allowUnauthenticated);
+
this.server = createServer((req, res) => {
res.writeHead(426, { 'Content-Type': 'text/plain' });
res.end('Upgrade Required - WebSocket connection expected');
@@ -87,6 +94,8 @@ export class WebSocketTransport extends EventEmitter implements ITransport {
path: this.config.path || '/ws',
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,
});
this.setupWebSocketHandlers();
diff --git a/v3/@claude-flow/mcp/src/types.ts b/v3/@claude-flow/mcp/src/types.ts
index b9b6bc3ee1..6c001d19d7 100644
--- a/v3/@claude-flow/mcp/src/types.ts
+++ b/v3/@claude-flow/mcp/src/types.ts
@@ -107,6 +107,8 @@ export interface MCPServerConfig {
tlsCert?: string;
tlsKey?: string;
auth?: AuthConfig;
+ /** Allow a non-loopback bind with no token. Off unless the operator opts in. */
+ allowUnauthenticated?: boolean;
loadBalancer?: LoadBalancerConfig;
connectionPool?: ConnectionPoolConfig;
corsEnabled?: boolean;