🌊 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(federation): peer identity comes from operator-pinned keys; loopback listener default (#4514)
rUvde8168b95247
diff --git a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/current-peer-trust-3561.test.ts b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/current-peer-trust-3561.test.tsindex d771bb4c1a..e73dc2b61b 100644--- a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/current-peer-trust-3561.test.ts+++ b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/current-peer-trust-3561.test.ts@@ -22,7 +22,7 @@ function manifest(nodeId: string): FederationManifest {async function fixture(resolveTrust = true) {let counter = 0;// Deterministic signing adapters isolate trust authorization from cryptography and transport.- const discovery = new DiscoveryService({ signManifest: async () => 'fixture-signature', verifyManifest: async () => true });+ const discovery = new DiscoveryService({ signManifest: async () => 'fixture-signature', verifyManifest: async () => true, pinnedKeyFor: (id) => `${id}-key` });const handshake = new HandshakeService({ generateSessionId: () => `session-${++counter}`,generateSessionToken: () => `token-${++counter}`, generateNonce: () => `nonce-${++counter}`,signChallenge: async () => 'signature', verifySignature: async () => true,diff --git a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/discovery-service.test.ts b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/discovery-service.test.tsindex 1e7a0ab05c..2a5ed3c4fd 100644--- a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/discovery-service.test.ts+++ b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/discovery-service.test.ts@@ -142,7 +142,8 @@ describe('DiscoveryService', () => {expect(node.trustLevel).toBe(TrustLevel.UNTRUSTED);});- it('should add a peer with VERIFIED trust level when a valid manifest is provided', async () => {+ it('should add a peer with VERIFIED trust level when a valid manifest carries the pinned key', async () => {+ service = new DiscoveryService({ ...deps, pinnedKeyFor: (id) => (id === 'node-1' ? 'pk-1' : undefined) });const manifest = makeManifest({ signature: 'valid' });const node = await service.addStaticPeer('https://peer1.example.com', manifest);@@ -150,6 +151,20 @@ describe('DiscoveryService', () => {expect(node.nodeId).toBe('node-1');});+ it('keeps a self-signed manifest UNTRUSTED when no key is pinned for the node', async () => {+ const node = await service.addStaticPeer('https://peer1.example.com', makeManifest({ signature: 'valid' }));++ expect(node.trustLevel).toBe(TrustLevel.UNTRUSTED);+ });++ it('rejects a manifest whose key is not the pinned one, however well it is signed', async () => {+ service = new DiscoveryService({ ...deps, pinnedKeyFor: () => 'the-real-key' });++ await expect(+ service.addStaticPeer('https://peer1.example.com', makeManifest({ signature: 'valid' })),+ ).rejects.toThrow(/pinned key/i);+ });+it('should throw when provided an invalid manifest', async () => {const manifest = makeManifest({ signature: 'invalid' });diff --git a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/handshake-key-pinning.test.ts b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/handshake-key-pinning.test.tsnew file mode 100644index 0000000000..dec358d518--- /dev/null+++ b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/handshake-key-pinning.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';+import { HandshakeService } from '../../src/domain/services/handshake-service.js';+import { FederationNode } from '../../src/domain/entities/federation-node.js';+import { TrustLevel } from '../../src/domain/entities/trust-level.js';++const PINNED = 'aa'.repeat(32);+const caps = { agentTypes: [], maxConcurrentSessions: 1, supportedProtocols: ['websocket'], complianceModes: [] };+const remote = () => FederationNode.create({ nodeId: 'peer', publicKey: '', endpoint: 'ws://peer:1', capabilities: caps });+let n = 0;+const service = (pins?: Record<string, string>) =>+ new HandshakeService({+ generateSessionId: () => `s-${++n}`, generateSessionToken: () => `t-${++n}`, generateNonce: () => `nonce-${++n}`,+ signChallenge: async () => 'sig', verifySignature: async () => true,+ ...(pins ? { pinnedKeyFor: (id: string) => pins[id] } : {}),+ getLocalNodeId: () => 'local', getLocalPublicKey: () => 'local-key', getLocalCapabilities: () => ['send'],+ });+const answer = async (svc: HandshakeService, node: FederationNode, publicKey: string) => {+ const challenge = await svc.initiateHandshake(node);+ return svc.verifyChallenge({ challengeId: challenge.challengeId, signedNonce: 'sig', publicKey, nodeId: 'peer', capabilities: ['send'] } as never, node);+};++const other = () => FederationNode.create({ nodeId: 'someone-else', publicKey: '', endpoint: 'ws://x:1', capabilities: caps });++describe('a handshake proves possession of a key, not who holds it', () => {+ it('attests a peer that answers with the key pinned for its node id', async () => {+ const node = remote();+ const result = await answer(service({ peer: PINNED }), node, PINNED);+ expect(result.success).toBe(true);+ expect(result.session!.trustLevel).toBe(TrustLevel.ATTESTED);+ expect(node.trustLevel).toBe(TrustLevel.ATTESTED);+ });++ it('refuses a peer that signs with a different key than the pinned one', async () => {+ const node = remote();+ const result = await answer(service({ peer: PINNED }), node, 'bb'.repeat(32));+ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/pinned key/) });+ expect(node.trustLevel).toBe(TrustLevel.UNTRUSTED);+ });++ it('refuses a response relayed by a node other than the one challenged, even with the right key', async () => {+ const svc = service({ peer: PINNED, 'someone-else': PINNED });+ const challenge = await svc.initiateHandshake(remote());+ const result = await svc.verifyChallenge({ challengeId: challenge.challengeId, signedNonce: 'sig', publicKey: PINNED, capabilities: ['send'] } as never, other());+ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/not from the node/) });+ });++ it('never attests a peer with no pinned key, whatever key it supplies', async () => {+ for (const svc of [service({}), service()]) {+ const node = remote();+ const result = await answer(svc, node, PINNED);+ expect(result.success).toBe(true);+ expect(result.pinned).toBe(false);+ expect(result.session!.trustLevel).toBe(TrustLevel.UNTRUSTED);+ expect(node.trustLevel).toBe(TrustLevel.UNTRUSTED);+ }+ });+});diff --git a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/plugin.test.ts b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/plugin.test.tsindex c37567d437..9173341bbf 100644--- a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/plugin.test.ts+++ b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/plugin.test.ts@@ -176,6 +176,8 @@ describe('AgentFederationPlugin', () => {});it('trusts JCS only from a verified peer manifest, never endpoint self-negotiation', async () => {+ const trustedPeerKeys: Record<string, string> = {};+ (context as any).config.trustedPeerKeys = trustedPeerKeys;await plugin.initialize(context as any);const registered = (name: string) =>context.services.register.mock.calls.find(([serviceName]) => serviceName === name)?.[1] as any;@@ -241,6 +243,12 @@ describe('AgentFederationPlugin', () => {});const signedPeerManifest = peerDiscovery.getLocalManifest();+ // A self-signed manifest earns nothing until the operator pins the peer's key.+ const unpinned = await coordinator.joinPeer(signedPeerManifest.endpoint, signedPeerManifest);+ expect(unpinned.trustLevel).toBe(TrustLevel.UNTRUSTED);+ await coordinator.leavePeer(unpinned.remoteNodeId);+ trustedPeerKeys[signedPeerManifest.nodeId] = signedPeerManifest.publicKey;+const verified = await coordinator.joinPeer(signedPeerManifest.endpoint,signedPeerManifest,diff --git a/v3/@claude-flow/plugin-agent-federation/src/application/federation-coordinator.ts b/v3/@claude-flow/plugin-agent-federation/src/application/federation-coordinator.tsindex 0f5ce1a1b3..e4fb1ae9f8 100644--- a/v3/@claude-flow/plugin-agent-federation/src/application/federation-coordinator.ts+++ b/v3/@claude-flow/plugin-agent-federation/src/application/federation-coordinator.ts@@ -218,7 +218,7 @@ export class FederationCoordinator {metadata: { endpoint },});- return this.establishSession(node, manifest !== undefined);+ return this.establishSession(node, manifest !== undefined && this.discovery.isPinned(manifest));}async leavePeer(nodeId: string): Promise<void> {diff --git a/v3/@claude-flow/plugin-agent-federation/src/domain/services/discovery-service.ts b/v3/@claude-flow/plugin-agent-federation/src/domain/services/discovery-service.tsindex cd2d5eccd8..11cf76cf09 100644--- a/v3/@claude-flow/plugin-agent-federation/src/domain/services/discovery-service.ts+++ b/v3/@claude-flow/plugin-agent-federation/src/domain/services/discovery-service.ts@@ -29,6 +29,12 @@ export interface FederationManifest {export interface DiscoveryServiceDeps {signManifest: (manifest: Omit<FederationManifest, 'signature'>) => Promise<string>;verifyManifest: (manifest: FederationManifest) => Promise<boolean>;+ /**+ * The Ed25519 key the operator pinned for a node id (hex). A manifest is signed with the key+ * it carries, so on its own it only proves the sender holds that key; it earns VERIFIED trust+ * only when the carried key is the pinned one.+ */+ pinnedKeyFor?: (nodeId: string) => string | undefined;onPeerDiscovered?: (node: FederationNode) => void;}@@ -101,6 +107,11 @@ export class DiscoveryService {return discovered;}+ /** Whether the manifest carries the key the operator pinned for its node id. */+ isPinned(manifest: Pick<FederationManifest, 'nodeId' | 'publicKey'>): boolean {+ return this.deps.pinnedKeyFor?.(manifest.nodeId)?.toLowerCase() === manifest.publicKey.toLowerCase();+ }+async addStaticPeer(endpoint: string, manifest?: FederationManifest): Promise<FederationNode> {if (manifest) {if (manifest.endpoint !== endpoint) {@@ -110,7 +121,12 @@ export class DiscoveryService {if (!valid) {throw new Error(`Invalid manifest signature for endpoint: ${endpoint}`);}+ const pinned = this.deps.pinnedKeyFor?.(manifest.nodeId);+ if (pinned !== undefined && pinned.toLowerCase() !== manifest.publicKey.toLowerCase()) {+ throw new Error(`Manifest key for ${manifest.nodeId} does not match the pinned key`);+ }}+ const pinnedManifest = manifest !== undefined && this.isPinned(manifest);const nodeId = manifest?.nodeId ?? `static-${this.hashEndpoint(endpoint)}`;const existing = this.knownPeers.get(nodeId);@@ -129,7 +145,8 @@ export class DiscoveryService {supportedProtocols: ['websocket', 'http'],complianceModes: [],},- trustLevel: manifest ? TrustLevel.VERIFIED : TrustLevel.UNTRUSTED,+ // A self-signed manifest is not an identity: only a pinned key makes a peer VERIFIED.+ trustLevel: pinnedManifest ? TrustLevel.VERIFIED : TrustLevel.UNTRUSTED,metadata: {discoveryMechanism: 'static' as DiscoveryMechanism,version: manifest?.version,diff --git a/v3/@claude-flow/plugin-agent-federation/src/domain/services/handshake-service.ts b/v3/@claude-flow/plugin-agent-federation/src/domain/services/handshake-service.tsindex 651a63fee8..2d8e319a0a 100644--- a/v3/@claude-flow/plugin-agent-federation/src/domain/services/handshake-service.ts+++ b/v3/@claude-flow/plugin-agent-federation/src/domain/services/handshake-service.ts@@ -21,6 +21,8 @@ export interface HandshakeResult {readonly success: boolean;readonly session?: FederationSession;readonly error?: string;+ /** The peer answered with the key pinned for its node id. False means the key was only claimed. */+ readonly pinned?: boolean;}export interface HandshakeServiceDeps {@@ -29,6 +31,8 @@ export interface HandshakeServiceDeps {generateNonce: () => string;signChallenge: (nonce: string) => Promise<string>;verifySignature: (nonce: string, signature: string, publicKey: string) => Promise<boolean>;+ /** The Ed25519 key (hex) the operator pinned for a node id. Without a pin, a handshake proves nothing about who answered. */+ pinnedKeyFor?: (nodeId: string) => string | undefined;getLocalNodeId: () => string;getLocalPublicKey: () => string;getLocalCapabilities: () => readonly string[];@@ -99,11 +103,25 @@ export class HandshakeService {return { success: false, error: 'Unknown or expired challenge' };}+ // A response answers one challenge, issued to one node: it cannot be replayed by another.+ if (pending.challenge.targetNodeId !== remoteNode.nodeId) {+ this.pendingChallenges.delete(response.challengeId);+ return { success: false, error: 'Response is not from the node that was challenged' };+ }+if (Date.now() > pending.expiresAt) {this.pendingChallenges.delete(response.challengeId);return { success: false, error: 'Challenge expired' };}+ // The response carries its own key, so a valid signature only proves possession of that key.+ // Identity comes from the key the operator pinned for this node id.+ const pinned = this.deps.pinnedKeyFor?.(remoteNode.nodeId);+ if (pinned !== undefined && pinned.toLowerCase() !== response.publicKey.toLowerCase()) {+ this.pendingChallenges.delete(response.challengeId);+ return { success: false, error: 'Peer key does not match the pinned key' };+ }+const isValid = await this.deps.verifySignature(pending.challenge.nonce,response.signedNonce,@@ -126,7 +144,7 @@ export class HandshakeService {sessionId: this.deps.generateSessionId(),localNodeId: this.deps.getLocalNodeId(),remoteNodeId: remoteNode.nodeId,- trustLevel: TrustLevel.ATTESTED,+ trustLevel: pinned !== undefined ? TrustLevel.ATTESTED : TrustLevel.UNTRUSTED,negotiatedCapabilities,createdAt: now,expiresAt: new Date(now.getTime() + this.config.sessionTtlMs),@@ -135,10 +153,10 @@ export class HandshakeService {metrics: FederationSession.createMetrics(),});- remoteNode.updateTrustLevel(TrustLevel.ATTESTED);+ if (pinned !== undefined) remoteNode.updateTrustLevel(TrustLevel.ATTESTED);remoteNode.markSeen();- return { success: true, session };+ return { success: true, session, pinned: pinned !== undefined };}/**diff --git a/v3/@claude-flow/plugin-agent-federation/src/plugin.ts b/v3/@claude-flow/plugin-agent-federation/src/plugin.tsindex a1ad04f837..6d98512b65 100644--- a/v3/@claude-flow/plugin-agent-federation/src/plugin.ts+++ b/v3/@claude-flow/plugin-agent-federation/src/plugin.ts@@ -7,7 +7,7 @@ import type {} from '@claude-flow/shared/src/plugin-interface.js';import * as ed from '@noble/ed25519';-import { createHash } from 'node:crypto';+import { createHash, randomBytes } from 'node:crypto';import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';import { dirname, join } from 'node:path';@@ -158,6 +158,12 @@ export class AgentFederationPlugin implements ClaudeFlowPlugin {version: FEDERATION_PLUGIN_VERSION,};+ // Operator-pinned peer keys: nodeId -> Ed25519 public key (hex). The only thing that can make a peer VERIFIED/ATTESTED.+ const trustedPeerKeys = (config['trustedPeerKeys'] ?? {}) as Record<string, unknown>;+ const pinnedKeyFor = (peerNodeId: string): string | undefined => {+ const key = Object.hasOwn(trustedPeerKeys, peerNodeId) ? trustedPeerKeys[peerNodeId] : undefined;+ return typeof key === 'string' && key.length > 0 ? key : undefined;+ };const generateId = () => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;// ADR-095 G2: real signing + verification using @noble/ed25519. The@@ -196,6 +202,7 @@ export class AgentFederationPlugin implements ClaudeFlowPlugin {const discovery = new DiscoveryService({signManifest: async (manifest) => signBytes(canonicalize(manifest as unknown as Record<string, unknown>)),+ pinnedKeyFor,verifyManifest: async (manifest) => {const peerPub = (manifest as { publicKey?: string }).publicKey;const sig = (manifest as { signature?: string }).signature;@@ -210,9 +217,10 @@ export class AgentFederationPlugin implements ClaudeFlowPlugin {);const handshake = new HandshakeService({+ pinnedKeyFor,generateSessionId: generateId,generateSessionToken: () => `token-${generateId()}`,- generateNonce: () => `nonce-${Math.random().toString(36).slice(2)}`,+ generateNonce: () => `nonce-${randomBytes(16).toString('hex')}`,signChallenge: async (nonce) => signBytes(nonce),verifySignature: async (nonce, signature, peerPublicKey) =>verifyBytes(nonce, signature, peerPublicKey),@@ -332,7 +340,7 @@ export class AgentFederationPlugin implements ClaudeFlowPlugin {const routing = new RoutingService({generateEnvelopeId: generateId,- generateNonce: () => `nonce-${Math.random().toString(36).slice(2)}`,+ generateNonce: () => `nonce-${randomBytes(16).toString('hex')}`,signEnvelope: (payload, token) => `hmac-${token.slice(0, 6)}-${payload.length}`,verifyEnvelope: () => true,scanPii: (text, trustLevel) => {@@ -431,7 +439,11 @@ export class AgentFederationPlugin implements ClaudeFlowPlugin {// need to free a port.const listenPort = config['port'] as number | undefined;if (transport && typeof listenPort === 'number' && transport.listen) {- const listenHost = (config['host'] as string | undefined) ?? '0.0.0.0';+ // Loopback unless the operator names an interface: the listener is plaintext.+ const listenHost = (config['host'] as string | undefined) ?? '127.0.0.1';+ if (listenHost !== '127.0.0.1' && listenHost !== 'localhost' && listenHost !== '::1') {+ context.logger.warn(`Federation listener on ${listenHost} is plaintext WebSocket; keep it on a private network (tailnet, WireGuard) or behind TLS`);+ }try {await transport.listen(listenPort, listenHost);context.logger.info(`Federation listening on ${listenHost}:${listenPort}`);