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

feat(federation): ADR-111 Phases 4-6 β€” firewall projection + witness chain + MCP tools (#1895)

rUv70e2339469d2
diff --git a/README.md b/README.md
index c88202852d..0fe9e56a54 100644
--- a/README.md
+++ b/README.md
@@ -263,6 +263,8 @@ The difference: some channels are trusted, some aren't. [`@claude-flow/plugin-ag
You don't configure handshakes or manage certificates. You `federation init`, `federation join`, and your agents start talking. The protocol handles identity, the PII pipeline handles data safety, and the audit trail handles compliance.
+> **πŸ“˜ Full user guide:** [`docs/federation/`](./docs/federation/) β€” setup, MCP tools, trust levels, circuit breaker, and the (opt-in) WireGuard mesh layer that ties packet-layer reachability to federation trust. ADR-111 deep-dive at [`docs/federation/phase7-mesh-bringup.md`](./docs/federation/phase7-mesh-bringup.md).
+
<details>
<summary><strong>Federation capabilities</strong></summary>
diff --git a/docs/federation/README.md b/docs/federation/README.md
new file mode 100644
index 0000000000..4d2758b162
--- /dev/null
+++ b/docs/federation/README.md
@@ -0,0 +1,276 @@
+# Ruflo Federation β€” User Guide
+
+> Cross-installation agent peering with built-in cost limits, circuit breaker, signed envelopes, and (as of alpha.14) opt-in WireGuard mesh layer governed by federation trust.
+
+This guide walks through what federation is, when to use it, and how to set it up. For the architectural backstory and per-phase release notes see the [companion gist](https://gist.github.com/ruvnet/3b5111a2ea7e450ff262ce96e88560bf).
+
+## What federation does
+
+Federation lets two or more Ruflo installations β€” your mac, a server, a teammate's laptop β€” discover each other, exchange signed manifests, and send messages between them with bounded cost and per-peer trust gates. Key properties:
+
+- **Ed25519 identity** β€” each node holds a private key; peers exchange Ed25519-signed manifests. No central directory.
+- **Five-level trust ladder** β€” `UNTRUSTED β†’ VERIFIED β†’ ATTESTED β†’ TRUSTED β†’ PRIVILEGED`. Each level unlocks a wider set of operations (`discovery`, `send`, `share-context`, `remote-spawn`, …).
+- **Per-peer budget + circuit breaker** β€” bounded tokens/USD per peer. Sustained failures auto-SUSPEND; further failures EVICT. ADR-097.
+- **PII pipeline + audit trail** β€” every cross-peer envelope passes through PII detection. Every state transition is auditable.
+- **Real wire transport** β€” WSS with permessage-deflate compression, optional cert pinning, stream multiplexing. ADR-104.
+- **Optional WG mesh layer** β€” opt-in opaque packet-layer reachability that follows federation trust changes. Compromised peer auto-isolated at L3 when the breaker fires. ADR-111.
+
+## When to use federation
+
+| Use case | Fit |
+|---|---|
+| Two laptops collaborating on a project, want bounded cost sharing + audit | βœ… |
+| Personal home server agent ↔ travel laptop | βœ… |
+| Team of 5 engineers sharing memory/skills across machines | βœ… |
+| Mobile / Windows / sub-50 peers with NAT issues | βœ… over Tailscale + federation |
+| Public-internet exposed agent endpoints | βœ… with TLS cert pinning (ADR-107) |
+| Internal HR/finance multi-agent workflow with strict access tiers | βœ… with PRIVILEGED gating + audit |
+| Replacing Slack/Discord β€” no | ❌ federation is for agent-to-agent, not human chat |
+| Untrusted-internet messaging without identity vetting | ❌ β€” trust ladder must be bootstrapped out-of-band |
+
+## Quick start
+
+### 1. Install the plugin
+
+```bash
+npx ruflo@latest # if you don't have it yet
+npx ruflo plugins install @claude-flow/plugin-agent-federation
+```
+
+Or directly via npm:
+
+```bash
+npm i @claude-flow/plugin-agent-federation@latest # currently 1.0.0-alpha.14
+```
+
+### 2. Initialize a node
+
+```bash
+npx claude-flow@v3alpha agent spawn -t federation --name fed-1
+```
+
+Or via the MCP tool `federation_init`:
+
+```json
+{
+ "tool": "federation_init",
+ "params": {
+ "nodeId": "my-mac",
+ "endpoint": "ws://my-mac.tailnet:9100",
+ "agentTypes": ["coder", "tester"]
+ }
+}
+```
+
+This generates an Ed25519 keypair (persisted to `.claude-flow/federation/keys-<nodeId>.json`, mode 0600), publishes a signed manifest, and starts the discovery service.
+
+### 3. Join a peer
+
+```json
+{
+ "tool": "federation_join",
+ "params": {
+ "endpoint": "ws://other-host.tailnet:9100"
+ }
+}
+```
+
+The handshake exchanges manifests, verifies Ed25519 signatures, and establishes the initial trust level (`UNTRUSTED` until the trust-evaluator records enough successful interactions to promote).
+
+### 4. Send a message
+
+```json
+{
+ "tool": "federation_send",
+ "params": {
+ "targetNodeId": "other-host",
+ "messageType": "agent-handoff",
+ "payload": { "task": "Investigate the failing integration test" }
+ }
+}
+```
+
+Budget and trust gates apply: if the peer is below `ATTESTED`, only `discovery`/`status`/`ping` go through. If the breaker has the peer SUSPENDED, the send short-circuits with `PEER_SUSPENDED`.
+
+## MCP tools at a glance
+
+| Tool | What it does | Trust gate |
+|---|---|---|
+| `federation_init` | Initialize this node | β€” |
+| `federation_join` | Join a peer by endpoint | β€” |
+| `federation_peers` | List discovered peers | β€” |
+| `federation_send` | Send a typed message to a peer | per-peer (varies) |
+| `federation_query` | Synchronous query β†’ response | `ATTESTED+` |
+| `federation_status` | Current node + peer trust summary | β€” |
+| `federation_trust` | View / adjust trust levels | operator |
+| `federation_audit` | Read audit log | operator |
+| `federation_breaker_status` | Per-peer state, when changed, why | β€” |
+| `federation_evict` | Operator manual evict | operator |
+| `federation_reactivate` | Operator manual reactivate | operator |
+| `federation_report_spend` | Report cost of a completed call | integrator |
+| `federation_consensus` | Federated proposal across peers | varies |
+| **`federation_wg_status`** | (ADR-111) Per-peer mesh state | β€” |
+| **`federation_wg_attest`** | (ADR-111) Operator-signed witness entry | operator |
+| **`federation_wg_keyrotate`** | (ADR-111) Rotate WG keypair | operator + `confirm:true` |
+
+## Trust levels β€” what each unlocks
+
+| Level | Capabilities (federation) | WG reachability (if ADR-111 active) |
+|---|---|---|
+| `UNTRUSTED` | `discovery` | Excluded from mesh β€” drop all |
+| `VERIFIED` | `+ status, ping` | Discovery port (9100) only |
+| `ATTESTED` | `+ send, receive, query-redacted` | + federation messaging (9101-9199) |
+| `TRUSTED` | `+ share-context, collaborative-task` | + ssh (22), services (80/443) |
+| `PRIVILEGED` | `+ full-memory, remote-spawn` | Full mesh |
+
+Trust is earned via repeated successful interactions (the `TrustEvaluator` tracks score + interaction count). Promotion thresholds are documented in `domain/entities/trust-level.ts`.
+
+## Circuit breaker
+
+If a peer's failure ratio or cost spend exceeds the policy:
+
+```
+ACTIVE β†’ SUSPENDED β†’ EVICTED
+ ↑ β”‚
+ └─────────operator-onlyβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+```
+
+- **SUSPEND**: peer's outbound sends short-circuit (`PEER_SUSPENDED`). Existing sessions continue; new sends rejected. Auto-eviction on continued failures.
+- **EVICT**: peer's outbound sends short-circuit (`PEER_EVICTED`). Session terminated. Operator must explicitly reactivate.
+- The breaker **does not auto-reactivate**. The integrator's health probe is responsible for confirming the peer is healthy and calling `federation_reactivate`.
+
+Policy is tunable; defaults are conservative (50+ samples needed before suspend, high failure ratio threshold).
+
+## ADR-111 β€” WireGuard mesh (opt-in, since alpha.14)
+
+Federation today treats network connectivity as the integrator's problem (Tailscale, LAN, wss://+pinning). That works but trust changes don't propagate to the L3 layer β€” a peer EVICTED in federation stays in the tailnet until an admin manually removes it.
+
+ADR-111 closes that gap with an optional in-tree WG mesh:
+
+- WG keypair generated alongside the federation key
+- Mesh IP derived deterministically from `nodeId` (sha256 β†’ `10.50.0.0/16` host portion, with collision-handling probe loop)
+- WG identity published inside the same Ed25519-signed manifest
+- Federation breaker SUSPEND β†’ `wg set ... allowed-ips ""` (soft-block at L3)
+- Federation breaker EVICT β†’ `wg set ... remove` (terminal)
+- Operator reactivate β†’ AllowedIPs restored
+- Each mutation entered into an append-only Ed25519-signed witness chain
+
+**Phases shipped in alpha.14:**
+- Phase 1 β€” Manifest extension + key generation
+- Phase 2 β€” `WgMeshService` (no shell β€” emits configs + commands)
+- Phase 3 β€” Coordinator/breaker wiring
+- Phase 4 β€” Firewall projection (`nftables` / `pf`) β€” PR #1895
+- Phase 5 β€” Witness attestation chain β€” PR #1895
+- Phase 6 β€” Operator MCP tools β€” PR #1895
+
+**Phase 7 β€” operator-mediated**:
+See [`docs/federation/phase7-mesh-bringup.md`](./phase7-mesh-bringup.md) for the cross-OS bringup procedure (mac ↔ ruvultra over Tailscale).
+
+### Enabling ADR-111
+
+Set `config.wgMesh: true` in your federation plugin config, then run the staging helper:
+
+```bash
+node v3/@claude-flow/plugin-agent-federation/scripts/phase7-stage.mjs \
+ <localNodeId> <peerNodeId> <peerPubkey> <peerMeshIP> <peerEndpoint>
+```
+
+The script generates `/tmp/adr-111-stage/`:
+- `wg-key-<nodeId>.json` (mode 0600 β€” your private WG key)
+- `ruflo-fed.conf` (the wg-quick interface config)
+- `ruflo-fed.nft` or `ruflo-fed.pf` (firewall projection)
+
+After review, the operator manually activates:
+
+```bash
+sudo install -m 0600 /tmp/adr-111-stage/ruflo-fed.conf /etc/wireguard/ruflo-fed.conf
+# Linux:
+sudo nft -f /tmp/adr-111-stage/ruflo-fed.nft
+# macOS:
+sudo pfctl -a ruflo-fed -f /tmp/adr-111-stage/ruflo-fed.pf
+sudo wg-quick up ruflo-fed
+```
+
+## Using `claude -p` headless mode
+
+`claude -p` (print/pipe mode) can drive federation MCP tools non-interactively. Each invocation processes its prompt and exits β€” for a persistent federation listener, run a long-lived MCP server instead.
+
+**On the originating host** (mac mini):
+
+```bash
+claude -p --model haiku --max-budget-usd 0.20 --output-format text \
+ "Federation MCP tools to verify cross-machine peering health: name 3. One line."
+# β†’ Three Federation MCP tools for peering health verification:
+# federation-init (keypair generation), federation-status (peers/trust/metrics),
+# federation-audit (compliance filtering).
+```
+
+**On the peer host (ruvultra)** β€” requires interactive `/login` first since `claude -p` reads stored credentials:
+
+```bash
+# First time only β€” operator-mediated:
+claude # then /login
+
+# After that:
+claude -p --model haiku --max-budget-usd 0.20 \
+ "Run federation_status MCP and report peer count."
+```
+
+**Workflow for cross-machine task handoff:**
+
+```bash
+# Host A β€” kick off a federated task:
+claude -p --model sonnet --output-format json --resume <session> \
+ "Use federation_send to dispatch this task to ruvultra: analyze the failing test"
+
+# Host B (ruvultra) β€” receive + work:
+claude -p --resume <session> "Continue handling the federated task"
+```
+
+The federation plugin handles signing, PII gating, breaker, and audit on every send. The two `claude -p` invocations don't share state directly β€” they communicate exclusively through the federation envelope channel.
+
+## Anti-goals β€” when **NOT** to use federation
+
+- **Replacement for Slack/Discord.** Federation moves agent envelopes, not human chat.
+- **Public internet without identity vetting.** Trust ladder bootstrapping is your responsibility.
+- **NAT traversal magic.** Use Tailscale (or Headscale) for that; federation rides on top.
+- **A general-purpose RPC framework.** It's specifically for AI agents with cost-aware budgeting.
+
+## Where things live
+
+| What | Path |
+|---|---|
+| Plugin source | `v3/@claude-flow/plugin-agent-federation/src/` |
+| Tests | `v3/@claude-flow/plugin-agent-federation/__tests__/` |
+| ADRs | `v3/docs/adr/ADR-{097,104,105,106,107,109,110,111}-*.md` |
+| Phase 7 staging script | `v3/@claude-flow/plugin-agent-federation/scripts/phase7-stage.mjs` |
+| Witness signing | `plugins/ruflo-core/scripts/witness/` |
+
+## Releases
+
+| Version | What landed |
+|---|---|
+| `1.0.0-alpha.9` | First user-visible release β€” see [announcement gist](https://gist.github.com/ruvnet/3b5111a2ea7e450ff262ce96e88560bf) |
+| `1.0.0-alpha.10` | ADR-097 Phases 2.a-4 + ADR-104 transport + ADR-109 inbound dispatcher |
+| `1.0.0-alpha.11-12` | ADR-109 sig verify, ADR-104 compression, ADR-107 TLS cert pinning |
+| `1.0.0-alpha.13` | ADR-104 stream multiplexing + ADR-110 MemorySpendReporter |
+| **`1.0.0-alpha.14`** | **ADR-111 Phases 1-3 (WG mesh foundation)** |
+| `1.0.0-alpha.15` (in flight) | ADR-111 Phases 4-6 (firewall + witness + MCP tools) β€” PR #1895 |
+
+## Related ADRs
+
+- [ADR-097](../../v3/docs/adr/ADR-097-federation-budget-circuit-breaker.md) β€” budget + circuit breaker
+- [ADR-104](../../v3/docs/adr/ADR-104-federation-wire-transport.md) β€” WSS transport + multiplexing
+- [ADR-105](../../v3/docs/adr/ADR-105-federation-v1-state-snapshot.md) β€” state snapshot/replay
+- [ADR-106](../../v3/docs/adr/ADR-106-peer-discovery.md) β€” discovery mechanisms
+- [ADR-107](../../v3/docs/adr/ADR-107-federation-tls.md) β€” TLS + cert pinning
+- [ADR-109](../../v3/docs/adr/ADR-109-federation-inbound-dispatcher.md) β€” inbound dispatch + sig verify
+- [ADR-110](../../v3/docs/adr/ADR-110-federation-memory-spend-reporter.md) β€” production SpendReporter
+- [**ADR-111**](../../v3/docs/adr/ADR-111-federation-wg-mesh.md) β€” **WG mesh layer**
+
+## Support
+
+- Issues: https://github.com/ruvnet/ruflo/issues
+- Tracking issue (ADR-111): [#1879](https://github.com/ruvnet/ruflo/issues/1879)
+- Federation gist (current through alpha.14): https://gist.github.com/ruvnet/3b5111a2ea7e450ff262ce96e88560bf
+- ADR-111 deep-dive gist: https://gist.github.com/ruvnet/c640fc71c7a6ced37908e645d5db84c5
diff --git a/docs/federation/phase7-mesh-bringup.md b/docs/federation/phase7-mesh-bringup.md
new file mode 100644
index 0000000000..8e4f6a994b
--- /dev/null
+++ b/docs/federation/phase7-mesh-bringup.md
@@ -0,0 +1,205 @@
+# ADR-111 Phase 7 β€” Cross-OS WG mesh bringup
+
+Step-by-step procedure for activating the opt-in WireGuard mesh between two federation peers. This is the **operator-mediated** step that follows Phases 1-6 (which ship as code in `@claude-flow/plugin-agent-federation`).
+
+> **⚠️ Phase 7 is destructive.** It modifies host networking and requires root. A typo in the firewall projection can drop ssh. Operator review of the staged configs is **mandatory** before activation.
+
+## Prerequisites
+
+- WireGuard installed on both hosts (`brew install wireguard-tools` on mac, `apt install wireguard` on linux).
+- Both hosts reachable on a common UDP port (default `51820`). Tailscale, a LAN, or a VPN concentrator works. ADR-111 does NOT do NAT traversal.
+- Federation plugin built on both hosts (`pnpm install && pnpm run build` in `v3/@claude-flow/plugin-agent-federation`).
+- Federation Ed25519 identity already initialized β€” Phase 7 reuses it for manifest signing.
+
+## Step 1 β€” Stage configs on each host
+
+On **host A** (mac mini in this example):
+
+```bash
+cd v3/@claude-flow/plugin-agent-federation
+node scripts/phase7-stage.mjs \
+ ruv-mac-mini \
+ ruvultra \
+ '<placeholder-pubkey>' \
+ '10.50.0.0/32' \
+ 'ruvultra-tailnet-name:51820'
+```
+
+The script will print host A's freshly-generated pubkey, e.g.:
+
+```
+publicKey: 61005ZbEMJq0tTIYwSHINdmJEsBM39sM5TIV6p4UfHA=
+meshIP: 10.50.119.95/32
+```
+
+On **host B** (ruvultra):
+
+```bash
+node scripts/phase7-stage.mjs \
+ ruvultra \
+ ruv-mac-mini \
+ '<placeholder-pubkey>' \
+ '10.50.0.0/32' \
+ 'mac-mini-tailnet-name:51820'
+```
+
+Note host B's pubkey, e.g.:
+
+```
+publicKey: v+cwXZ3BoYZZAodDI38RYf9UO5c9xz+TkjaAZg8mzhs=
+meshIP: 10.50.242.138/32
+```
+
+## Step 2 β€” Re-stage with REAL peer values
+
+Now that both hosts have generated keys, re-run staging with the actual peer pubkey + meshIP. The script reuses each host's own key from `/tmp/adr-111-stage/wg-key-<nodeId>.json` (idempotent).
+
+On host A:
+
+```bash
+node scripts/phase7-stage.mjs \
+ ruv-mac-mini \
+ ruvultra \
+ 'v+cwXZ3BoYZZAodDI38RYf9UO5c9xz+TkjaAZg8mzhs=' \
+ '10.50.242.138/32' \
+ 'ruvultra-tailnet:51820'
+```
+
+On host B:
+
+```bash
+node scripts/phase7-stage.mjs \
+ ruvultra \
+ ruv-mac-mini \
+ '61005ZbEMJq0tTIYwSHINdmJEsBM39sM5TIV6p4UfHA=' \
+ '10.50.119.95/32' \
+ 'mac-mini-tailnet:51820'
+```
+
+Each host now has cross-coherent staged configs in `/tmp/adr-111-stage/`.
+
+## Step 3 β€” Operator review checklist
+
+Before activating, inspect each staged file:
+
+```bash
+cat /tmp/adr-111-stage/ruflo-fed.conf
+cat /tmp/adr-111-stage/ruflo-fed.nft # linux only
+cat /tmp/adr-111-stage/ruflo-fed.pf # macos only
+```
+
+Checklist:
+- [ ] `ruflo-fed.conf` has exactly one `[Peer]` block (per peer expected)
+- [ ] The `[Peer]` block's `PublicKey` matches the OTHER host's emitted pubkey
+- [ ] `AllowedIPs` lists ONLY the peer's mesh IP β€” no broader CIDR
+- [ ] `ListenPort` is what you expect (default `51820`)
+- [ ] Firewall projection contains only ATTESTED+ peers
+- [ ] Default policy is `drop` (nftables) / not affecting main pf ruleset (pf anchor-scoped)
+- [ ] No mention of UNTRUSTED peers anywhere
+
+If anything looks off, **stop and re-stage** with corrected inputs β€” `ruflo-fed.conf` is what `wg-quick up` parses, and a misconfigured rule can drop ssh.
+
+## Step 4 β€” Activate (per host)
+
+After the checklist passes:
+
+```bash
+# Install the wg-quick config
+sudo install -m 0600 /tmp/adr-111-stage/ruflo-fed.conf /etc/wireguard/ruflo-fed.conf
+
+# Load the firewall rules (atomic, scoped to the WG interface or pf anchor)
+# Linux:
+sudo nft -f /tmp/adr-111-stage/ruflo-fed.nft
+# macOS:
+sudo pfctl -a ruflo-fed -f /tmp/adr-111-stage/ruflo-fed.pf
+
+# Bring up the WG interface
+sudo wg-quick up ruflo-fed
+```
+
+## Step 5 β€” Verify reachability
+
+On host A:
+
+```bash
+sudo wg show ruflo-fed
+# Expected: [Peer] section shows ruvultra's pubkey, last handshake timestamp,
+# transfer counters update after activity.
+
+ping 10.50.242.138 # ruvultra's mesh IP β€” should respond
+```
+
+On host B (mirror):
+
+```bash
+sudo wg show ruflo-fed
+ping 10.50.119.95
+```
+
+## Step 6 β€” Validate breaker β†’ L3 propagation
+
+Trigger an operator-initiated evict on host A and confirm L3 isolation propagates:
+
+```bash
+# On host A, evict ruvultra at the federation layer
+ruflo federation evict --node-id ruvultra
+# Or via MCP: federation_evict
+
+# Confirm WG layer responded
+sudo wg show ruflo-fed # ruvultra peer's [Peer] line should be gone
+
+# From host A:
+ping 10.50.242.138 # NOW unreachable β€” L3 followed L7 trust eviction
+```
+
+To restore:
+
+```bash
+ruflo federation reactivate --node-id ruvultra
+# A wg set ruflo-fed peer ... allowed-ips ... command is emitted via the
+# wgCommandSink the operator wired during plugin init.
+sudo wg show ruflo-fed # ruvultra back in [Peer] list
+ping 10.50.242.138 # responsive again
+```
+
+## Step 7 β€” Witness verification (optional)
+
+If `WgWitnessService` is wired into your federation plugin lifecycle (Phase 5 integration β€” operator-supplied):
+
+```bash
+cat .claude-flow/federation/wg-changes.log # append-only chain
+node plugins/ruflo-core/scripts/witness/verify.mjs \
+ --manifest .claude-flow/federation/wg-witness.md.json
+# Expected: Ed25519 signature valid, chain link verified end-to-end
+```
+
+## Rollback
+
+```bash
+sudo wg-quick down ruflo-fed
+
+# Linux:
+sudo nft delete table inet ruflo_fed
+
+# macOS:
+sudo pfctl -a ruflo-fed -F all
+```
+
+The configs in `/tmp/adr-111-stage/` and `/etc/wireguard/ruflo-fed.conf` stay on disk β€” re-run `wg-quick up ruflo-fed` to reactivate. To fully tear down also delete `/etc/wireguard/ruflo-fed.conf` (private key inside).
+
+## Known limitations (v1)
+
+- **No NAT traversal** β€” peers must be direct-UDP reachable. Use Tailscale, a VPN concentrator, or a public IP.
+- **No DERP-equivalent relay** β€” if direct UDP fails, fall back to Tailscale instead.
+- **No MagicDNS** β€” mesh IPs are derived from `nodeId`, not resolved.
+- **Trust-graded firewall rules use ports** β€” but WG itself routes at L3. The firewall projection ships now and enforces these tighter rules once loaded.
+- **Mobile / Windows clients** β€” out of scope for v1. Windows requires WireGuard for Windows + a different config-gen path.
+
+## When NOT to use ADR-111
+
+| If you... | Use this instead |
+|---|---|
+| Need NAT traversal | Tailscale or Headscale |
+| Have >50 peers | Tailscale (their infra handles your scale) |
+| Don't need trust↔L3 coupling | Plain tailnet + federation breaker is simpler |
+| Don't need cryptographic provenance of mesh changes | Tailscale's audit log suffices |
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.ts
index 02156e87e8..876ce09cab 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
@@ -178,10 +178,10 @@ describe('AgentFederationPlugin', () => {
});
describe('registerMCPTools', () => {
- it('should return 13 MCP tool definitions', () => {
- // 9 original + 3 ADR-097 Phase 4 + 1 ADR-097 Phase 3 upstream
+ it('should return 16 MCP tool definitions', () => {
+ // 9 original + 3 ADR-097 Phase 4 + 1 ADR-097 Phase 3 upstream + 3 ADR-111 Phase 6
const tools = plugin.registerMCPTools();
- expect(tools).toHaveLength(13);
+ expect(tools).toHaveLength(16);
});
it.each([
@@ -200,6 +200,10 @@ describe('AgentFederationPlugin', () => {
'federation_reactivate',
// ADR-097 Phase 3 upstream
'federation_report_spend',
+ // ADR-111 Phase 6
+ 'federation_wg_status',
+ 'federation_wg_attest',
+ 'federation_wg_keyrotate',
] as const)('should include tool "%s"', (expectedName) => {
const tools = plugin.registerMCPTools();
const names = tools.map((t) => t.name);
diff --git a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/wg-firewall-service.test.ts b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/wg-firewall-service.test.ts
new file mode 100644
index 0000000000..536a726c62
--- /dev/null
+++ b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/wg-firewall-service.test.ts
@@ -0,0 +1,151 @@
+/**
+ * ADR-111 Phase 4 β€” unit tests for WgFirewallService.
+ */
+import { describe, it, expect } from 'vitest';
+import { WgFirewallService } from '../../src/domain/services/wg-firewall-service.js';
+import { FederationNode } from '../../src/domain/entities/federation-node.js';
+import { TrustLevel } from '../../src/domain/entities/trust-level.js';
+
+function peer(nodeId: string, trustLevel: TrustLevel, meshIP?: string): FederationNode {
+ return FederationNode.create({
+ nodeId,
+ publicKey: 'pk-' + nodeId,
+ endpoint: `ws://${nodeId}:9100`,
+ trustLevel,
+ capabilities: {
+ agentTypes: [],
+ maxConcurrentSessions: 1,
+ supportedProtocols: ['websocket'],
+ complianceModes: [],
+ },
+ metadata: meshIP ? { wgMeshIP: meshIP } : {},
+ });
+}
+
+describe('ADR-111 Phase 4 β€” WgFirewallService nftables projection', () => {
+ it('emits a #!/usr/sbin/nft -f shebang and drop-default policy', () => {
+ const svc = new WgFirewallService({ platform: 'linux-nftables' });
+ const { content } = svc.projectRules([]);
+ expect(content).toContain('#!/usr/sbin/nft -f');
+ expect(content).toContain('policy drop');
+ expect(content).toContain('table inet ruflo_fed');
+ });
+
+ it('scopes input chain to the WG interface', () => {
+ const svc = new WgFirewallService({ platform: 'linux-nftables', interfaceName: 'wgtest' });
+ const { content } = svc.projectRules([]);
+ expect(content).toContain('iifname "wgtest"');
+ });
+
+ it('projects ATTESTED trust β†’ discovery port + federation range', () => {
+ const svc = new WgFirewallService({ platform: 'linux-nftables' });
+ const { content, peerProjections } = svc.projectRules([
+ peer('attested-peer', TrustLevel.ATTESTED, '10.50.1.2/32'),
+ ]);
+ expect(content).toContain('# peer attested-peer');
+ expect(content).toContain('ip saddr 10.50.1.2 tcp dport 9100 accept');
+ expect(content).toContain('ip saddr 10.50.1.2 tcp dport 9101-9199 accept');
+ expect(peerProjections).toHaveLength(1);
+ expect(peerProjections[0].rules.length).toBe(2);
+ });
+
+ it('projects PRIVILEGED β†’ wildcard accept', () => {
+ const svc = new WgFirewallService({ platform: 'linux-nftables' });
+ const { content } = svc.projectRules([
+ peer('full-trust', TrustLevel.PRIVILEGED, '10.50.7.7/32'),
+ ]);
+ expect(content).toMatch(/ip saddr 10\.50\.7\.7 accept/);
+ });
+
+ it('excludes UNTRUSTED peers from rule output', () => {
+ const svc = new WgFirewallService({ platform: 'linux-nftables' });
+ const { content, peerProjections } = svc.projectRules([
+ peer('drop-bucket', TrustLevel.UNTRUSTED, '10.50.9.9/32'),
+ ]);
+ expect(content).not.toContain('drop-bucket');
+ expect(peerProjections).toHaveLength(0);
+ });
+
+ it('skips peers without wgMeshIP metadata', () => {
+ const svc = new WgFirewallService({ platform: 'linux-nftables' });
+ const { peerProjections } = svc.projectRules([
+ peer('no-wg', TrustLevel.ATTESTED),
+ ]);
+ expect(peerProjections).toHaveLength(0);
+ });
+
+ it('emits loadCmd = nft -f <rulePath>', () => {
+ const svc = new WgFirewallService({ platform: 'linux-nftables', rulePath: '/tmp/ruflo.nft' });
+ const { loadCmd } = svc.projectRules([]);
+ expect(loadCmd).toBe('nft -f /tmp/ruflo.nft');
+ });
+});
+
+describe('ADR-111 Phase 4 β€” WgFirewallService pf projection', () => {
+ it('emits header marking the anchor scope', () => {
+ const svc = new WgFirewallService({ platform: 'darwin-pf', pfAnchor: 'test-anchor' });
+ const { content, loadCmd } = svc.projectRules([]);
+ expect(content).toContain('# This anchor is scoped to test-anchor');
+ expect(loadCmd).toMatch(/^pfctl -a test-anchor -f .*$/);
+ });
+
+ it('projects ATTESTED trust β†’ discovery + federation pass rules', () => {
+ const svc = new WgFirewallService({ platform: 'darwin-pf', interfaceName: 'utun9' });
+ const { content } = svc.projectRules([
+ peer('attested-peer', TrustLevel.ATTESTED, '10.50.1.2/32'),
+ ]);
+ expect(content).toContain('# peer attested-peer');
+ expect(content).toContain('pass in on utun9 proto tcp from 10.50.1.2 to any port 9100 keep state');
+ expect(content).toContain('pass in on utun9 proto tcp from 10.50.1.2 to any port 9101:9199 keep state');
+ });
+
+ it('projects TRUSTED β†’ adds ssh + 80/443 services', () => {
+ const svc = new WgFirewallService({ platform: 'darwin-pf' });
+ const { content } = svc.projectRules([
+ peer('trusted-peer', TrustLevel.TRUSTED, '10.50.5.5/32'),
+ ]);
+ expect(content).toContain('to any port 22');
+ expect(content).toContain('to any port 80:443');
+ });
+
+ it('projects PRIVILEGED β†’ catch-all pass rule', () => {
+ const svc = new WgFirewallService({ platform: 'darwin-pf' });
+ const { content } = svc.projectRules([
+ peer('full-trust', TrustLevel.PRIVILEGED, '10.50.7.7/32'),
+ ]);
+ expect(content).toMatch(/pass in on ruflo-fed from 10\.50\.7\.7 to any keep state/);
+ });
+});
+
+describe('ADR-111 Phase 4 β€” WgFirewallService defense-in-depth', () => {
+ it('refuses construction with unsafe interface name', () => {
+ expect(() => new WgFirewallService({ interfaceName: 'wg0; rm -rf /' })).toThrow(/unsafe/);
+ });
+
+ it('refuses construction with unsafe pf anchor', () => {
+ expect(() => new WgFirewallService({ platform: 'darwin-pf', pfAnchor: 'ev`il`' })).toThrow(/unsafe/);
+ });
+
+ it('refuses peer with unsafe meshIP', () => {
+ const svc = new WgFirewallService({ platform: 'linux-nftables' });
+ expect(() => svc.projectRules([
+ peer('evil', TrustLevel.ATTESTED, '10.50.1.2; rm -rf /'),
+ ])).toThrow(/unsafe/);
+ });
+
+ it('platform auto-detects on construction', () => {
+ const svc = new WgFirewallService();
+ const platform = svc.getPlatform();
+ expect(['linux-nftables', 'darwin-pf']).toContain(platform);
+ });
+
+ it('produces empty rule body when no eligible peers', () => {
+ const svc = new WgFirewallService({ platform: 'linux-nftables' });
+ const { content, peerProjections } = svc.projectRules([
+ peer('untrusted', TrustLevel.UNTRUSTED, '10.50.9.9/32'),
+ peer('no-wg', TrustLevel.ATTESTED),
+ ]);
+ expect(peerProjections).toHaveLength(0);
+ expect(content).toContain('# No ATTESTED+ peers in mesh.');
+ });
+});
diff --git a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/wg-mesh-service.test.ts b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/wg-mesh-service.test.ts
index 31c26600ad..0342ee23aa 100644
--- a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/wg-mesh-service.test.ts
+++ b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/wg-mesh-service.test.ts
@@ -168,6 +168,82 @@ describe('ADR-111 Phase 2 β€” WgMeshService breaker hooks', () => {
});
});
+describe('ADR-111 Phase 2 β€” readSafePeerWgFields (compromised-peer defense)', () => {
+ function evilPeer(overrides: { wgPublicKey?: string; wgMeshIP?: string; wgEndpoint?: string }) {
+ return FederationNode.create({
+ nodeId: 'evil',
+ publicKey: 'ed25519-evil',
+ endpoint: 'ws://evil:9100',
+ trustLevel: TrustLevel.ATTESTED,
+ capabilities: {
+ agentTypes: [],
+ maxConcurrentSessions: 1,
+ supportedProtocols: ['websocket'],
+ complianceModes: [],
+ },
+ metadata: {
+ wgPublicKey: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=',
+ wgMeshIP: '10.50.1.2/32',
+ wgEndpoint: 'evil.example:51820',
+ ...overrides,
+ },
+ });
+ }
+
+ let svc: WgMeshService;
+ beforeEach(() => {
+ svc = new WgMeshService();
+ svc.setLocalIdentity(generateWgKeyPair(), '10.50.0.1/32');
+ });
+
+ it('rejects [Peer] injection via wgEndpoint newline', () => {
+ const evil = evilPeer({ wgEndpoint: 'host:51820\n[Peer]\nPublicKey = attacker' });
+ const cfg = svc.buildInterfaceConfig([evil]);
+ // The malicious endpoint must not appear, nor must the injected [Peer] block
+ expect(cfg).not.toContain('attacker');
+ expect(cfg).not.toContain('host:51820\n[Peer]');
+ // Peer should be skipped entirely β€” no nodeId comment for it either
+ expect(cfg).not.toContain('Peer evil');
+ });
+
+ it('rejects unsafe wgPublicKey (wrong length / non-base64)', () => {
+ const cfg1 = svc.buildInterfaceConfig([evilPeer({ wgPublicKey: 'short' })]);
+ const cfg2 = svc.buildInterfaceConfig([evilPeer({ wgPublicKey: '\\n; rm -rf /;\\n' })]);
+ expect(cfg1).not.toContain('Peer evil');
+ expect(cfg2).not.toContain('Peer evil');
+ });
+
+ it('rejects unsafe wgMeshIP (out-of-range octet)', () => {
+ const cfg = svc.buildInterfaceConfig([evilPeer({ wgMeshIP: '999.999.999.999/32' })]);
+ expect(cfg).not.toContain('Peer evil');
+ });
+
+ it('rejects unsafe wgMeshIP (missing /32 cidr)', () => {
+ const cfg = svc.buildInterfaceConfig([evilPeer({ wgMeshIP: '10.50.1.2' })]);
+ expect(cfg).not.toContain('Peer evil');
+ });
+
+ it('rejects port out of range in wgEndpoint', () => {
+ const cfg = svc.buildInterfaceConfig([evilPeer({ wgEndpoint: 'host:99999' })]);
+ expect(cfg).not.toContain('Peer evil');
+ });
+
+ it('accepts IPv6-bracketed endpoint', () => {
+ const cfg = svc.buildInterfaceConfig([evilPeer({ wgEndpoint: '[::1]:51820' })]);
+ expect(cfg).toContain('Peer evil');
+ expect(cfg).toContain('[::1]:51820');
+ });
+
+ it('summarize() also excludes unsafe peers (empty pubkey/IP/endpoint)', () => {
+ const evil = evilPeer({ wgEndpoint: 'host:51820\nmalicious' });
+ const summary = svc.summarize([evil]);
+ expect(summary).toHaveLength(1);
+ expect(summary[0].endpoint).toBe('');
+ expect(summary[0].publicKey).toBe('');
+ expect(summary[0].meshIP).toBe('');
+ });
+});
+
describe('ADR-111 Phase 2 β€” WgMeshService defense-in-depth', () => {
it('refuses cmd args with shell metacharacters', () => {
const svc = new WgMeshService();
diff --git a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/wg-witness-service.test.ts b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/wg-witness-service.test.ts
new file mode 100644
index 0000000000..a3ec271900
--- /dev/null
+++ b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/wg-witness-service.test.ts
@@ -0,0 +1,178 @@
+/**
+ * ADR-111 Phase 5 β€” unit tests for WgWitnessService.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ WgWitnessService,
+ canonicalizeContent,
+ hashContent,
+ verifyWitnessEntry,
+ verifyWitnessChain,
+ type WgWitnessSigner,
+ type WgWitnessContent,
+} from '../../src/domain/services/wg-witness-service.js';
+import type { WgCommand } from '../../src/domain/services/wg-mesh-service.js';
+
+function makeSigner(seed = 'sig'): { signer: WgWitnessSigner; signed: Buffer[] } {
+ const signed: Buffer[] = [];
+ return {
+ signer: {
+ sign: async (bytes) => {
+ signed.push(bytes);
+ // Stable fake sig β€” same bytes always produce same sig so chain
+ // hash + sig are reproducible across test runs.
+ return `${seed}:${Buffer.from(bytes).toString('base64').slice(0, 16)}`;
+ },
+ },
+ signed,
+ };
+}
+
+describe('ADR-111 Phase 5 β€” canonicalizeContent', () => {
+ it('sorts keys for stable encoding', () => {
+ const a: WgWitnessContent = {
+ version: '1',
+ type: 'peer-added',
+ timestamp: '2026-05-11T00:00:00Z',
+ nodeId: 'a',
+ rationale: 'test',
+ prevHash: '',
+ };
+ const b: WgWitnessContent = {
+ prevHash: '',
+ rationale: 'test',
+ nodeId: 'a',
+ timestamp: '2026-05-11T00:00:00Z',
+ type: 'peer-added',
+ version: '1',
+ };
+ expect(canonicalizeContent(a).toString()).toBe(canonicalizeContent(b).toString());
+ });
+
+ it('omits undefined fields', () => {
+ const c: WgWitnessContent = {
+ version: '1',
+ type: 'peer-added',
+ timestamp: '2026-05-11T00:00:00Z',
+ nodeId: 'a',
+ rationale: 'test',
+ prevHash: '',
+ };
+ const out = canonicalizeContent(c).toString();
+ expect(out).not.toContain('undefined');
+ expect(out).not.toContain('meshIP');
+ });
+
+ it('produces deterministic hash for identical content', () => {
+ const c: WgWitnessContent = {
+ version: '1',
+ type: 'peer-added',
+ timestamp: '2026-05-11T00:00:00Z',
+ nodeId: 'a',
+ rationale: 'test',
+ prevHash: '',
+ };
+ expect(hashContent(c)).toBe(hashContent(c));
+ expect(hashContent(c)).toMatch(/^[a-f0-9]{64}$/);
+ });
+});
+
+describe('ADR-111 Phase 5 β€” WgWitnessService.build', () => {
+ it('produces an entry with hash + signature + correct prevHash', async () => {
+ const { signer } = makeSigner();
+ const w = new WgWitnessService('local', signer);
+ const e1 = await w.build('peer-added', {
+ rationale: 'first',
+ });
+ expect(e1.content.prevHash).toBe('');
+ expect(e1.hash).toMatch(/^[a-f0-9]{64}$/);
+ expect(e1.signature).toMatch(/^sig:/);
+ expect(e1.content.nodeId).toBe('local');
+ expect(e1.content.version).toBe('1');
+
+ const e2 = await w.build('peer-removed-suspended', { rationale: 'second' });
+ expect(e2.content.prevHash).toBe(e1.hash);
+ });
+
+ it('setLastHash lets a resumer continue an existing chain', async () => {
+ const { signer } = makeSigner();
+ const w = new WgWitnessService('local', signer);
+ w.setLastHash('deadbeef');
+ const e = await w.build('peer-added', { rationale: 'resume' });
+ expect(e.content.prevHash).toBe('deadbeef');
+ });
+});
+
+describe('ADR-111 Phase 5 β€” WgWitnessService.attestWgCommand', () => {
+ it('maps verbs to event types', async () => {
+ const { signer } = makeSigner();
+ const w = new WgWitnessService('local', signer);
+ const cmds: WgCommand[] = [
+ { verb: 'remove-allowed-ips', peerPublicKey: 'pk1', cmd: 'wg set ruflo-fed peer pk1 allowed-ips ""', rationale: 'r' },
+ { verb: 'set-allowed-ips', peerPublicKey: 'pk1', cmd: 'wg set ruflo-fed peer pk1 allowed-ips 10.50.1.2/32', rationale: 'r' },
+ { verb: 'remove-peer', peerPublicKey: 'pk1', cmd: 'wg set ruflo-fed peer pk1 remove', rationale: 'r' },
+ ];
+ const expected = ['peer-removed-suspended', 'peer-restored', 'peer-evicted'];
+ for (let i = 0; i < cmds.length; i++) {
+ const e = await w.attestWgCommand(cmds[i]);
+ expect(e.content.type).toBe(expected[i]);
+ expect(e.content.wgCommand).toBe(cmds[i].cmd);
+ }
+ });
+});
+
+describe('ADR-111 Phase 5 β€” chain verification', () => {
+ const fakeVerify = async (bytes: Buffer, sig: string) =>
+ sig === `sig:${Buffer.from(bytes).toString('base64').slice(0, 16)}`;
+
+ it('verifyWitnessEntry returns true for well-formed entry', async () => {
+ const { signer } = makeSigner();
+ const w = new WgWitnessService('local', signer);
+ const e = await w.build('peer-added', { rationale: 'ok' });
+ expect(await verifyWitnessEntry(e, fakeVerify)).toBe(true);
+ });
+
+ it('verifyWitnessEntry returns false if hash is mutated', async () => {
+ const { signer } = makeSigner();
+ const w = new WgWitnessService('local', signer);
+ const e = await w.build('peer-added', { rationale: 'ok' });
+ const tampered = { ...e, hash: 'a'.repeat(64) };
+ expect(await verifyWitnessEntry(tampered, fakeVerify)).toBe(false);
+ });
+
+ it('verifyWitnessChain green for an intact chain', async () => {
+ const { signer } = makeSigner();
+ const w = new WgWitnessService('local', signer);
+ const chain = [
+ await w.build('peer-added', { rationale: 'a' }),
+ await w.build('peer-removed-suspended', { rationale: 'b' }),
+ await w.build('peer-restored', { rationale: 'c' }),
+ ];
+ const result = await verifyWitnessChain(chain, fakeVerify);
+ expect(result.ok).toBe(true);
+ });
+
+ it('detects broken chain link (entry inserted out of order)', async () => {
+ const { signer } = makeSigner();
+ const w = new WgWitnessService('local', signer);
+ const chain = [
+ await w.build('peer-added', { rationale: 'a' }),
+ await w.build('peer-removed-suspended', { rationale: 'b' }),
+ ];
+ // Swap the order β€” second now claims prevHash=first.hash but appears first
+ const broken = [chain[1], chain[0]];
+ const result = await verifyWitnessChain(broken, fakeVerify);
+ expect(result.ok).toBe(false);
+ expect(result.reason).toBe('broken-chain-link');
+ });
+
+ it('detects invalid signature within a chain', async () => {
+ const { signer } = makeSigner();
+ const w = new WgWitnessService('local', signer);
+ const chain = [await w.build('peer-added', { rationale: 'a' })];
+ const tampered = [{ ...chain[0], signature: 'bogus-sig' }];
+ const result = await verifyWitnessChain(tampered, fakeVerify);
+ expect(result.ok).toBe(false);
+ expect(result.reason).toBe('invalid-signature-or-hash');
+ });
+});
diff --git a/v3/@claude-flow/plugin-agent-federation/scripts/phase7-stage.mjs b/v3/@claude-flow/plugin-agent-federation/scripts/phase7-stage.mjs
new file mode 100755
index 0000000000..e99c4c8632
--- /dev/null
+++ b/v3/@claude-flow/plugin-agent-federation/scripts/phase7-stage.mjs
@@ -0,0 +1,144 @@
+#!/usr/bin/env node
+/**
+ * ADR-111 Phase 7 staging helper. Generates WG configs + firewall rules on
+ * the current host, naming a single peer. Outputs go to a staging dir;
+ * NOTHING is loaded into the kernel β€” `wg-quick up`, `nft -f`, `pfctl -f`
+ * are operator-mediated.
+ *
+ * Usage:
+ * node scripts/phase7-stage.mjs <localNodeId> <peerNodeId> <peerPubkey> <peerMeshIP> <peerEndpoint>
+ *
+ * Where peerPubkey / peerMeshIP / peerEndpoint come from the peer host's
+ * own staging run. The two hosts swap these out-of-band before activation.
+ */
+
+import { writeFileSync, readFileSync, mkdirSync, existsSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+const distRoot = join(__dirname, '..', 'dist');
+const wgConfig = await import(join(distRoot, 'domain/value-objects/wg-config.js'));
+const wgMesh = await import(join(distRoot, 'domain/services/wg-mesh-service.js'));
+const wgFirewall = await import(join(distRoot, 'domain/services/wg-firewall-service.js'));
+const trustLevel = await import(join(distRoot, 'domain/entities/trust-level.js'));
+
+const [, , localNodeId, peerNodeId, peerPubkey, peerMeshIPArg, peerEndpoint] = process.argv;
+if (!localNodeId || !peerNodeId || !peerPubkey || !peerMeshIPArg || !peerEndpoint) {
+ console.error(`Usage: node scripts/phase7-stage.mjs <localNodeId> <peerNodeId> <peerPubkey> <peerMeshIP> <peerEndpoint>
+
+If you don't yet have the peer's pubkey, run this on EACH host with
+placeholder values (e.g. 'TBD-x44=' '10.50.0.0/32' 'tbd:51820') to
+generate the local key, then exchange and re-run with real values.`);
+ process.exit(1);
+}
+
+const stageDir = '/tmp/adr-111-stage';
+if (!existsSync(stageDir)) mkdirSync(stageDir, { recursive: true });
+
+// Idempotent: reuse a previously-generated key if present so subsequent runs
+// with corrected peer args don't churn the pubkey. Key is mode 0600.
+const keyFile = join(stageDir, `wg-key-${localNodeId}.json`);
+let localKey;
+if (existsSync(keyFile)) {
+ const persisted = JSON.parse(readFileSync(keyFile, 'utf-8'));
+ localKey = { publicKey: persisted.publicKey, privateKey: persisted.privateKey, createdAt: persisted.createdAt };
+ console.log(`[reused existing key from ${keyFile}]`);
+} else {
+ localKey = wgConfig.generateWgKeyPair();
+}
+const localMeshIP = wgConfig.deriveMeshIP(localNodeId);
+const peerMeshIP = peerMeshIPArg.startsWith('TBD')
+ ? wgConfig.deriveMeshIP(peerNodeId)
+ : peerMeshIPArg;
+
+console.log('=== Local identity (this host) ===');
+console.log(`nodeId: ${localNodeId}`);
+console.log(`meshIP: ${localMeshIP}`);
+console.log(`publicKey: ${localKey.publicKey} ← share this with the peer host`);
+console.log(`platform: ${process.platform}`);
+console.log();
+console.log('=== Peer identity (provided as arg) ===');
+console.log(`nodeId: ${peerNodeId}`);
+console.log(`meshIP: ${peerMeshIP}`);
+console.log(`publicKey: ${peerPubkey}`);
+console.log(`endpoint: ${peerEndpoint}`);
+console.log();
+
+// Persist local private key (mode 0600) for operator to move to .claude-flow/federation/
+writeFileSync(
+ join(stageDir, `wg-key-${localNodeId}.json`),
+ JSON.stringify(
+ { nodeId: localNodeId, ...localKey, meshIP: localMeshIP },
+ null, 2,
+ ),
+ { mode: 0o600 },
+);
+
+// Build the wg-quick interface config naming the peer
+const meshSvc = new wgMesh.WgMeshService({ listenPort: 51820 });
+meshSvc.setLocalIdentity(localKey, localMeshIP);
+
+// FederationNode-shaped object for the service. ATTESTED gets full mesh
+// reachability in v1; the firewall service will narrow ports per
+// WG_NETWORK_GATES once Phase 4 firewall rules load.
+const fakePeer = {
+ nodeId: peerNodeId,
+ trustLevel: trustLevel.TrustLevel.ATTESTED,
+ metadata: {
+ wgPublicKey: peerPubkey,
+ wgMeshIP: peerMeshIP,
+ wgEndpoint: peerEndpoint,
+ },
+};
+
+let interfaceConfig;
+try {
+ interfaceConfig = meshSvc.buildInterfaceConfig([fakePeer]);
+} catch (e) {
+ console.error('ERROR: buildInterfaceConfig refused β€” peer field validation failed.');
+ console.error(` Likely cause: peerPubkey / peerMeshIP / peerEndpoint format unexpected.`);
+ console.error(` ${e?.message ?? e}`);
+ process.exit(2);
+}
+writeFileSync(join(stageDir, 'ruflo-fed.conf'), interfaceConfig);
+
+// Firewall projection per OS
+const fw = new wgFirewall.WgFirewallService();
+const fwFile = process.platform === 'linux' ? 'ruflo-fed.nft' : 'ruflo-fed.pf';
+const fwResult = fw.projectRules([fakePeer]);
+writeFileSync(join(stageDir, fwFile), fwResult.content);
+
+console.log('=== Staged files ===');
+console.log(` ${stageDir}/wg-key-${localNodeId}.json (mode 0600 β€” local private key)`);
+console.log(` ${stageDir}/ruflo-fed.conf (wg-quick config)`);
+console.log(` ${stageDir}/${fwFile} (firewall projection)`);
+console.log();
+console.log('=== Activation checklist (operator-mediated; NOT auto-run) ===');
+console.log(' [ ] Cross-check: peer host ran the same staging with our local pubkey above?');
+console.log(' [ ] Review ruflo-fed.conf for unexpected [Peer] blocks (defense vs compromised manifest)');
+console.log(' [ ] Verify the AllowedIPs only includes the peer\'s mesh IP, not broader CIDR');
+console.log(' [ ] Confirm UDP/51820 is open between the two hosts');
+console.log();
+console.log('=== Activation commands ===');
+console.log(` sudo install -m 0600 ${stageDir}/ruflo-fed.conf /etc/wireguard/ruflo-fed.conf`);
+if (process.platform === 'linux') {
+ console.log(` sudo nft -f ${stageDir}/${fwFile}`);
+} else {
+ console.log(` sudo pfctl -a ruflo-fed -f ${stageDir}/${fwFile}`);
+}
+console.log(' sudo wg-quick up ruflo-fed');
+console.log();
+console.log('=== Verification ===');
+console.log(' sudo wg show ruflo-fed');
+console.log(` ping ${peerMeshIP.replace('/32', '')} # mesh reachability`);
+console.log();
+console.log('=== Rollback ===');
+console.log(' sudo wg-quick down ruflo-fed');
+if (process.platform === 'linux') {
+ console.log(' sudo nft delete table inet ruflo_fed');
+} else {
+ console.log(' sudo pfctl -a ruflo-fed -F all');
+}
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.ts
index 7415a06319..364fe5e19f 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
@@ -425,6 +425,16 @@ export class FederationCoordinator {
}));
}
+ /**
+ * ADR-111 Phase 6: public read of the discovery peer list. Used by
+ * federation_wg_status MCP tool + WG firewall projection. Returns the
+ * full known-peer set (active + suspended + evicted) β€” filter via
+ * .isActive / state if you only want the live mesh members.
+ */
+ listPeers(): readonly FederationNode[] {
+ return this.discovery.listPeers();
+ }
+
/**
* Aggregated counts for the doctor surface β€” `{ active: N, suspended: M,
* evicted: K }`. Cheap O(peers) sweep; safe to call from a status line.
diff --git a/v3/@claude-flow/plugin-agent-federation/src/domain/services/wg-firewall-service.ts b/v3/@claude-flow/plugin-agent-federation/src/domain/services/wg-firewall-service.ts
new file mode 100644
index 0000000000..0cfdbf64f0
--- /dev/null
+++ b/v3/@claude-flow/plugin-agent-federation/src/domain/services/wg-firewall-service.ts
@@ -0,0 +1,251 @@
+/**
+ * ADR-111 Phase 4 β€” Trust-graded firewall projection.
+ *
+ * Projects the WG_NETWORK_GATES table (defined in wg-mesh-service.ts) into
+ * concrete kernel-firewall rules. Two backends:
+ *
+ * - `nftables` for Linux β€” atomic `nft -f <file>` loader, family `inet`,
+ * hook `input` (interface-scoped to the WG iface).
+ * - `pf` for macOS β€” `pfctl -a ruflo-fed -f <file>`, anchor-scoped so
+ * ruflo's rules don't collide with the operator's main pf ruleset.
+ *
+ * Like Phase 2's WgMeshService this is a **pure-projection** service: it
+ * returns rule strings + the shell command the operator runs. It never
+ * shells out or modifies kernel state itself. Operator review is mandatory
+ * because `pf` / `nft` reloads atomically replace the active ruleset for
+ * the targeted scope β€” a typo here can drop ssh.
+ *
+ * v1 scope: the four trust levels VERIFIED/ATTESTED/TRUSTED/PRIVILEGED.
+ * UNTRUSTED peers are never in the mesh (excluded by WgMeshService) so
+ * they don't need a firewall rule either β€” implicit drop policy.
+ */
+
+import { FederationNode } from '../entities/federation-node.js';
+import { TrustLevel } from '../entities/trust-level.js';
+import { WG_NETWORK_GATES, WG_MIN_MESH_TRUST, type WgPortRule } from './wg-mesh-service.js';
+
+export type WgFirewallPlatform = 'linux-nftables' | 'darwin-pf';
+
+export interface WgFirewallServiceConfig {
+ /** Target platform. Default: auto-detect from process.platform. */
+ readonly platform?: WgFirewallPlatform;
+ /** WG interface name to scope rules to. Defaults to `ruflo-fed`. */
+ readonly interfaceName?: string;
+ /** Where the operator should write the rule file. Used for the load-command string. */
+ readonly rulePath?: string;
+ /** pf anchor (macOS only). Defaults to `ruflo-fed`. */
+ readonly pfAnchor?: string;
+}
+
+export interface WgFirewallRuleSet {
+ /** The full rule-file content the operator writes to disk. */
+ readonly content: string;
+ /** The shell command the operator runs to load it. */
+ readonly loadCmd: string;
+ /** Recommended file path (informational β€” the operator decides). */
+ readonly rulePath: string;
+ /** Per-peer rule projections for audit/inspection. */
+ readonly peerProjections: ReadonlyArray<{
+ readonly nodeId: string;
+ readonly trustLabel: string;
+ readonly meshIP: string;
+ readonly rules: readonly string[];
+ }>;
+}
+
+const DEFAULT_INTERFACE = 'ruflo-fed';
+const DEFAULT_PF_ANCHOR = 'ruflo-fed';
+
+function autoDetectPlatform(): WgFirewallPlatform {
+ switch (process.platform) {
+ case 'linux': return 'linux-nftables';
+ case 'darwin': return 'darwin-pf';
+ default:
+ // Other platforms (win32/freebsd) β€” fall back to linux-nftables since
+ // most production federation hosts are linux. The operator can
+ // override via config.platform.
+ return 'linux-nftables';
+ }
+}
+
+/**
+ * Defense-in-depth: every value spliced into a rule line goes through this
+ * filter. Allows the chars `nft`/`pf` syntax actually needs and refuses
+ * anything else β€” a poisoned manifest can't escape the rule string.
+ */
+function assertSafeRuleArg(s: string, label: string): void {
+ if (!/^[A-Za-z0-9_./:-]+$/.test(s)) {
+ throw new Error(`WgFirewallService: refusing unsafe ${label}: ${JSON.stringify(s)}`);
+ }
+}
+
+function projectRuleNftables(rule: WgPortRule, srcIP: string): string {
+ if (rule.proto === 'all') {
+ return ` ip saddr ${srcIP} accept`;
+ }
+ if (rule.port !== undefined) {
+ return ` ip saddr ${srcIP} ${rule.proto} dport ${rule.port} accept`;
+ }
+ if (rule.portRange) {
+ const [lo, hi] = rule.portRange;
+ return ` ip saddr ${srcIP} ${rule.proto} dport ${lo}-${hi} accept`;
+ }
+ throw new Error(`projectRuleNftables: rule missing port/portRange/all: ${JSON.stringify(rule)}`);
+}
+
+function projectRulePf(rule: WgPortRule, iface: string, srcIP: string): string {
+ if (rule.proto === 'all') {
+ return `pass in on ${iface} from ${srcIP} to any keep state`;
+ }
+ if (rule.port !== undefined) {
+ return `pass in on ${iface} proto ${rule.proto} from ${srcIP} to any port ${rule.port} keep state`;
+ }
+ if (rule.portRange) {
+ const [lo, hi] = rule.portRange;
+ return `pass in on ${iface} proto ${rule.proto} from ${srcIP} to any port ${lo}:${hi} keep state`;
+ }
+ throw new Error(`projectRulePf: rule missing port/portRange/all: ${JSON.stringify(rule)}`);
+}
+
+export class WgFirewallService {
+ private readonly platform: WgFirewallPlatform;
+ private readonly interfaceName: string;
+ private readonly rulePath: string;
+ private readonly pfAnchor: string;
+
+ constructor(config: WgFirewallServiceConfig = {}) {
+ this.platform = config.platform ?? autoDetectPlatform();
+ this.interfaceName = config.interfaceName ?? DEFAULT_INTERFACE;
+ assertSafeRuleArg(this.interfaceName, 'interfaceName');
+ this.pfAnchor = config.pfAnchor ?? DEFAULT_PF_ANCHOR;
+ assertSafeRuleArg(this.pfAnchor, 'pfAnchor');
+ this.rulePath = config.rulePath ?? this.defaultRulePath();
+ }
+
+ getPlatform(): WgFirewallPlatform {
+ return this.platform;
+ }
+
+ /**
+ * Project the current peer set into a complete rule file (nftables or pf)
+ * scoped to the WG interface.
+ *
+ * Peers below WG_MIN_MESH_TRUST (UNTRUSTED) are dropped β€” they have no
+ * mesh IP and shouldn't appear in firewall allow rules anyway. Peers
+ * without `metadata.wgMeshIP` are skipped (a stale manifest with no WG
+ * block; the mesh layer already excludes them).
+ */
+ projectRules(peers: readonly FederationNode[]): WgFirewallRuleSet {
+ const eligible = peers.filter(p => {
+ if (p.trustLevel < WG_MIN_MESH_TRUST) return false;
+ const meshIP = p.metadata.wgMeshIP as string | undefined;
+ return typeof meshIP === 'string' && meshIP.length > 0;
+ });
+
+ const peerProjections = eligible.map(peer => {
+ const meshIP = (peer.metadata.wgMeshIP as string).replace(/\/32$/, '');
+ assertSafeRuleArg(meshIP, 'meshIP');
+ const ruleSpecs = WG_NETWORK_GATES[peer.trustLevel];
+ const rules = ruleSpecs.map(r =>
+ this.platform === 'linux-nftables'
+ ? projectRuleNftables(r, meshIP)
+ : projectRulePf(r, this.interfaceName, meshIP),
+ );
+ return {
+ nodeId: peer.nodeId,
+ trustLabel: this.trustLabel(peer.trustLevel),
+ meshIP: peer.metadata.wgMeshIP as string,
+ rules,
+ };
+ });
+
+ const content = this.platform === 'linux-nftables'
+ ? this.renderNftables(peerProjections)
+ : this.renderPf(peerProjections);
+
+ return {
+ content,
+ loadCmd: this.platform === 'linux-nftables'
+ ? `nft -f ${this.rulePath}`
+ : `pfctl -a ${this.pfAnchor} -f ${this.rulePath}`,
+ rulePath: this.rulePath,
+ peerProjections,
+ };
+ }
+
+ private renderNftables(projections: ReadonlyArray<{
+ readonly nodeId: string;
+ readonly trustLabel: string;
+ readonly meshIP: string;
+ readonly rules: readonly string[];
+ }>): string {
+ // Atomic nft script. The `flush` clears existing rules in the table
+ // before reload β€” same atomicity property nft itself guarantees.
+ // Default policy DROP so anything not explicitly allowed is rejected.
+ const lines: string[] = [];
+ lines.push('#!/usr/sbin/nft -f');
+ lines.push('# Generated by ruflo federation plugin β€” ADR-111 Phase 4.');
+ lines.push('# Operator MUST review before `nft -f`. A typo here can drop ssh.');
+ lines.push('# This file is overwritten on every peer-set change; do not hand-edit.');
+ lines.push('');
+ lines.push('table inet ruflo_fed {');
+ lines.push(' chain wg_input {');
+ lines.push(` type filter hook input priority 0; policy drop;`);
+ lines.push(` iifname "${this.interfaceName}" jump wg_peer_rules`);
+ lines.push(' }');
+ lines.push(' chain wg_peer_rules {');
+ if (projections.length === 0) {
+ lines.push(' # No ATTESTED+ peers in mesh.');
+ }
+ for (const p of projections) {
+ lines.push(` # peer ${p.nodeId} β€” trust=${p.trustLabel} mesh=${p.meshIP}`);
+ for (const rule of p.rules) {
+ lines.push(rule);
+ }
+ }
+ lines.push(' }');
+ lines.push('}');
+ return lines.join('\n');
+ }
+
+ private renderPf(projections: ReadonlyArray<{
+ readonly nodeId: string;
+ readonly trustLabel: string;
+ readonly meshIP: string;
+ readonly rules: readonly string[];
+ }>): string {
+ const lines: string[] = [];
+ lines.push('# Generated by ruflo federation plugin β€” ADR-111 Phase 4.');
+ lines.push('# Operator MUST review before `pfctl -f`. A typo here can drop ssh.');
+ lines.push(`# This anchor is scoped to ${this.pfAnchor}; main pf ruleset stays untouched.`);
+ lines.push('');
+ // Default within the anchor: pass nothing not explicitly allowed.
+ // The main ruleset's policy still applies; the anchor only adds allows.
+ if (projections.length === 0) {
+ lines.push('# No ATTESTED+ peers in mesh.');
+ }
+ for (const p of projections) {
+ lines.push(`# peer ${p.nodeId} β€” trust=${p.trustLabel} mesh=${p.meshIP}`);
+ for (const rule of p.rules) {
+ lines.push(rule);
+ }
+ }
+ return lines.join('\n');
+ }
+
+ private defaultRulePath(): string {
+ return this.platform === 'linux-nftables'
+ ? '/etc/nftables.d/ruflo-fed.nft'
+ : `/etc/pf.anchors/${this.pfAnchor}`;
+ }
+
+ private trustLabel(level: TrustLevel): string {
+ switch (level) {
+ case TrustLevel.UNTRUSTED: return 'UNTRUSTED';
+ case TrustLevel.VERIFIED: return 'VERIFIED';
+ case TrustLevel.ATTESTED: return 'ATTESTED';
+ case TrustLevel.TRUSTED: return 'TRUSTED';
+ case TrustLevel.PRIVILEGED: return 'PRIVILEGED';
+ }
+ }
+}
diff --git a/v3/@claude-flow/plugin-agent-federation/src/domain/services/wg-mesh-service.ts b/v3/@claude-flow/plugin-agent-federation/src/domain/services/wg-mesh-service.ts
index e50918eab6..8784d4af88 100644
--- a/v3/@claude-flow/plugin-agent-federation/src/domain/services/wg-mesh-service.ts
+++ b/v3/@claude-flow/plugin-agent-federation/src/domain/services/wg-mesh-service.ts
@@ -64,6 +64,49 @@ export const WG_NETWORK_GATES: Record<TrustLevel, readonly WgPortRule[]> = {
*/
export const WG_MIN_MESH_TRUST: TrustLevel = TrustLevel.VERIFIED;
+/**
+ * Security: validate every field we splice into a wg-quick config string
+ * or shell command. The ADR's threat model explicitly includes "compromised
+ * federation peer with valid WG key" β€” that peer signs their own manifest,
+ * so the Ed25519 signature only proves origin, not content safety. A
+ * compromised peer could publish e.g. wgEndpoint = "host:51820\n[Peer]\n..."
+ * to inject extra peers into the config the operator runs via wg-quick.
+ *
+ * These regexes are intentionally narrow:
+ * - publicKey: base64 X25519, exactly 43 chars + '=' padding
+ * - meshIP: a.b.c.d/32, octets 0-255, no whitespace
+ * - endpoint: hostname-or-ipv4-or-bracketed-ipv6 + :port, no newlines/specials
+ */
+const WG_PUBKEY_REGEX = /^[A-Za-z0-9+/]{43}=$/;
+const WG_MESH_IP_REGEX = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\/32$/;
+const WG_ENDPOINT_REGEX = /^(\[[0-9a-fA-F:]+\]|[a-zA-Z0-9][a-zA-Z0-9.-]*):\d{1,5}$/;
+
+export interface WgPeerFields {
+ readonly wgPublicKey: string;
+ readonly wgMeshIP: string;
+ readonly wgEndpoint: string;
+}
+
+/**
+ * Return the validated peer wg fields, or null if any is malformed or
+ * out-of-range. Callers treat null as "peer not eligible for mesh" β€” the
+ * peer stays in the federation discovery registry but is excluded from
+ * the wg config and any wg commands.
+ */
+export function readSafePeerWgFields(peer: FederationNode): WgPeerFields | null {
+ const pk = peer.metadata.wgPublicKey;
+ const ip = peer.metadata.wgMeshIP;
+ const ep = peer.metadata.wgEndpoint;
+ if (typeof pk !== 'string' || !WG_PUBKEY_REGEX.test(pk)) return null;
+ if (typeof ip !== 'string' || !WG_MESH_IP_REGEX.test(ip)) return null;
+ const ipMatch = ip.match(WG_MESH_IP_REGEX);
+ if (!ipMatch || [ipMatch[1], ipMatch[2], ipMatch[3], ipMatch[4]].some(o => Number(o) > 255)) return null;
+ if (typeof ep !== 'string' || !WG_ENDPOINT_REGEX.test(ep)) return null;
+ const port = Number(ep.split(':').pop());
+ if (port < 1 || port > 65535) return null;
+ return { wgPublicKey: pk, wgMeshIP: ip, wgEndpoint: ep };
+}
+
export interface WgMeshServiceConfig {
/** Local interface name. Defaults to `ruflo-fed`. */
readonly interfaceName?: string;
@@ -161,16 +204,20 @@ export class WgMeshService {
lines.push('');
for (const peer of peers) {
if (peer.trustLevel < WG_MIN_MESH_TRUST) continue;
- const meshIP = peer.metadata.wgMeshIP as string | undefined;
- const wgPubkey = peer.metadata.wgPublicKey as string | undefined;
- const endpoint = peer.metadata.wgEndpoint as string | undefined;
- if (!meshIP || !wgPubkey || !endpoint) continue;
- if (this.evicted.has(wgPubkey)) continue;
- const allowed = this.suspended.has(wgPubkey) ? '' : this.computeAllowedIPs(peer, meshIP).join(', ');
- lines.push(`# Peer ${peer.nodeId} β€” trust=${getTrustLevelLabel(peer.trustLevel)}${this.suspended.has(wgPubkey) ? ' (SUSPENDED)' : ''}`);
+ // Security: validate every spliced field. A compromised but-signed
+ // peer can otherwise inject extra [Peer] blocks via newline-laden
+ // wgEndpoint. readSafePeerWgFields enforces base64/CIDR/host:port
+ // regexes; mismatches skip the peer entirely (safer than partial-write).
+ const safe = readSafePeerWgFields(peer);
+ if (!safe) continue;
+ if (this.evicted.has(safe.wgPublicKey)) continue;
+ const allowed = this.suspended.has(safe.wgPublicKey)
+ ? ''
+ : this.computeAllowedIPs(peer, safe.wgMeshIP).join(', ');
+ lines.push(`# Peer ${peer.nodeId} β€” trust=${getTrustLevelLabel(peer.trustLevel)}${this.suspended.has(safe.wgPublicKey) ? ' (SUSPENDED)' : ''}`);
lines.push('[Peer]');
- lines.push(`PublicKey = ${wgPubkey}`);
- lines.push(`Endpoint = ${endpoint}`);
+ lines.push(`PublicKey = ${safe.wgPublicKey}`);
+ lines.push(`Endpoint = ${safe.wgEndpoint}`);
lines.push(`AllowedIPs = ${allowed}`);
lines.push('');
}
@@ -261,12 +308,16 @@ export class WgMeshService {
return peers
.filter(p => p.trustLevel >= WG_MIN_MESH_TRUST)
.map(peer => {
- const meshIP = (peer.metadata.wgMeshIP as string | undefined) ?? '';
- const pubkey = (peer.metadata.wgPublicKey as string | undefined) ?? '';
- const endpoint = (peer.metadata.wgEndpoint as string | undefined) ?? '';
+ // Security: same validation as buildInterfaceConfig. If a peer
+ // published unsafe wg fields they get reported with empty strings β€”
+ // visible in operator status without becoming an injection vector.
+ const safe = readSafePeerWgFields(peer);
+ const meshIP = safe?.wgMeshIP ?? '';
+ const pubkey = safe?.wgPublicKey ?? '';
+ const endpoint = safe?.wgEndpoint ?? '';
let state: 'active' | 'suspended' | 'evicted' = 'active';
- if (this.evicted.has(pubkey)) state = 'evicted';
- else if (this.suspended.has(pubkey)) state = 'suspended';
+ if (pubkey && this.evicted.has(pubkey)) state = 'evicted';
+ else if (pubkey && this.suspended.has(pubkey)) state = 'suspended';
return {
nodeId: peer.nodeId,
trustLevel: peer.trustLevel,
@@ -275,7 +326,7 @@ export class WgMeshService {
endpoint,
publicKey: pubkey,
state,
- allowedIPs: state === 'active' ? this.computeAllowedIPs(peer, meshIP) : [],
+ allowedIPs: safe && state === 'active' ? this.computeAllowedIPs(peer, safe.wgMeshIP) : [],
};
});
}
diff --git a/v3/@claude-flow/plugin-agent-federation/src/domain/services/wg-witness-service.ts b/v3/@claude-flow/plugin-agent-federation/src/domain/services/wg-witness-service.ts
new file mode 100644
index 0000000000..7d6234ae4d
--- /dev/null
+++ b/v3/@claude-flow/plugin-agent-federation/src/domain/services/wg-witness-service.ts
@@ -0,0 +1,183 @@
+/**
+ * ADR-111 Phase 5 β€” Witness attestation chain for WG mesh mutations.
+ *
+ * Every coordination change (peer added/suspended/evicted/reactivated,
+ * keypair rotated) appends a signed entry to an append-only log
+ * `.claude-flow/federation/wg-changes.log`. The signature is over a
+ * canonical JSON encoding of the entry's content fields, using the
+ * operator's federation Ed25519 key β€” the same identity that signs
+ * federation manifests, so anyone who already trusts the manifest chain
+ * automatically trusts the WG change chain.
+ *
+ * Append-only via O_APPEND open + entries chained by prevHash (sha256 of
+ * the previous entry's canonical bytes). Tampering with history requires
+ * forging a chain of signatures with the operator's key.
+ *
+ * The periodic ruflo witness regen (plugins/ruflo-core/scripts/witness/)
+ * includes wg-changes.log as one of its watched artifacts (operator wires
+ * this via witness-fixes.json).
+ *
+ * Pure service: emits the canonical bytes and the signature to write.
+ * Caller does the I/O so this stays unit-testable without fs mocks.
+ */
+
+import { createHash } from 'node:crypto';
+import type { WgCommand } from './wg-mesh-service.js';
+
+export type WgWitnessEventType =
+ | 'peer-added'
+ | 'peer-removed-suspended'
+ | 'peer-restored'
+ | 'peer-evicted'
+ | 'key-rotated'
+ | 'interface-config-applied';
+
+/**
+ * Canonical fields of a witness entry. The hash + signature are computed
+ * over these in a stable JSON encoding (sorted keys, no whitespace).
+ */
+export interface WgWitnessContent {
+ readonly version: '1';
+ readonly type: WgWitnessEventType;
+ readonly timestamp: string;
+ readonly nodeId: string;
+ /** Public key of the affected peer, if any. */
+ readonly peerPublicKey?: string;
+ /** Mesh IP affected, if any. */
+ readonly meshIP?: string;
+ /** wg command that was emitted, if any. */
+ readonly wgCommand?: string;
+ /** Human-readable rationale for the audit log. */
+ readonly rationale: string;
+ /** Hash of the previous entry in the chain (sha256 hex), or empty for the genesis entry. */
+ readonly prevHash: string;
+}
+
+/**
+ * Full witness entry as it appears on disk β€” content + the operator's
+ * Ed25519 signature over the canonical encoding of content.
+ */
+export interface WgWitnessEntry {
+ readonly content: WgWitnessContent;
+ readonly hash: string; // sha256 of canonicalize(content)
+ readonly signature: string; // operator Ed25519 sig over canonicalize(content), base64
+}
+
+export interface WgWitnessSigner {
+ /** Returns an Ed25519 signature (base64) over the given canonical bytes. */
+ sign(bytes: Buffer): Promise<string>;
+}
+
+/**
+ * Stable JSON serialization for hashing/signing. Keys are sorted; no
+ * whitespace; undefined fields omitted. Same shape on every host so
+ * cross-host verifiers produce identical hashes.
+ */
+export function canonicalizeContent(content: WgWitnessContent): Buffer {
+ const keys = Object.keys(content).sort() as Array<keyof WgWitnessContent>;
+ const ordered: Record<string, unknown> = {};
+ for (const k of keys) {
+ if (content[k] !== undefined) ordered[k] = content[k];
+ }
+ return Buffer.from(JSON.stringify(ordered), 'utf-8');
+}
+
+export function hashContent(content: WgWitnessContent): string {
+ return createHash('sha256').update(canonicalizeContent(content)).digest('hex');
+}
+
+export class WgWitnessService {
+ private readonly nodeId: string;
+ private readonly signer: WgWitnessSigner;
+ private lastHash: string = '';
+
+ constructor(nodeId: string, signer: WgWitnessSigner) {
+ this.nodeId = nodeId;
+ this.signer = signer;
+ }
+
+ /**
+ * Override the previous-hash pointer (used when resuming from an existing
+ * log on disk). Caller reads the last entry from `wg-changes.log` and
+ * passes its `hash` here before appending more.
+ */
+ setLastHash(hash: string): void {
+ this.lastHash = hash;
+ }
+
+ /** Build + sign an entry. Caller is responsible for the actual append-write. */
+ async build(
+ type: WgWitnessEventType,
+ fields: Omit<WgWitnessContent, 'version' | 'type' | 'timestamp' | 'nodeId' | 'prevHash'>,
+ ): Promise<WgWitnessEntry> {
+ const content: WgWitnessContent = {
+ version: '1',
+ type,
+ timestamp: new Date().toISOString(),
+ nodeId: this.nodeId,
+ prevHash: this.lastHash,
+ ...fields,
+ };
+ const canonical = canonicalizeContent(content);
+ const hash = createHash('sha256').update(canonical).digest('hex');
+ const signature = await this.signer.sign(canonical);
+ this.lastHash = hash;
+ return { content, hash, signature };
+ }
+
+ /**
+ * Convenience: take a WgCommand emitted by WgMeshService Phase 2/3 and
+ * produce a witness entry of the right type. Maps verb β†’ eventType.
+ */
+ async attestWgCommand(cmd: WgCommand, meshIP?: string): Promise<WgWitnessEntry> {
+ const typeMap: Record<WgCommand['verb'], WgWitnessEventType> = {
+ 'add-peer': 'peer-added',
+ 'set-allowed-ips': 'peer-restored',
+ 'remove-allowed-ips': 'peer-removed-suspended',
+ 'remove-peer': 'peer-evicted',
+ };
+ return this.build(typeMap[cmd.verb], {
+ peerPublicKey: cmd.peerPublicKey,
+ meshIP,
+ wgCommand: cmd.cmd,
+ rationale: cmd.rationale,
+ });
+ }
+}
+
+/**
+ * Verify a single entry's signature + hash. Caller verifies the chain by
+ * iterating entries and confirming each entry's `prevHash` equals the
+ * preceding entry's `hash`.
+ */
+export async function verifyWitnessEntry(
+ entry: WgWitnessEntry,
+ verify: (bytes: Buffer, signature: string) => Promise<boolean>,
+): Promise<boolean> {
+ const canonical = canonicalizeContent(entry.content);
+ const expectedHash = createHash('sha256').update(canonical).digest('hex');
+ if (entry.hash !== expectedHash) return false;
+ return verify(canonical, entry.signature);
+}
+
+/**
+ * Verify a full chain β€” every entry valid + chain link unbroken.
+ */
+export async function verifyWitnessChain(
+ entries: readonly WgWitnessEntry[],
+ verify: (bytes: Buffer, signature: string) => Promise<boolean>,
+): Promise<{ ok: boolean; failedAt?: number; reason?: string }> {
+ let prevHash = '';
+ for (let i = 0; i < entries.length; i++) {
+ const e = entries[i];
+ if (e.content.prevHash !== prevHash) {
+ return { ok: false, failedAt: i, reason: 'broken-chain-link' };
+ }
+ const validEntry = await verifyWitnessEntry(e, verify);
+ if (!validEntry) {
+ return { ok: false, failedAt: i, reason: 'invalid-signature-or-hash' };
+ }
+ prevHash = e.hash;
+ }
+ return { ok: true };
+}
diff --git a/v3/@claude-flow/plugin-agent-federation/src/mcp-tools.ts b/v3/@claude-flow/plugin-agent-federation/src/mcp-tools.ts
index 8241271fbf..5c51c602ed 100644
--- a/v3/@claude-flow/plugin-agent-federation/src/mcp-tools.ts
+++ b/v3/@claude-flow/plugin-agent-federation/src/mcp-tools.ts
@@ -2,9 +2,12 @@ import type { MCPToolDefinition } from '@claude-flow/shared/src/plugin-interface
import type { PluginContext } from '@claude-flow/shared/src/plugin-interface.js';
import type { FederationCoordinator } from './application/federation-coordinator.js';
import type { FederationMessageType } from './domain/entities/federation-envelope.js';
+import type { WgMeshService } from './domain/services/wg-mesh-service.js';
+import { generateWgKeyPair } from './domain/value-objects/wg-config.js';
type CoordinatorGetter = () => FederationCoordinator | null;
type ContextGetter = () => PluginContext | null;
+type WgMeshGetter = () => WgMeshService | null;
function textResult(text: string, isError = false) {
return { content: [{ type: 'text' as const, text }], isError };
@@ -13,12 +16,18 @@ function textResult(text: string, isError = false) {
export function createMcpTools(
getCoordinator: CoordinatorGetter,
getContext: ContextGetter,
+ getWgMesh: WgMeshGetter = () => null,
): MCPToolDefinition[] {
function requireCoordinator(): FederationCoordinator {
const c = getCoordinator();
if (!c) throw new Error('Federation not initialized');
return c;
}
+ function requireWgMesh(): WgMeshService {
+ const w = getWgMesh();
+ if (!w) throw new Error('WG mesh layer not initialized (set config.wgMesh = true and inject WgMeshService)');
+ return w;
+ }
return [
{
@@ -368,5 +377,91 @@ export function createMcpTools(
}, null, 2));
},
},
+ {
+ name: 'federation_wg_status',
+ description: 'ADR-111 Phase 6: WG mesh state β€” per-peer trust level, mesh IP, suspended/evicted flags, and the AllowedIPs slice each peer currently has. Use to inspect what the breaker has propagated to the L3 layer.',
+ pluginName: '@claude-flow/plugin-agent-federation',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ nodeId: { type: 'string', description: 'Optional: filter to a single peer' },
+ },
+ },
+ handler: async (params) => {
+ const wg = requireWgMesh();
+ const coordinator = requireCoordinator();
+ const peers = coordinator.listPeers();
+ const summary = wg.summarize(peers);
+ const filter = params['nodeId'] as string | undefined;
+ const filtered = filter ? summary.filter(s => s.nodeId === filter) : summary;
+ return textResult(JSON.stringify({
+ interfaceName: wg.getInterfaceName(),
+ meshSubnet: wg.getMeshSubnet(),
+ peers: filtered,
+ }, null, 2));
+ },
+ },
+ {
+ name: 'federation_wg_attest',
+ description: 'ADR-111 Phase 6 (witness chain): emit an operator-signed attestation entry for a coordination change. Returns the canonical bytes the operator signs + the witness entry; operator appends it to .claude-flow/federation/wg-changes.log. Idempotent β€” re-attesting the same change just appends another entry.',
+ pluginName: '@claude-flow/plugin-agent-federation',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ eventType: { type: 'string', description: 'peer-added | peer-removed-suspended | peer-restored | peer-evicted | key-rotated | interface-config-applied' },
+ peerPublicKey: { type: 'string', description: 'Optional: peer pubkey (omit for interface-level events)' },
+ meshIP: { type: 'string', description: 'Optional: peer mesh IP' },
+ wgCommand: { type: 'string', description: 'Optional: wg command that was emitted' },
+ rationale: { type: 'string', description: 'Human-readable rationale for the audit log' },
+ },
+ required: ['eventType', 'rationale'],
+ },
+ handler: async () => {
+ // Phase 6 v1 stub β€” the WgWitnessService is the canonical signer. This
+ // MCP tool returns instructions until plugin.ts wires the service.
+ // Tracked alongside #1879 follow-up: integrate WgWitnessService into
+ // plugin lifecycle so this handler can call attestWgCommand directly.
+ return textResult(
+ 'federation_wg_attest: wire WgWitnessService in plugin.ts (Phase 6 follow-up). Until then, use the WgWitnessService class directly from the federation package.',
+ true,
+ );
+ },
+ },
+ {
+ name: 'federation_wg_keyrotate',
+ description: 'ADR-111 Phase 6: rotate the local WG keypair. Returns the new public key + recommended next steps (republish manifest, peers regenerate their wg-quick config, grace-period destruction of old key). DESTRUCTIVE β€” the old private key is overwritten on disk; existing tunnels are dropped until peers update.',
+ pluginName: '@claude-flow/plugin-agent-federation',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ confirm: { type: 'boolean', description: 'Must be true. Destructive: drops existing tunnels until all peers update their config.' },
+ },
+ required: ['confirm'],
+ },
+ handler: async (params) => {
+ if (params['confirm'] !== true) {
+ return textResult('Refusing rotate: confirm must be true. This drops existing tunnels until peers fetch the new manifest.', true);
+ }
+ // Phase 6 v1: emits a fresh keypair + the upgrade checklist. plugin.ts
+ // is responsible for the actual disk write + manifest republish; this
+ // returns the new public key for the operator to coordinate.
+ const newKey = generateWgKeyPair();
+ return textResult(JSON.stringify({
+ publicKey: newKey.publicKey,
+ createdAt: newKey.createdAt,
+ nextSteps: [
+ 'Write the new private key to .claude-flow/federation/wg-key-<nodeId>.json (mode 0600)',
+ 'Republish federation manifest with the new wg.publicKey',
+ 'Peers regenerate their wg-quick config from the updated manifest',
+ 'Operator removes the old [Peer] block from /etc/wireguard/<iface>.conf after the grace period (default 1h)',
+ 'Run federation_wg_attest with eventType=key-rotated',
+ ],
+ warning: 'Private key NOT returned via MCP. The operator wires the actual disk persistence.',
+ }, null, 2));
+ },
+ },
];
}