mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-12-03 22:12:01 +09:00
* fix(security): enforce transport and WebSocket limits (#4752) - x-gateway ws-proxy: release a connection slot once per connection; close/error on both sockets decremented `active` up to four times, which defeated the 500-connection cap. - mcp http transport: /ws now has maxPayload (maxMessageSize, default 10 MiB) and checks the bearer token in verifyClient, before the upgrade, using the same Authorization header as the HTTP routes (no ?token=). Unset token entries are skipped instead of throwing. - mcp http transport: cap legacy SSE streams on GET /mcp (maxSseClients, default 100); extra streams get 503 + Retry-After. - agent-federation fallback WebSocket listener: maxPayload (default 4 MiB, configurable) instead of the ws 100 MiB default. - agentbbs sync: redirect "error", reject an oversized Content-Length up front, and stream the body with a running byte cap instead of buffering it whole. Each limit has a test. * fix(mcp): keep ?token= on /ws, checked before the upgrade (#4752) Browsers cannot set Authorization on a WebSocket, so dropping ?token= would cut browser clients off /ws and make the HTTP transport behave differently from the standalone WebSocket transport. verifyClient now takes the token from the Authorization header or, failing that, from ?token=, still before the upgrade and still failing closed on an empty token list. ADR-479 describes the new check. Also: - maxMessageSize and maxSseClients fall back to their defaults unless they are positive numbers. - shared/src/mcp/transport/http.ts: /ws gets maxPayload (maxMessageSize, default 10 MiB) instead of the ws 100 MiB default. * chore(ruflo-x-gateway): bump to 0.10.5 for the ws-proxy slot fix Co-Authored-By: RuFlo <ruv@ruv.net> * chore(leaves): shared 3.0.9 for the /ws payload cap (#4752) The /ws maxPayload change in shared/src/mcp/transport/http.ts only reaches users through a standalone shared publish. shared 3.0.9 is published; the CLI and root manifests pin it and both lockfiles follow. Co-Authored-By: RuFlo <ruv@ruv.net> * test(ci): list the x-gateway ws-proxy node:test file with its siblings Root vitest cannot run plugins/ruflo-x-gateway node:test files (they run via the plugin's npm test), so each one is listed in ci-test-baseline.txt. The new ws-proxy test was missing, which failed the ratchet with 'No test suite found'. Co-Authored-By: RuFlo <ruv@ruv.net> --------- Co-authored-by: Rutvij97 <218486544+Rutvij97@users.noreply.github.com> Co-authored-by: rUv <ruv@ruv.net> Co-authored-by: r <r@x>
This commit is contained in:
18 files changed
+315
-54
No files matched your search
Generated
+4
-4
@@ -27,7 +27,7 @@
|
||||
"@claude-flow/neural": "3.0.3",
|
||||
"@claude-flow/plugin-agent-federation": "1.0.7",
|
||||
"@claude-flow/security": "3.0.7",
|
||||
"@claude-flow/shared": "3.0.8",
|
||||
"@claude-flow/shared": "3.0.9",
|
||||
"@electron/asar": "^4.3.1",
|
||||
"@iarna/toml": "^2.2.5",
|
||||
"@noble/ed25519": "2.3.0",
|
||||
@@ -282,9 +282,9 @@
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@claude-flow/shared": {
|
||||
"version": "3.0.8",
|
||||
"resolved": "https://registry.npmjs.org/@claude-flow/shared/-/shared-3.0.8.tgz",
|
||||
"integrity": "sha512-MeQY5KQpWTaRvF5mmFlV6vaogj6qN6SBNoK77D0/4sfUQrByAVMscpXq2KUZCMre8tdVE+r9+NW1ZQklyREpcw==",
|
||||
"version": "3.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@claude-flow/shared/-/shared-3.0.9.tgz",
|
||||
"integrity": "sha512-l1GJIDYKh7iteL4O0SI4fN1VNFZMcLT4ZqVB2utevNRpKw2YxA1tUGrVzXVI+BGvsyn9ZYvwpR/l7HjyaR4vwA==",
|
||||
"dependencies": {
|
||||
"@types/ws": "^8.5.10",
|
||||
"cors": "^2.8.5",
|
||||
|
||||
+1
-1
@@ -75,7 +75,7 @@
|
||||
"@claude-flow/neural": "3.0.3",
|
||||
"@claude-flow/plugin-agent-federation": "1.0.7",
|
||||
"@claude-flow/security": "3.0.7",
|
||||
"@claude-flow/shared": "3.0.8",
|
||||
"@claude-flow/shared": "3.0.9",
|
||||
"@electron/asar": "^4.3.1",
|
||||
"@iarna/toml": "^2.2.5",
|
||||
"@noble/ed25519": "2.3.0",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ruflo-x-gateway",
|
||||
"description": "Coordinate AI-agent swarms through signed federation messages, channels, and work claims. The remote Claude connector exposes a directory-safe Streamable HTTP MCP surface with OAuth-protected publishing and five ruv:// reference resources.",
|
||||
"version": "0.10.4",
|
||||
"version": "0.10.5",
|
||||
"repository": "https://github.com/ruvnet/ruflo",
|
||||
"author": {
|
||||
"name": "ruvnet",
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
Newest first. One `## <version> — <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; older versions: `git log -- plugins/ruflo-x-gateway`.
|
||||
|
||||
## 0.10.5 — 2026-11-18
|
||||
- fix: the WebSocket proxy released its connection slot once per close or error event, so a socket that fired both drove the 500-connection counter below its true value; each connection now releases its slot exactly once (#4752).
|
||||
|
||||
## 0.10.4 — 2026-11-09
|
||||
- fix(deps): zod ^4.6.7 (GHSA-mrhx-c7xc-m3w5: zod < 4.6.6 can exhaust memory validating oversized constrained collections).
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import WebSocket, { WebSocketServer } from 'ws';
|
||||
const MAX_CONN = 500, MAX_PAYLOAD = 256 * 1024; let active = 0;
|
||||
/** Live proxied connections (each counted once, however it closes). */
|
||||
export const activeConnections = () => active;
|
||||
// Transparent WebSocket proxy: client <-> this gateway <-> Nostr relay.
|
||||
export function attachWsProxy(server, relayUrl, paths = ['/', '/relay']) {
|
||||
const wss = new WebSocketServer({ noServer: true, perMessageDeflate: false, maxPayload: MAX_PAYLOAD });
|
||||
@@ -12,7 +14,12 @@ export function attachWsProxy(server, relayUrl, paths = ['/', '/relay']) {
|
||||
active++;
|
||||
client.on('message', (d) => { if (up.readyState === WebSocket.OPEN) up.send(d.toString()); });
|
||||
up.on('message', (d) => { if (client.readyState === WebSocket.OPEN) client.send(d.toString()); });
|
||||
const closeBoth = () => { active--; try { client.close(); } catch {} try { up.close(); } catch {} };
|
||||
// close and error can both fire on both sockets; release the slot only once.
|
||||
let released = false;
|
||||
const closeBoth = () => {
|
||||
if (!released) { released = true; active--; }
|
||||
try { client.close(); } catch {} try { up.close(); } catch {}
|
||||
};
|
||||
client.once('close', closeBoth); up.once('close', closeBoth);
|
||||
client.once('error', closeBoth); up.once('error', closeBoth);
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createServer } from 'node:http';
|
||||
import WebSocket, { WebSocketServer } from 'ws';
|
||||
import { attachWsProxy, activeConnections } from '../src/ws-proxy.mjs';
|
||||
|
||||
const listen = (srv) => new Promise((r) => srv.listen(0, '127.0.0.1', () => r(srv.address().port)));
|
||||
const settle = () => new Promise((r) => setTimeout(r, 100));
|
||||
|
||||
test('ws proxy releases each connection slot exactly once (#4752)', async () => {
|
||||
const relay = new WebSocketServer({ port: 0, host: '127.0.0.1' });
|
||||
await new Promise((r) => relay.once('listening', r));
|
||||
const relayUrl = `ws://127.0.0.1:${relay.address().port}`;
|
||||
const server = createServer();
|
||||
const wss = attachWsProxy(server, relayUrl);
|
||||
const port = await listen(server);
|
||||
const before = activeConnections();
|
||||
try {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const c = new WebSocket(`ws://127.0.0.1:${port}/relay`);
|
||||
await new Promise((r, j) => { c.once('open', r); c.once('error', j); });
|
||||
await settle();
|
||||
assert.equal(activeConnections(), before + 1);
|
||||
c.close();
|
||||
await settle();
|
||||
// close fires on both the client side and the relay side; the slot must be freed once.
|
||||
assert.equal(activeConnections(), before);
|
||||
}
|
||||
// Relay side going away first must also free exactly one slot.
|
||||
const c = new WebSocket(`ws://127.0.0.1:${port}/relay`);
|
||||
await new Promise((r, j) => { c.once('open', r); c.once('error', j); });
|
||||
await settle();
|
||||
for (const s of relay.clients) s.terminate();
|
||||
await settle();
|
||||
assert.equal(activeConnections(), before);
|
||||
} finally {
|
||||
wss.close(); server.close(); relay.close();
|
||||
}
|
||||
});
|
||||
@@ -139,6 +139,7 @@ plugins/ruflo-x-gateway/test/github.test.mjs
|
||||
plugins/ruflo-x-gateway/test/relay-robustness.test.mjs
|
||||
plugins/ruflo-x-gateway/test/registration-compat.test.mjs
|
||||
plugins/ruflo-x-gateway/test/client-ip.test.mjs
|
||||
plugins/ruflo-x-gateway/test/ws-proxy.test.mjs
|
||||
|
||||
# ruflo-chatgpt-federation: same pattern — plugin-local deps (jose, nostr-tools/pure) not resolvable from root vitest
|
||||
plugins/ruflo-chatgpt-federation/test/oauth.test.mjs
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
validateRoomId,
|
||||
MAX_HOPS,
|
||||
MAX_ENVELOPE_BYTES,
|
||||
MAX_SYNC_RESPONSE_BYTES,
|
||||
type SignedEnvelope,
|
||||
} from '../src/mcp-tools/agentbbs-federation.js';
|
||||
|
||||
@@ -359,6 +360,48 @@ describe('http transport (two real nodes)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('sync response limits (#4752)', () => {
|
||||
async function peerB() {
|
||||
const idB = await getNodeIdentity(dirB);
|
||||
addPeer(dirA, { nodeId: idB.nodeId, url: 'http://127.0.0.1:9', publicKey: idB.publicKey });
|
||||
return readPeers(dirA)[0];
|
||||
}
|
||||
|
||||
it('refuses to follow redirects from a peer', async () => {
|
||||
const peer = await peerB();
|
||||
let init: RequestInit | undefined;
|
||||
const fetchImpl = (async (_u: string, i?: RequestInit) => { init = i; return new Response('{"envelopes":[]}'); }) as typeof fetch;
|
||||
await syncRoomFromPeer(dirA, peer, 'sales-dd6531eb', fetchImpl);
|
||||
expect(init?.redirect).toBe('error');
|
||||
});
|
||||
|
||||
it('rejects a declared Content-Length over the cap without reading the body', async () => {
|
||||
const peer = await peerB();
|
||||
let pulled = 0;
|
||||
const body = new ReadableStream<Uint8Array>({ pull(c) { pulled++; c.enqueue(new Uint8Array(1024)); } });
|
||||
const fetchImpl = (async () => new Response(body, {
|
||||
headers: { 'content-length': String(MAX_SYNC_RESPONSE_BYTES + 1) },
|
||||
})) as typeof fetch;
|
||||
await expect(syncRoomFromPeer(dirA, peer, 'sales-dd6531eb', fetchImpl)).rejects.toThrow(/size cap/);
|
||||
expect(pulled).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('stops reading a streamed body as soon as it passes the cap', async () => {
|
||||
const peer = await peerB();
|
||||
const chunk = new Uint8Array(1024 * 1024);
|
||||
let sent = 0;
|
||||
let cancelled = false;
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
pull(c) { sent += chunk.byteLength; c.enqueue(chunk); },
|
||||
cancel() { cancelled = true; },
|
||||
});
|
||||
const fetchImpl = (async () => new Response(body)) as typeof fetch;
|
||||
await expect(syncRoomFromPeer(dirA, peer, 'sales-dd6531eb', fetchImpl)).rejects.toThrow(/size cap/);
|
||||
expect(cancelled).toBe(true);
|
||||
expect(sent).toBeLessThanOrEqual(MAX_SYNC_RESPONSE_BYTES + 2 * chunk.byteLength);
|
||||
});
|
||||
});
|
||||
|
||||
describe('convergence', () => {
|
||||
it('two nodes that each publish converge on the same set after mutual sync', async () => {
|
||||
const idA = await getNodeIdentity(dirA);
|
||||
|
||||
@@ -114,7 +114,7 @@
|
||||
"@claude-flow/neural": "3.0.3",
|
||||
"@claude-flow/plugin-agent-federation": "1.0.7",
|
||||
"@claude-flow/security": "3.0.7",
|
||||
"@claude-flow/shared": "3.0.8",
|
||||
"@claude-flow/shared": "3.0.9",
|
||||
"@iarna/toml": "^2.2.5",
|
||||
"@metaharness/darwin": "~0.14.0",
|
||||
"@noble/ed25519": "2.3.0",
|
||||
|
||||
@@ -416,6 +416,38 @@ export async function mergeEnvelopes(
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a response body, giving up as soon as it passes `cap` bytes, so an
|
||||
* oversized peer reply is never buffered whole before the size check.
|
||||
*/
|
||||
export async function readCappedText(res: Response, cap: number, peerNodeId: string): Promise<string> {
|
||||
const tooBig = () => new Error(`peer ${peerNodeId} response exceeds size cap`);
|
||||
const declared = Number(res.headers?.get?.('content-length'));
|
||||
if (Number.isFinite(declared) && declared > cap) {
|
||||
await res.body?.cancel().catch(() => undefined);
|
||||
throw tooBig();
|
||||
}
|
||||
if (!res.body) {
|
||||
const text = await res.text();
|
||||
if (Buffer.byteLength(text, 'utf8') > cap) throw tooBig();
|
||||
return text;
|
||||
}
|
||||
const reader = res.body.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
total += value.byteLength;
|
||||
if (total > cap) {
|
||||
await reader.cancel().catch(() => undefined);
|
||||
throw tooBig();
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
return Buffer.concat(chunks, total).toString('utf8');
|
||||
}
|
||||
|
||||
/** Pull one room from one peer and merge what verifies. */
|
||||
export async function syncRoomFromPeer(
|
||||
basePath: string,
|
||||
@@ -431,11 +463,10 @@ export async function syncRoomFromPeer(
|
||||
const timer = setTimeout(() => controller.abort(), SYNC_TIMEOUT_MS);
|
||||
let body: any;
|
||||
try {
|
||||
const res = await fetchImpl(url, { signal: controller.signal, headers: { accept: 'application/json' } });
|
||||
// A peer URL is pinned by the operator; a redirect would send the pull somewhere they never approved.
|
||||
const res = await fetchImpl(url, { signal: controller.signal, headers: { accept: 'application/json' }, redirect: 'error' });
|
||||
if (!res.ok) throw new Error(`peer ${peer.nodeId} returned ${res.status}`);
|
||||
const text = await res.text();
|
||||
if (text.length > MAX_SYNC_RESPONSE_BYTES) throw new Error(`peer ${peer.nodeId} response exceeds size cap`);
|
||||
body = JSON.parse(text);
|
||||
body = JSON.parse(await readCappedText(res, MAX_SYNC_RESPONSE_BYTES, peer.nodeId));
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import type { Server } from 'node:http';
|
||||
import { WebSocket } from 'ws';
|
||||
import { HttpTransport } from '../src/transport/http.js';
|
||||
import type { ILogger } from '../src/types.js';
|
||||
|
||||
const TOKEN = 'a-long-enough-token-4752';
|
||||
const logger: ILogger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
|
||||
let stop: (() => Promise<void>) | undefined;
|
||||
afterEach(async () => { await stop?.(); stop = undefined; });
|
||||
|
||||
async function open(extra: Record<string, unknown> = {}): Promise<number> {
|
||||
const t = new HttpTransport(logger, { host: '127.0.0.1', port: 0, ...extra } as never);
|
||||
t.onRequest(async (r) => ({ jsonrpc: '2.0', id: r.id, result: { ok: true } }));
|
||||
await t.start();
|
||||
stop = () => t.stop();
|
||||
return ((t as unknown as { server: Server }).server.address() as AddressInfo).port;
|
||||
}
|
||||
|
||||
/** 'open' when the upgrade is accepted, else the HTTP status it was refused with. */
|
||||
const upgrade = (url: string, headers: Record<string, string> = {}): Promise<'open' | number> =>
|
||||
new Promise((resolve) => {
|
||||
const ws = new WebSocket(url, { headers });
|
||||
ws.on('open', () => { ws.close(); resolve('open'); });
|
||||
ws.on('unexpected-response', (_req, res) => resolve(res.statusCode ?? 0));
|
||||
ws.on('error', () => resolve(0));
|
||||
});
|
||||
|
||||
describe('/ws on the HTTP transport (#4752)', () => {
|
||||
const auth = { auth: { enabled: true, method: 'token', tokens: [TOKEN] } };
|
||||
|
||||
it('refuses the upgrade itself when the token is missing or wrong', async () => {
|
||||
const port = await open(auth);
|
||||
expect(await upgrade(`ws://127.0.0.1:${port}/ws`)).toBe(401);
|
||||
expect(await upgrade(`ws://127.0.0.1:${port}/ws`, { authorization: 'Bearer wrong-wrong-wrong' })).toBe(401);
|
||||
expect(await upgrade(`ws://127.0.0.1:${port}/ws`, { authorization: `Bearer ${TOKEN}` })).toBe('open');
|
||||
});
|
||||
|
||||
it('also takes ?token= (browsers cannot set Authorization), checked before the upgrade', async () => {
|
||||
const port = await open(auth);
|
||||
expect(await upgrade(`ws://127.0.0.1:${port}/ws?token=${TOKEN}`)).toBe('open');
|
||||
expect(await upgrade(`ws://127.0.0.1:${port}/ws?token=wrong-wrong-wrong`)).toBe(401);
|
||||
expect(await upgrade(`ws://127.0.0.1:${port}/ws?token=`)).toBe(401);
|
||||
});
|
||||
|
||||
it('fails closed with an empty token list, header or query', async () => {
|
||||
const port = await open({ auth: { enabled: true, method: 'token', tokens: [] } });
|
||||
expect(await upgrade(`ws://127.0.0.1:${port}/ws?token=${TOKEN}`)).toBe(401);
|
||||
expect(await upgrade(`ws://127.0.0.1:${port}/ws`, { authorization: `Bearer ${TOKEN}` })).toBe(401);
|
||||
});
|
||||
|
||||
it('skips an unset token entry instead of throwing during the upgrade', async () => {
|
||||
const port = await open({ auth: { enabled: true, method: 'token', tokens: [undefined, TOKEN] } });
|
||||
expect(await upgrade(`ws://127.0.0.1:${port}/ws`, { authorization: `Bearer ${TOKEN}` })).toBe('open');
|
||||
});
|
||||
|
||||
it('closes a connection that sends a frame over maxMessageSize', async () => {
|
||||
const port = await open({ maxMessageSize: 1024 });
|
||||
const code = await new Promise<number>((resolve) => {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
|
||||
ws.on('open', () => ws.send('x'.repeat(4096)));
|
||||
ws.on('close', (c) => resolve(c));
|
||||
ws.on('error', () => undefined);
|
||||
});
|
||||
expect(code).toBe(1009);
|
||||
});
|
||||
|
||||
it('ignores a non-positive maxMessageSize and keeps the default cap', async () => {
|
||||
const port = await open({ maxMessageSize: -1 });
|
||||
const wss = await new Promise<string>((resolve) => {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
|
||||
ws.on('open', () => { ws.send('x'.repeat(4096)); setTimeout(() => { resolve(ws.readyState === WebSocket.OPEN ? 'open' : 'closed'); ws.close(); }, 200); });
|
||||
ws.on('error', () => undefined);
|
||||
});
|
||||
expect(wss).toBe('open');
|
||||
});
|
||||
});
|
||||
|
||||
describe('legacy SSE streams on GET /mcp (#4752)', () => {
|
||||
it('refuses new streams past maxSseClients and accepts again once one closes', async () => {
|
||||
const port = await open({ maxSseClients: 2 });
|
||||
const url = `http://127.0.0.1:${port}/mcp`;
|
||||
const first = new AbortController();
|
||||
const second = new AbortController();
|
||||
expect((await fetch(url, { signal: first.signal })).status).toBe(200);
|
||||
expect((await fetch(url, { signal: second.signal })).status).toBe(200);
|
||||
const refused = await fetch(url);
|
||||
expect(refused.status).toBe(503);
|
||||
expect(refused.headers.get('retry-after')).toBe('5');
|
||||
|
||||
first.abort();
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
const third = new AbortController();
|
||||
expect((await fetch(url, { signal: third.signal })).status).toBe(200);
|
||||
second.abort();
|
||||
third.abort();
|
||||
});
|
||||
});
|
||||
@@ -38,6 +38,10 @@ export interface HttpTransportConfig {
|
||||
/** Accept a non-loopback bind with no token (the operator's own risk). */
|
||||
allowUnauthenticated?: boolean;
|
||||
maxRequestSize?: string;
|
||||
/** Largest WebSocket frame accepted on /ws, in bytes (default 10 MiB). */
|
||||
maxMessageSize?: number;
|
||||
/** Most legacy SSE streams open at once on GET /mcp (default 100). */
|
||||
maxSseClients?: number;
|
||||
requestTimeout?: number;
|
||||
rateLimit?: {
|
||||
windowMs?: number;
|
||||
@@ -45,6 +49,9 @@ export interface HttpTransportConfig {
|
||||
};
|
||||
}
|
||||
|
||||
const DEFAULT_MAX_WS_PAYLOAD = 10 * 1024 * 1024;
|
||||
const DEFAULT_MAX_SSE_CLIENTS = 100;
|
||||
|
||||
export class HttpTransport extends EventEmitter implements ITransport {
|
||||
public readonly type: TransportType = 'http';
|
||||
|
||||
@@ -90,9 +97,14 @@ export class HttpTransport extends EventEmitter implements ITransport {
|
||||
this.wss = new WebSocketServer({
|
||||
server: this.server,
|
||||
path: '/ws',
|
||||
maxPayload: positiveOr(this.config.maxMessageSize, DEFAULT_MAX_WS_PAYLOAD),
|
||||
// Authenticate before the upgrade. Browsers cannot set Authorization on a
|
||||
// WebSocket, so /ws also takes `?token=`, like the standalone WebSocket transport.
|
||||
// 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.config.auth?.enabled === true
|
||||
? this.validateUpgradeAuth(info.req)
|
||||
: refuseOpenRequest(info.req, this.config.host, this.config.corsOrigins) === undefined,
|
||||
});
|
||||
|
||||
this.setupWebSocketHandlers();
|
||||
@@ -328,6 +340,14 @@ export class HttpTransport extends EventEmitter implements ITransport {
|
||||
return;
|
||||
}
|
||||
|
||||
const maxSse = positiveOr(this.config.maxSseClients, DEFAULT_MAX_SSE_CLIENTS);
|
||||
if (this.sseClients.size >= maxSse) {
|
||||
this.logger.warn('SSE stream refused: client limit reached', { limit: maxSse });
|
||||
res.status(503).setHeader('Retry-After', '5');
|
||||
res.json({ jsonrpc: '2.0', id: null, error: { code: -32000, message: 'Too many open streams' } });
|
||||
return;
|
||||
}
|
||||
|
||||
const sessionId = randomUUID();
|
||||
res.status(200);
|
||||
res.setHeader('Content-Type', 'text/event-stream');
|
||||
@@ -384,35 +404,7 @@ export class HttpTransport extends EventEmitter implements ITransport {
|
||||
|
||||
// SECURITY: Handle WebSocket authentication via upgrade request
|
||||
this.wss.on('connection', (ws, req) => {
|
||||
// Validate authentication if enabled
|
||||
if (this.config.auth?.enabled) {
|
||||
const url = new URL(req.url || '', `http://${req.headers.host}`);
|
||||
const token = url.searchParams.get('token') || req.headers['authorization']?.replace(/^Bearer\s+/i, '');
|
||||
|
||||
if (!token) {
|
||||
this.logger.warn('WebSocket connection rejected: no authentication token');
|
||||
ws.close(4001, 'Authentication required');
|
||||
return;
|
||||
}
|
||||
|
||||
// SECURITY: Timing-safe token validation
|
||||
let valid = false;
|
||||
if (this.config.auth.tokens?.length) {
|
||||
for (const validToken of this.config.auth.tokens) {
|
||||
if (this.timingSafeCompare(token, validToken)) {
|
||||
valid = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!valid) {
|
||||
this.logger.warn('WebSocket connection rejected: invalid token');
|
||||
ws.close(4003, 'Invalid token');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// The token was already checked in verifyClient, before the upgrade.
|
||||
this.activeConnections.add(ws);
|
||||
this.logger.info('WebSocket client connected', {
|
||||
total: this.activeConnections.size,
|
||||
@@ -604,25 +596,41 @@ export class HttpTransport extends EventEmitter implements ITransport {
|
||||
});
|
||||
}
|
||||
|
||||
private validateAuth(req: Request): { valid: boolean } {
|
||||
const given = bearerToken(req.headers.authorization);
|
||||
private validateAuth(req: Pick<IncomingMessage, 'headers'>): { valid: boolean } {
|
||||
return { valid: this.matchesConfiguredToken(bearerToken(req.headers.authorization)) };
|
||||
}
|
||||
|
||||
/** /ws upgrade: token from `Authorization: Bearer`, else from `?token=`. */
|
||||
private validateUpgradeAuth(req: IncomingMessage): boolean {
|
||||
const fromQuery = new URL(req.url ?? '', 'http://localhost').searchParams.get('token') ?? undefined;
|
||||
return this.matchesConfiguredToken(bearerToken(req.headers.authorization) ?? fromQuery);
|
||||
}
|
||||
|
||||
private matchesConfiguredToken(given: string | undefined): boolean {
|
||||
if (!given) {
|
||||
return { valid: false };
|
||||
return false;
|
||||
}
|
||||
|
||||
// Fail closed: auth enabled with no configured token accepts nothing.
|
||||
const tokens = this.config.auth?.tokens ?? [];
|
||||
let valid = false;
|
||||
for (const validToken of tokens) {
|
||||
// An unset entry (e.g. `tokens: [process.env.X]` with X unset) matches nothing.
|
||||
if (typeof validToken !== 'string' || validToken.length === 0) continue;
|
||||
// No early exit, so timing does not depend on which token matched.
|
||||
if (this.timingSafeCompare(given, validToken)) {
|
||||
valid = true;
|
||||
}
|
||||
}
|
||||
return { valid };
|
||||
return valid;
|
||||
}
|
||||
}
|
||||
|
||||
/** A configured limit when it is a positive number, else the default. */
|
||||
function positiveOr(value: number | undefined, fallback: number): number {
|
||||
return typeof value === 'number' && value > 0 ? value : fallback;
|
||||
}
|
||||
|
||||
export function createHttpTransport(
|
||||
logger: ILogger,
|
||||
config: HttpTransportConfig
|
||||
|
||||
+16
-2
@@ -13,6 +13,7 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
DEFAULT_FEDERATION_MAX_PAYLOAD,
|
||||
loadFederationTransport,
|
||||
} from '../../src/transport/midstream-aware-loader.js';
|
||||
|
||||
@@ -36,7 +37,7 @@ vi.mock('agentic-flow/transport/loader', async () => {
|
||||
};
|
||||
});
|
||||
|
||||
const wsServerOptions = vi.hoisted(() => [] as Array<{ port?: number; host?: string }>);
|
||||
const wsServerOptions = vi.hoisted(() => [] as Array<{ port?: number; host?: string; maxPayload?: number }>);
|
||||
|
||||
vi.mock('ws', async () => {
|
||||
class MockWebSocket {
|
||||
@@ -45,7 +46,7 @@ vi.mock('ws', async () => {
|
||||
close() {}
|
||||
}
|
||||
class MockWebSocketServer {
|
||||
constructor(options: { port?: number; host?: string }) {
|
||||
constructor(options: { port?: number; host?: string; maxPayload?: number }) {
|
||||
wsServerOptions.push(options);
|
||||
}
|
||||
on(event: string, handler: () => void) {
|
||||
@@ -166,6 +167,19 @@ describe('loadFederationTransport — ADR-120 Step 2', () => {
|
||||
expect(wsServerOptions.map((o) => o.host)).toEqual(['127.0.0.1', '0.0.0.0', '127.0.0.1']);
|
||||
});
|
||||
|
||||
it('the fallback listener caps inbound frames instead of using the ws 100 MiB default (#4752)', async () => {
|
||||
const mod = await import('agentic-flow/transport/loader');
|
||||
const loaderFn = (mod as unknown as { loadQuicTransport: ReturnType<typeof vi.fn> })
|
||||
.loadQuicTransport;
|
||||
for (let i = 0; i < 2; i++) loaderFn.mockResolvedValueOnce({ send: vi.fn() });
|
||||
|
||||
wsServerOptions.length = 0;
|
||||
await (await loadFederationTransport({ port: 0 })).transport.listen!(0);
|
||||
await (await loadFederationTransport({ port: 0, maxPayload: 65536 })).transport.listen!(0);
|
||||
|
||||
expect(wsServerOptions.map((o) => o.maxPayload)).toEqual([DEFAULT_FEDERATION_MAX_PAYLOAD, 65536]);
|
||||
});
|
||||
|
||||
it('returned envelope has the documented LoadedFederationTransport shape', async () => {
|
||||
const loaded = await loadFederationTransport();
|
||||
expect(Object.keys(loaded).sort()).toEqual(
|
||||
|
||||
@@ -50,10 +50,15 @@ export interface AgentTransport {
|
||||
close?: () => Promise<void> | void;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
/** Largest inbound frame the fallback WebSocket listener accepts by default. */
|
||||
export const DEFAULT_FEDERATION_MAX_PAYLOAD = 4 * 1024 * 1024;
|
||||
|
||||
export interface QuicTransportConfig {
|
||||
port?: number;
|
||||
host?: string;
|
||||
serverName?: string;
|
||||
/** Largest inbound WebSocket frame, in bytes (default 4 MiB). */
|
||||
maxPayload?: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
@@ -184,7 +189,9 @@ class WebSocketFallbackTransport implements AgentTransport {
|
||||
// host would bind every interface, so it counts as unset.
|
||||
async listen(port = Number(this.config.port ?? 0), host = this.config.host || '127.0.0.1'): Promise<void> {
|
||||
const { WebSocketServer } = await import('ws');
|
||||
const server = new WebSocketServer({ port, host }) as WebSocketServerLike;
|
||||
// ws defaults to 100 MiB per frame; federation envelopes are small JSON.
|
||||
const maxPayload = Number(this.config.maxPayload) > 0 ? Number(this.config.maxPayload) : DEFAULT_FEDERATION_MAX_PAYLOAD;
|
||||
const server = new WebSocketServer({ port, host, maxPayload }) as WebSocketServerLike;
|
||||
this.server = server;
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@claude-flow/shared",
|
||||
"version": "3.0.8",
|
||||
"version": "3.0.9",
|
||||
"type": "module",
|
||||
"description": "Shared types, event bus, config schemas and validators, MCP transport helpers and resilience utilities used by the Ruflo (claude-flow) V3 packages.",
|
||||
"main": "dist/index.js",
|
||||
|
||||
@@ -47,9 +47,13 @@ export interface HttpTransportConfig {
|
||||
/** Accept a non-loopback bind with no token (the operator's own risk). */
|
||||
allowUnauthenticated?: boolean;
|
||||
maxRequestSize?: string;
|
||||
/** Largest WebSocket frame accepted on /ws, in bytes (default 10 MiB). */
|
||||
maxMessageSize?: number;
|
||||
requestTimeout?: number;
|
||||
}
|
||||
|
||||
const DEFAULT_MAX_WS_PAYLOAD = 10 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* HTTP Transport Implementation
|
||||
*/
|
||||
@@ -103,6 +107,10 @@ export class HttpTransport extends EventEmitter implements ITransport {
|
||||
this.wss = new WebSocketServer({
|
||||
server: this.server,
|
||||
path: '/ws',
|
||||
maxPayload:
|
||||
typeof this.config.maxMessageSize === 'number' && this.config.maxMessageSize > 0
|
||||
? this.config.maxMessageSize
|
||||
: DEFAULT_MAX_WS_PAYLOAD,
|
||||
verifyClient: (info: { req: IncomingMessage }) =>
|
||||
this.config.auth?.enabled === true || refuseOpenRequest(info.req, this.config.host, this.config.corsOrigins) === undefined,
|
||||
});
|
||||
|
||||
@@ -61,9 +61,10 @@ environment variable `RUFLO_MCP_HTTP_TOKEN`. An unset or empty variable means no
|
||||
"message":"Unauthorized"}}`. The header and token are never logged.
|
||||
- Fail closed: auth enabled with an empty token list accepts nothing (this was the fail-open fixed with this change).
|
||||
- `GET /health` stays public and, when auth is on, answers only `{"status":"ok"}`: no timestamp, no connection count.
|
||||
- The WebSocket endpoint on this transport (`/ws`) checks the token in its connection handler, from `Authorization: Bearer` or from a
|
||||
`?token=` query parameter, and closes the socket with 4001 (none) or 4003 (invalid). An HTTP upgrade does not pass through the middleware
|
||||
above, so this handler is the only check on that path.
|
||||
- The WebSocket endpoint on this transport (`/ws`) checks the token in `verifyClient`, before the upgrade, from `Authorization: Bearer`
|
||||
or from a `?token=` query parameter (browsers cannot set headers on a WebSocket), and refuses a missing or invalid token with HTTP 401.
|
||||
An HTTP upgrade does not pass through the middleware above, so this is the only check on that path. Frames are capped by
|
||||
`maxMessageSize` (default 10 MiB).
|
||||
- Tool calls reach the handler with `transport: 'http'` (or `'websocket'`), which is what ADR-476 uses to classify a caller as remote.
|
||||
|
||||
### 2.4 Behaviour matrix
|
||||
|
||||
Generated
+1
-1
@@ -136,7 +136,7 @@ importers:
|
||||
specifier: 3.0.7
|
||||
version: link:../security
|
||||
'@claude-flow/shared':
|
||||
specifier: 3.0.8
|
||||
specifier: 3.0.9
|
||||
version: link:../shared
|
||||
'@electron/asar':
|
||||
specifier: ^4.3.1
|
||||
|
||||
Reference in new issue
Block a user