Skip to content

Agent Mesh

sdk: join the mesh over libp2p, milestone 2

Antonio Ojea950c4cf25ed2
diff --git a/.github/workflows/sdk.yml b/.github/workflows/sdk.yml
index 5cce6691..8129ad06 100644
--- a/.github/workflows/sdk.yml
+++ b/.github/workflows/sdk.yml
@@ -64,8 +64,10 @@ jobs:
with:
python-version: "3.12"
- - name: Install protoc
- run: sudo apt-get update && sudo apt-get install -y protobuf-compiler
+ - name: Install protoc and py-libp2p build dependencies
+ # fastecdsa (a py-libp2p dependency) ships as a source distribution
+ # and builds against GMP.
+ run: sudo apt-get update && sudo apt-get install -y protobuf-compiler libgmp-dev
- name: JavaScript SDK
run: make sdk-js
@@ -76,5 +78,5 @@ jobs:
- name: Generated bindings are current
run: ./hack/verify-sdk-generated.sh
- - name: Both SDKs against a real control plane
+ - name: Both SDKs on a mesh with a real control plane, router and sam-node
run: go test ./tests/integration -run TestNativeSDKs -count=1 -v
diff --git a/hack/gen-sdk-proto.sh b/hack/gen-sdk-proto.sh
index a51f768d..1ee24c46 100755
--- a/hack/gen-sdk-proto.sh
+++ b/hack/gen-sdk-proto.sh
@@ -47,5 +47,11 @@ protoc -I api \
--python_out="${PY_GEN_DIR}" \
--pyi_out="${PY_GEN_DIR}" \
api/sam.proto
+# The relay v2 client speaks go-libp2p's circuit.proto directly; see the
+# proto's header for why the SDK carries a copy.
+protoc -I sdk/python/proto \
+ --python_out="${PY_GEN_DIR}" \
+ --pyi_out="${PY_GEN_DIR}" \
+ sdk/python/proto/circuit.proto
echo "SDK protobuf generation complete."
diff --git a/sdk/README.md b/sdk/README.md
index 60723cd3..35d3f6d1 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -21,20 +21,49 @@ node and to the control plane, a `sam-node`.
## What exists today
-Milestone 1 is implemented and tested in both languages:
+Milestones 1 and 2 are implemented and tested in both languages:
| Capability | JS | Python |
| --- | --- | --- |
| ed25519 identity, libp2p key encodings, peer ID | yes | yes |
| Enrollment with a bootstrap token (`POST /enroll`, `GET /enroll/status` polling) | yes | yes |
| Enrollment with an OIDC token (`POST /register`) | yes | yes |
-| Credential refresh (`POST /refresh`) | yes | yes |
+| Credential refresh (`POST /refresh`), also in the background while joined | yes | yes |
| Signed key-set sync (`GET /keys`) | yes | yes |
| Persisted state (identity and credential, owner-only files) | yes | yes |
-| `AuthFrame` encoding | yes | yes |
-
-A member built this way holds a valid mesh credential bound to its peer ID
-and knows the router addresses. It cannot yet open a libp2p connection.
+| Biscuit verification of a peer's credential (signature, expiry, peer binding, roles, labels) | yes | yes |
+| libp2p host as `sam-node` configures it (TCP, TLS, yamux) | yes | yes |
+| `/sam/auth/1.0.0`, both sides; join = handshake with a router and check its role | yes | yes |
+| Circuit relay v2 reservation on the router; dial and accept through it | yes | yes |
+
+A member built this way is on the mesh: authenticated with a router,
+reachable through it, verifying every peer that dials it and every peer it
+dials. It cannot yet discover or call tools.
+
+Facts about the libp2p implementations that the SDKs work around, each
+pinned by a test:
+
+- py-libp2p 0.7 advertises early muxer negotiation in TLS ALPN but does not
+ complete it, and go-libp2p then refuses the mux upgrade. The Python host
+ sets no ALPN muxer list, so the muxer is negotiated with
+ multistream-select (`sdk/python/src/agent_mesh/host.py`).
+- js-libp2p's `@libp2p/tls` reads the libp2p extension from
+ `extensions[0]` of the peer certificate. py-libp2p's default certificate
+ puts BasicConstraints and KeyUsage first, so the Python host uses a
+ certificate template with only the libp2p extension.
+- py-libp2p's circuit relay v2 client sends its protobufs without the
+ varint length prefix that go-libp2p (and js-libp2p) use, so it cannot talk
+ to a router. The Python SDK carries the relay protocol itself
+ (`sdk/python/src/agent_mesh/relay.py`, `sdk/python/proto/circuit.proto`)
+ on top of py-libp2p's raw-connection upgrade.
+- go-libp2p's relay leaves private addresses out of a reservation, so a
+ router on loopback (every test) grants a reservation that lists no
+ address. js-libp2p falls back to the connection's address; the Python SDK
+ does the same.
+- js-libp2p reserves a relay slot when it starts listening on
+ `<relay>/p2p-circuit`, and a router refuses that before the auth
+ handshake. The JS SDK starts the listener after the handshake, through the
+ transport manager, which is not on the public `Libp2p` interface.
## Wire contract
@@ -160,39 +189,59 @@ conformance runner against a real control plane in manual-approval mode,
approves the request through `/admin`, and checks the biscuits the SDK
holds against the control plane's records.
-### Milestone 2 — join the mesh
-
-- libp2p host per SDK: TCP, TLS, yamux, identify, circuit relay v2 client,
- Kademlia client with prefix `/sam`, dial-through-relay to peers.
- JS: `libp2p`, `@libp2p/tcp`, `@libp2p/tls`, `@chainsafe/libp2p-yamux`,
- `@libp2p/circuit-relay-v2`, `@libp2p/kad-dht`, `@libp2p/identify`.
- Python: `libp2p>=0.7` (`security.tls`, `stream_muxer.yamux`,
- `relay.circuit_v2`, `kad_dht`); it is trio-based, so the Python SDK's
- networking API is `anyio`-compatible async.
-- Biscuit verification of the peer's `AuthResponse`: signature under a
- trusted control plane key, expiry, authority binding to the connection
- peer ID, and the router role for routers. JS:
- `@biscuit-auth/biscuit-wasm`; Python: `biscuit-python`.
-- `/sam/auth/1.0.0` client handshake with a router; the router addresses come
- from the credential.
-- Background credential refresh, driven by the biscuit's expiration as
- `StartRenewalLoop` does.
-- Test: a Go integration test starts a real router (`startRouter`) and
- checks, through the control plane's lease report, that the SDK member is
- among the router's authenticated peers.
+### Milestone 2 — join the mesh (done)
+
+- libp2p host per SDK, configured as `sam-node`'s: TCP, TLS, yamux,
+ identify, circuit relay v2 client. JS: `libp2p`, `@libp2p/tcp`,
+ `@libp2p/tls`, `@chainsafe/libp2p-yamux`, `@libp2p/circuit-relay-v2`,
+ `@libp2p/identify`. Python: `libp2p>=0.7` (`security.tls`,
+ `stream_muxer.yamux`) plus the SDK's own relay client; py-libp2p is
+ trio-based, so `join()` is an async context manager.
+- Biscuit verification of a peer's credential: signature under any trusted
+ control plane key, authority block only, expiry, binding to the
+ connection peer ID, roles and labels. JS: `@biscuit-auth/biscuit-wasm`,
+ instantiated by hand so no Node flag is needed; Python: `biscuit-python`.
+ `sdk/testdata/biscuit_vectors.json` holds tokens minted by
+ `internal/identity` (valid, other peer, expired, untrusted key, appended
+ block, garbage) and both verifiers agree with the Go one on all of them.
+- `/sam/auth/1.0.0` on both sides. Join connects to the routers in the
+ credential, runs the handshake, requires the router role under the key
+ that verified the token, and reserves a relay slot; the router grants one
+ only to an authenticated peer. Inbound handshakes are answered the way
+ `HandleAuthHandshake` does: a credential that does not verify gets a
+ closed stream and nothing else.
+- `session.authenticate(addr)` connects to any peer, directly or through a
+ router (`/p2p-circuit`), and runs the handshake; `session.authenticatedPeers`
+ is the admitted set. Background refresh is driven by the biscuit's
+ expiration, as `StartRenewalLoop` does.
+- Tests. Unit: each SDK joins an in-process fake router (its own libp2p
+ with the handshake and a relay), and refuses a relay without the router
+ role, a router that trusts another control plane, and a refused
+ reservation. Integration: `tests/integration/sdk_mesh_test.go` runs one
+ mesh with a control plane, a `sam-router`, a `sam-node` and one member per
+ SDK, all real, then walks the connectivity matrix: every member on the
+ router's lease; each SDK member verifies the `sam-node` and the other SDK
+ member on both the direct and the relayed path, and is verified by them;
+ the `sam-node` reaches each member through the router; an admitted Go peer
+ does the same and sends a forged frame; an address behind the router for
+ a peer that is not on the mesh fails. About 7 seconds.
### Milestone 3 — call tools
-- DHT lookup by service type and name; `/sam/mcp/1.0.0` client: send the
- `AuthFrame`, verify the provider's biscuit, then run an MCP client over
- the varint-framed stream. JS: a `Transport` for
- `@modelcontextprotocol/sdk`; Python: a read/write stream pair for `mcp`.
+- Kademlia client with prefix `/sam` (JS: `@libp2p/kad-dht`; Python:
+ `libp2p.kad_dht`, to be checked against go-libp2p the way the relay was),
+ lookup by service type and name.
+- `/sam/mcp/1.0.0` client: send the `AuthFrame` with the target service,
+ verify the provider's biscuit, then run an MCP client over the
+ varint-framed stream. JS: a `Transport` for `@modelcontextprotocol/sdk`;
+ Python: a read/write stream pair for `mcp`.
- Caller-side label requirements (`checkPeerLabels`) on the provider's
biscuit.
-- Public API: `mesh.discover(type, name)`, `mesh.callTool("mcp://svc/tool",
- args)`, `mesh.listTools(peer, service)`.
-- Test: the SDK calls a tool served by a `sam-node` started with
- `startBackgroundNode` and a registered MCP backend, through a real router.
+- Public API: `session.discover(type, name)`,
+ `session.callTool("mcp://svc/tool", args)`, `session.listTools(peer, service)`.
+- Test: the mesh of `sdk_mesh_test.go` gains an MCP backend on the
+ `sam-node`; each SDK member discovers it and calls a tool through the
+ router, and the runners' command protocol gains `discover` and `call`.
### Milestone 4 — serve tools
@@ -240,14 +289,19 @@ python3 -m venv sdk/python/.venv
sdk/python/.venv/bin/pip install -e 'sdk/python[test]'
sdk/python/.venv/bin/pytest sdk/python/tests
-# Both against a real control plane
+# Both against a real control plane, router and sam-node
go test ./tests/integration -run TestNativeSDKs -v
```
-`make sdk-test` runs all of the above. The integration test skips an SDK
+`make sdk-test` runs all of the above. The integration tests skip an SDK
whose toolchain is missing, and CI (`.github/workflows/sdk.yml`) installs
-both so nothing skips there.
+both so nothing skips there. The SDK members in the mesh test are the
+runners `sdk/js/src/conformance-join.ts` and
+`sdk/python/src/agent_mesh/conformance_join.py`: each joins, prints what it
+holds, then takes JSON commands on stdin (`auth`, `peers`, `quit`) so the Go
+test can drive both languages through the same script.
Interoperability facts that the tests pin: `sdk/testdata/identity_vectors.json`
holds key encodings, peer IDs and challenge signatures produced with
-go-libp2p, and every SDK's identity tests reproduce them.
+go-libp2p, `sdk/testdata/biscuit_vectors.json` holds tokens minted by the
+control plane's code, and every SDK reproduces or agrees with them.
diff --git a/sdk/js/README.md b/sdk/js/README.md
index b198f653..37b244ee 100644
--- a/sdk/js/README.md
+++ b/sdk/js/README.md
@@ -3,9 +3,9 @@
Native JavaScript SDK for joining a SAM agent mesh from inside the agent
process. It replaces the `sam-node` sidecar for agents written for Node.js.
-Status: **milestone 1** (identity, enrollment, credential refresh). The
-libp2p transport, service discovery and MCP over the mesh are the next
-milestones; see [../README.md](../README.md) for the plan.
+Status: **milestone 2** (identity, enrollment, credential refresh, joining
+the mesh over libp2p with mutual authentication). Discovering and calling
+tools are the next milestones; see [../README.md](../README.md) for the plan.
## Install
@@ -13,8 +13,10 @@ milestones; see [../README.md](../README.md) for the plan.
cd sdk/js && npm ci && npm run build
```
-Requires Node.js 22.18 or later. The only runtime dependency is
-`@bufbuild/protobuf`.
+Requires Node.js 22.18 or later. Runtime dependencies are
+`@bufbuild/protobuf`, `@biscuit-auth/biscuit-wasm` and the js-libp2p
+packages (`libp2p`, `@libp2p/tcp`, `@libp2p/tls`, `@chainsafe/libp2p-yamux`,
+`@libp2p/circuit-relay-v2`, `@libp2p/identify`).
## Use
@@ -27,11 +29,19 @@ const mesh = await AgentMesh.enroll({
stateDir: `${process.env.HOME}/.config/sam-mesh/agent`,
});
console.log(mesh.peerId); // 12D3Koo...
-await mesh.refresh(); // trades the biscuit for a fresh one
+
+// On the mesh: authenticated with a router, reachable through it, credential
+// kept fresh until close().
+const session = await mesh.join();
+console.log(session.relayAddresses.map(String));
+
+// Reach another member (directly or through a router) and verify it.
+const peer = await session.authenticate("/ip4/.../p2p/<router>/p2p-circuit/p2p/<peer>");
+console.log(peer.roles, peer.labels, peer.expiration);
+await session.close();
// Later, in a new process:
const resumed = await AgentMesh.load({ controlPlaneUrl: "https://hub.sam-mesh.dev", stateDir: "..." });
-const frame = resumed.authFrame("mcp://calculator"); // first frame on a mesh stream
```
`enroll` takes exactly one of `bootstrapTokenPath`, `bootstrapToken` or
@@ -50,14 +60,20 @@ A plaintext `http://` control plane is accepted only on loopback. Pass
- `src/credential.ts`: what a member holds, `AuthFrame` encoding.
- `src/mesh.ts`: `AgentMesh`, persistence under a state directory
(`identity.key` in the libp2p private key encoding, `credential.json`).
+- `src/biscuit.ts`: verification of a peer's credential with biscuit-wasm,
+ as `internal/identity.verifyBiscuit` does.
+- `src/host.ts`, `src/auth.ts`, `src/session.ts`: the libp2p host, the
+ `/sam/auth/1.0.0` handshake on both sides, `MeshSession` with the relay
+ reservation and the refresh loop.
- `src/gen/`: generated from `api/sam.proto` by `hack/gen-sdk-proto.sh`.
## Test
```bash
-npm test # unit tests, fake control plane
-go test ./tests/integration -run TestNativeSDKs # against a real control plane
+npm test # unit tests, fake control plane and router
+go test ./tests/integration -run TestNativeSDKs # real control plane, router and sam-node
```
-The integration test runs `dist/conformance.js`, so build first. It skips
-when `dist/` or `node_modules/` is missing.
+The integration tests run `dist/conformance.js` and
+`dist/conformance-join.js`, so build first. They skip when `dist/` or
+`node_modules/` is missing.
diff --git a/sdk/js/package-lock.json b/sdk/js/package-lock.json
index ebebc5ed..0b4614ce 100644
--- a/sdk/js/package-lock.json
+++ b/sdk/js/package-lock.json
@@ -9,7 +9,18 @@
"version": "0.1.0",
"license": "Apache-2.0",
"dependencies": {
- "@bufbuild/protobuf": "^2.15.0"
+ "@biscuit-auth/biscuit-wasm": "^0.6.0",
+ "@bufbuild/protobuf": "^2.15.0",
+ "@chainsafe/libp2p-yamux": "^8.0.1",
+ "@libp2p/circuit-relay-v2": "^4.2.13",
+ "@libp2p/crypto": "^5.1.23",
+ "@libp2p/identify": "^4.1.14",
+ "@libp2p/interface": "^3.3.0",
+ "@libp2p/tcp": "^11.0.28",
+ "@libp2p/tls": "^3.1.10",
+ "@libp2p/utils": "^7.4.1",
+ "@multiformats/multiaddr": "^13.0.3",
+ "libp2p": "^3.3.11"
},
"devDependencies": {
"@bufbuild/protoc-gen-es": "^2.15.0",
@@ -20,6 +31,15 @@
"node": ">=22.18"
}
},
+ "node_modules/@biscuit-auth/biscuit-wasm": {
+ "version": "0.6.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@biscuit-auth/biscuit-wasm/-/biscuit-wasm-0.6.0.tgz",
+ "integrity": "sha512-QM4rZU+f/WI1tr2vPMCErrGXrJdfK4mTiY1m/JyR1eIiOIJOzoHUHf3Z+hE2a1+Dt9vm6wgGyJg89S871JN7BQ==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=22.0.0"
+ }
+ },
"node_modules/@bufbuild/protobuf": {
"version": "2.15.0",
"resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@bufbuild/protobuf/-/protobuf-2.15.0.tgz",
@@ -77,6 +97,712 @@
"node": ">=14.17"
}
},
+ "node_modules/@chainsafe/is-ip": {
+ "version": "2.1.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@chainsafe/is-ip/-/is-ip-2.1.0.tgz",
+ "integrity": "sha512-KIjt+6IfysQ4GCv66xihEitBjvhU/bixbbbFxdJ1sqCp4uJ0wuZiYBPhksZoy4lfaF0k9cwNzY5upEW/VWdw3w==",
+ "license": "MIT"
+ },
+ "node_modules/@chainsafe/libp2p-yamux": {
+ "version": "8.0.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@chainsafe/libp2p-yamux/-/libp2p-yamux-8.0.1.tgz",
+ "integrity": "sha512-pJsqmUg1cZRJZn/luAtQaq0uLcVfExo51Rg7iRtAEceNYtsKUi/exfegnvTBzTnF1CGmTzVEV3MCLsRhqiNyoA==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@libp2p/interface": "^3.0.0",
+ "@libp2p/utils": "^7.0.0",
+ "race-signal": "^2.0.0",
+ "uint8arraylist": "^2.4.8"
+ }
+ },
+ "node_modules/@chainsafe/netmask": {
+ "version": "2.0.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@chainsafe/netmask/-/netmask-2.0.0.tgz",
+ "integrity": "sha512-I3Z+6SWUoaljh3TBzCnCxjlUyN8tA+NAk5L6m9IxvCf1BENQTePzPMis97CoN/iMW1St3WN+AWCCRp+TTBRiDg==",
+ "license": "MIT",
+ "dependencies": {
+ "@chainsafe/is-ip": "^2.0.1"
+ }
+ },
+ "node_modules/@dnsquery/dns-packet": {
+ "version": "6.1.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@dnsquery/dns-packet/-/dns-packet-6.1.1.tgz",
+ "integrity": "sha512-WXTuFvL3G+74SchFAtz3FgIYVOe196ycvGsMgvSH/8Goptb1qpIQtIuM4SOK9G9lhMWYpHxnXyy544ZhluFOew==",
+ "license": "MIT",
+ "dependencies": {
+ "@leichtgewicht/ip-codec": "^2.0.4",
+ "utf8-codec": "^1.0.0"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/@leichtgewicht/ip-codec": {
+ "version": "2.0.5",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@leichtgewicht/ip-codec/-/ip-codec-2.0.5.tgz",
+ "integrity": "sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw==",
+ "license": "MIT"
+ },
+ "node_modules/@libp2p/circuit-relay-v2": {
+ "version": "4.2.13",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@libp2p/circuit-relay-v2/-/circuit-relay-v2-4.2.13.tgz",
+ "integrity": "sha512-AGEzj72W7Ae5eizaM+HeDzJBR28zK4yYp4BYvUOHQViT62W97FIITo/9Gc5rlkKti+gJJAurBm3cHV4A8Wcoxw==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@libp2p/crypto": "^5.1.23",
+ "@libp2p/interface": "^3.3.0",
+ "@libp2p/interface-internal": "^3.1.13",
+ "@libp2p/peer-collections": "^7.0.28",
+ "@libp2p/peer-id": "^6.0.15",
+ "@libp2p/peer-record": "^9.0.16",
+ "@libp2p/utils": "^7.4.1",
+ "@multiformats/multiaddr": "^13.0.3",
+ "@multiformats/multiaddr-matcher": "^3.0.2",
+ "any-signal": "^4.1.1",
+ "main-event": "^1.0.1",
+ "multiformats": "^14.0.0",
+ "nanoid": "^6.0.0",
+ "progress-events": "^1.1.0",
+ "protons-runtime": "^7.0.0",
+ "retimeable-signal": "^1.0.1",
+ "uint8arraylist": "^3.0.2",
+ "uint8arrays": "^6.1.1"
+ }
+ },
+ "node_modules/@libp2p/circuit-relay-v2/node_modules/uint8arraylist": {
+ "version": "3.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8arraylist/-/uint8arraylist-3.0.2.tgz",
+ "integrity": "sha512-LDVoq9BQaGJzGDUovEnoX6rpKCvnY/Jbtws4ikwnBzjRbq5qBAFpBZevUEbSmMM87aO0Sp+wOZy2ZXf5yODmXQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "uint8arrays": "^6.0.0"
+ }
+ },
+ "node_modules/@libp2p/crypto": {
+ "version": "5.1.23",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@libp2p/crypto/-/crypto-5.1.23.tgz",
+ "integrity": "sha512-u6XVMD1YpUJgjS5MAayrxlzi+hQcj3FHY0wS6/M/T93ntyCW13BmmRzFb2ESamk65PEuSCAChmQeSzRV2sh2rQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@libp2p/interface": "^3.3.0",
+ "@noble/curves": "^2.0.1",
+ "@noble/hashes": "^2.0.1",
+ "multiformats": "^14.0.0",
+ "protons-runtime": "^7.0.0",
+ "uint8arraylist": "^3.0.2",
+ "uint8arrays": "^6.1.1"
+ }
+ },
+ "node_modules/@libp2p/crypto/node_modules/uint8arraylist": {
+ "version": "3.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8arraylist/-/uint8arraylist-3.0.2.tgz",
+ "integrity": "sha512-LDVoq9BQaGJzGDUovEnoX6rpKCvnY/Jbtws4ikwnBzjRbq5qBAFpBZevUEbSmMM87aO0Sp+wOZy2ZXf5yODmXQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "uint8arrays": "^6.0.0"
+ }
+ },
+ "node_modules/@libp2p/identify": {
+ "version": "4.1.14",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@libp2p/identify/-/identify-4.1.14.tgz",
+ "integrity": "sha512-c7oU0DSKzkMNsanruOQc4Zy6mSf3fq8/W+4E/I936HiHZc/LIbUuCWaxbgmQexdfKqECH1qH4q9IwaCUWmjPMQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@libp2p/crypto": "^5.1.23",
+ "@libp2p/interface": "^3.3.0",
+ "@libp2p/interface-internal": "^3.1.13",
+ "@libp2p/peer-id": "^6.0.15",
+ "@libp2p/peer-record": "^9.0.16",
+ "@libp2p/utils": "^7.4.1",
+ "@multiformats/multiaddr": "^13.0.3",
+ "@multiformats/multiaddr-matcher": "^3.0.2",
+ "it-drain": "^3.0.10",
+ "it-parallel": "^3.0.13",
+ "main-event": "^1.0.1",
+ "protons-runtime": "^7.0.0",
+ "uint8arraylist": "^3.0.2",
+ "uint8arrays": "^6.1.1"
+ }
+ },
+ "node_modules/@libp2p/identify/node_modules/uint8arraylist": {
+ "version": "3.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8arraylist/-/uint8arraylist-3.0.2.tgz",
+ "integrity": "sha512-LDVoq9BQaGJzGDUovEnoX6rpKCvnY/Jbtws4ikwnBzjRbq5qBAFpBZevUEbSmMM87aO0Sp+wOZy2ZXf5yODmXQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "uint8arrays": "^6.0.0"
+ }
+ },
+ "node_modules/@libp2p/interface": {
+ "version": "3.3.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@libp2p/interface/-/interface-3.3.0.tgz",
+ "integrity": "sha512-SXahM/4IgpiFKTtocbXYSTA1wEUVjktmT1yBCzBbc2Vgsu1VBCg6SvsFmXo2Hbeyev3D8EU+y3uaCKDB43C/Vg==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@multiformats/dns": "^1.0.6",
+ "@multiformats/multiaddr": "^13.0.3",
+ "main-event": "^1.0.1",
+ "multiformats": "^14.0.0",
+ "progress-events": "^1.1.0",
+ "uint8arraylist": "^3.0.2"
+ }
+ },
+ "node_modules/@libp2p/interface-internal": {
+ "version": "3.1.13",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@libp2p/interface-internal/-/interface-internal-3.1.13.tgz",
+ "integrity": "sha512-+vjQzpQl+0uoWCyNwV5NDnv1RAK9LDeWGeMbx/Fl2ZWrndtuFUPa9LxwqHXrTly6YOhgUatSzVqZBWnrQ1PxGg==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@libp2p/interface": "^3.3.0",
+ "@libp2p/peer-collections": "^7.0.28",
+ "@multiformats/multiaddr": "^13.0.3",
+ "progress-events": "^1.0.1"
+ }
+ },
+ "node_modules/@libp2p/interface/node_modules/uint8arraylist": {
+ "version": "3.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8arraylist/-/uint8arraylist-3.0.2.tgz",
+ "integrity": "sha512-LDVoq9BQaGJzGDUovEnoX6rpKCvnY/Jbtws4ikwnBzjRbq5qBAFpBZevUEbSmMM87aO0Sp+wOZy2ZXf5yODmXQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "uint8arrays": "^6.0.0"
+ }
+ },
+ "node_modules/@libp2p/logger": {
+ "version": "6.2.13",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@libp2p/logger/-/logger-6.2.13.tgz",
+ "integrity": "sha512-+tkZuRPoiFdh+frG//3hQ3goV1uMzRblpZ+mwtezgLXkRNqB5YKBLl+c/rtrurwAUqjCuI/yoEPJBiCizg2z6w==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@libp2p/interface": "^3.3.0",
+ "@multiformats/multiaddr": "^13.0.3",
+ "interface-datastore": "^10.0.1",
+ "multiformats": "^14.0.0",
+ "weald": "^1.1.0"
+ }
+ },
+ "node_modules/@libp2p/multistream-select": {
+ "version": "7.0.28",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@libp2p/multistream-select/-/multistream-select-7.0.28.tgz",
+ "integrity": "sha512-X6rmxeAlFeTDHDc4IPujz+y9TdA8cSMFfWyGJfxdIbQpDc1PwZI/Ttt3YWp0LAT9sbSYVFaWA6cGTN9EnMWtGQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@libp2p/interface": "^3.3.0",
+ "@libp2p/utils": "^7.4.1",
+ "it-length-prefixed": "^11.0.1",
+ "uint8arraylist": "^3.0.2",
+ "uint8arrays": "^6.1.1"
+ }
+ },
+ "node_modules/@libp2p/multistream-select/node_modules/uint8arraylist": {
+ "version": "3.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8arraylist/-/uint8arraylist-3.0.2.tgz",
+ "integrity": "sha512-LDVoq9BQaGJzGDUovEnoX6rpKCvnY/Jbtws4ikwnBzjRbq5qBAFpBZevUEbSmMM87aO0Sp+wOZy2ZXf5yODmXQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "uint8arrays": "^6.0.0"
+ }
+ },
+ "node_modules/@libp2p/peer-collections": {
+ "version": "7.0.28",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@libp2p/peer-collections/-/peer-collections-7.0.28.tgz",
+ "integrity": "sha512-+evafZ5oSnGRfB7z+ycf09ehzNhCKoOZaiHgi6TpnDitpRQM5KQeN0H9Ep2uNJtzyW944HOG41BqcSaHbEHv7Q==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@libp2p/interface": "^3.3.0",
+ "@libp2p/peer-id": "^6.0.15",
+ "@libp2p/utils": "^7.4.1",
+ "multiformats": "^14.0.0"
+ }
+ },
+ "node_modules/@libp2p/peer-id": {
+ "version": "6.0.15",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@libp2p/peer-id/-/peer-id-6.0.15.tgz",
+ "integrity": "sha512-aIbYJcldMNOIzmm9J57aESjZInYFdrQ9AY0ij+qn0Oam2vBxDfEIJZxJu+JzVkB2rVvT+FHDQXKWT2nAqNgB8w==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@libp2p/crypto": "^5.1.23",
+ "@libp2p/interface": "^3.3.0",
+ "multiformats": "^14.0.0",
+ "uint8arrays": "^6.1.1"
+ }
+ },
+ "node_modules/@libp2p/peer-record": {
+ "version": "9.0.16",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@libp2p/peer-record/-/peer-record-9.0.16.tgz",
+ "integrity": "sha512-J4QoPr0F1v6xqjHjAJ9KPbg4jdDlGutDk2K3Km6+o0nWzZCgCGeSEIDOO2UvPa2bFoZTL62cD73fn8tm5K06cg==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@libp2p/crypto": "^5.1.23",
+ "@libp2p/interface": "^3.3.0",
+ "@libp2p/peer-id": "^6.0.15",
+ "@multiformats/multiaddr": "^13.0.3",
+ "multiformats": "^14.0.0",
+ "protons-runtime": "^7.0.0",
+ "uint8-varint": "^3.0.0",
+ "uint8arraylist": "^3.0.2",
+ "uint8arrays": "^6.1.1"
+ }
+ },
+ "node_modules/@libp2p/peer-record/node_modules/uint8arraylist": {
+ "version": "3.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8arraylist/-/uint8arraylist-3.0.2.tgz",
+ "integrity": "sha512-LDVoq9BQaGJzGDUovEnoX6rpKCvnY/Jbtws4ikwnBzjRbq5qBAFpBZevUEbSmMM87aO0Sp+wOZy2ZXf5yODmXQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "uint8arrays": "^6.0.0"
+ }
+ },
+ "node_modules/@libp2p/peer-store": {
+ "version": "12.0.28",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@libp2p/peer-store/-/peer-store-12.0.28.tgz",
+ "integrity": "sha512-dj4qRhN01kml/It5/4P4DVcjfEZXJ2uZVVItCrs2YBGG2HLEYfWQZYROVbTCXDOCWwZK46aJ8eSLt4orsefq7Q==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@libp2p/crypto": "^5.1.23",
+ "@libp2p/interface": "^3.3.0",
+ "@libp2p/peer-collections": "^7.0.28",
+ "@libp2p/peer-id": "^6.0.15",
+ "@libp2p/peer-record": "^9.0.16",
+ "@multiformats/multiaddr": "^13.0.3",
+ "interface-datastore": "^10.0.1",
+ "it-all": "^3.0.9",
+ "main-event": "^1.0.1",
+ "mortice": "^3.3.1",
+ "multiformats": "^14.0.0",
+ "protons-runtime": "^7.0.0",
+ "uint8arraylist": "^3.0.2",
+ "uint8arrays": "^6.1.1"
+ }
+ },
+ "node_modules/@libp2p/peer-store/node_modules/uint8arraylist": {
+ "version": "3.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8arraylist/-/uint8arraylist-3.0.2.tgz",
+ "integrity": "sha512-LDVoq9BQaGJzGDUovEnoX6rpKCvnY/Jbtws4ikwnBzjRbq5qBAFpBZevUEbSmMM87aO0Sp+wOZy2ZXf5yODmXQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "uint8arrays": "^6.0.0"
+ }
+ },
+ "node_modules/@libp2p/tcp": {
+ "version": "11.0.28",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@libp2p/tcp/-/tcp-11.0.28.tgz",
+ "integrity": "sha512-+YD59zz1V8YT47ZiInqoHAeSx45BC2bb5FVu3Bplo5zOxMMNXcH5WATIgn+IYIbusNPpMcs5wKd0QimQwzBl6Q==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@libp2p/interface": "^3.3.0",
+ "@libp2p/utils": "^7.4.1",
+ "@multiformats/multiaddr": "^13.0.3",
+ "@multiformats/multiaddr-matcher": "^3.0.2",
+ "main-event": "^1.0.1",
+ "p-event": "^7.0.0",
+ "progress-events": "^1.0.1",
+ "uint8arraylist": "^3.0.2"
+ }
+ },
+ "node_modules/@libp2p/tcp/node_modules/uint8arraylist": {
+ "version": "3.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8arraylist/-/uint8arraylist-3.0.2.tgz",
+ "integrity": "sha512-LDVoq9BQaGJzGDUovEnoX6rpKCvnY/Jbtws4ikwnBzjRbq5qBAFpBZevUEbSmMM87aO0Sp+wOZy2ZXf5yODmXQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "uint8arrays": "^6.0.0"
+ }
+ },
+ "node_modules/@libp2p/tls": {
+ "version": "3.1.10",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@libp2p/tls/-/tls-3.1.10.tgz",
+ "integrity": "sha512-V8J0hVRjN7AFNX1yA/klNSzmdZwGrxwiu3K7UEeWpxSO4ky86V4W1TYqzIHVaS7mnP/fePU1sIqtgraYeuFCfQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@libp2p/crypto": "^5.1.23",
+ "@libp2p/interface": "^3.3.0",
+ "@libp2p/peer-id": "^6.0.15",
+ "@libp2p/utils": "^7.4.1",
+ "@peculiar/asn1-schema": "^2.4.0",
+ "@peculiar/asn1-x509": "^2.4.0",
+ "@peculiar/webcrypto": "^1.5.0",
+ "@peculiar/x509": "^2.0.0",
+ "asn1js": "^3.0.6",
+ "p-event": "^7.0.0",
+ "protons-runtime": "^7.0.0",
+ "reflect-metadata": "^0.2.2",
+ "uint8arraylist": "^3.0.2",
+ "uint8arrays": "^6.1.1"
+ }
+ },
+ "node_modules/@libp2p/tls/node_modules/uint8arraylist": {
+ "version": "3.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8arraylist/-/uint8arraylist-3.0.2.tgz",
+ "integrity": "sha512-LDVoq9BQaGJzGDUovEnoX6rpKCvnY/Jbtws4ikwnBzjRbq5qBAFpBZevUEbSmMM87aO0Sp+wOZy2ZXf5yODmXQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "uint8arrays": "^6.0.0"
+ }
+ },
+ "node_modules/@libp2p/utils": {
+ "version": "7.4.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@libp2p/utils/-/utils-7.4.1.tgz",
+ "integrity": "sha512-e9cZeop+awI0rFczG4DvAwVeHqBhuCZfTyskvgONfKQrsT7L0BSlTlTTzZoFF8Dnb+QrzHsoIpnl0PrCr0h+Hg==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@chainsafe/is-ip": "^2.1.0",
+ "@chainsafe/netmask": "^2.0.0",
+ "@libp2p/interface": "^3.3.0",
+ "@libp2p/logger": "^6.2.13",
+ "@multiformats/multiaddr": "^13.0.3",
+ "@multiformats/multiaddr-matcher": "^3.0.2",
+ "@sindresorhus/fnv1a": "^3.1.0",
+ "any-signal": "^4.1.1",
+ "cborg": "^6.0.0",
+ "delay": "^7.0.0",
+ "is-loopback-addr": "^2.0.2",
+ "it-length-prefixed": "^11.0.1",
+ "it-pipe": "^3.0.1",
+ "it-pushable": "^3.2.3",
+ "it-stream-types": "^2.0.2",
+ "main-event": "^1.0.1",
+ "netmask": "^2.0.2",
+ "p-defer": "^4.0.1",
+ "p-event": "^7.0.0",
+ "progress-events": "^1.1.0",
+ "protons-runtime": "^7.0.0",
+ "race-signal": "^2.0.0",
+ "uint8-varint": "^3.0.0",
+ "uint8arraylist": "^3.0.2",
+ "uint8arrays": "^6.1.1"
+ }
+ },
+ "node_modules/@libp2p/utils/node_modules/uint8arraylist": {
+ "version": "3.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8arraylist/-/uint8arraylist-3.0.2.tgz",
+ "integrity": "sha512-LDVoq9BQaGJzGDUovEnoX6rpKCvnY/Jbtws4ikwnBzjRbq5qBAFpBZevUEbSmMM87aO0Sp+wOZy2ZXf5yODmXQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "uint8arrays": "^6.0.0"
+ }
+ },
+ "node_modules/@multiformats/dns": {
+ "version": "1.0.15",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@multiformats/dns/-/dns-1.0.15.tgz",
+ "integrity": "sha512-W0zAMABtAn+3chgFcPGvllKND7M6GblMAAFcJQTy+iMmGiyFErZYPzAh2b50Y3SFf340iFV7+ckVgZkGfUyxzA==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@dnsquery/dns-packet": "^6.1.1",
+ "@libp2p/interface": "^3.1.0",
+ "hashlru": "^2.3.0",
+ "p-queue": "^9.0.0",
+ "progress-events": "^1.0.0",
+ "uint8arrays": "^6.1.1"
+ }
+ },
+ "node_modules/@multiformats/multiaddr": {
+ "version": "13.0.3",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@multiformats/multiaddr/-/multiaddr-13.0.3.tgz",
+ "integrity": "sha512-mEqqJ4r3a/uuFMTpRkU316wGNIDQNhuVWpm+ebKTQeYsfv9jXbPONWM6VVnj3KGUrwfsX7GZOyp4TFqEA2SPCw==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@chainsafe/is-ip": "^2.0.1",
+ "multiformats": "^14.0.0",
+ "uint8-varint": "^3.0.0",
+ "uint8arrays": "^6.1.1"
+ }
+ },
+ "node_modules/@multiformats/multiaddr-matcher": {
+ "version": "3.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@multiformats/multiaddr-matcher/-/multiaddr-matcher-3.0.2.tgz",
+ "integrity": "sha512-iphGQJliZxe2yKu57bdRDgeS+3znc5uXtMybDO1Wau3rIjas4zjrjlyxmFz3wqyUL9f3VDQwas/ZqA7N4QeSfw==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@multiformats/multiaddr": "^13.0.0"
+ }
+ },
+ "node_modules/@noble/curves": {
+ "version": "2.4.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@noble/curves/-/curves-2.4.0.tgz",
+ "integrity": "sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==",
+ "license": "MIT",
+ "dependencies": {
+ "@noble/hashes": "2.4.0"
+ },
+ "engines": {
+ "node": ">= 20.19.0"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/@noble/hashes": {
+ "version": "2.4.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@noble/hashes/-/hashes-2.4.0.tgz",
+ "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 20.19.0"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/@peculiar/asn1-asym-key": {
+ "version": "2.9.5",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@peculiar/asn1-asym-key/-/asn1-asym-key-2.9.5.tgz",
+ "integrity": "sha512-U3Q2bUWYNVpfk+oOhPl/+OSHxXaBTQBwMf93jJ7oPi/sbmcY5CnARdjGMwLoXT/ggWSryo5t7A7o3/Gfz0U2WA==",
+ "license": "MIT",
+ "dependencies": {
+ "@peculiar/asn1-pkcs8": "^2.9.5",
+ "@peculiar/asn1-schema": "^2.9.5",
+ "@peculiar/asn1-x509": "^2.9.5",
+ "asn1js": "^3.0.10",
+ "tslib": "^2.8.1"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@peculiar/asn1-cms": {
+ "version": "2.9.5",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@peculiar/asn1-cms/-/asn1-cms-2.9.5.tgz",
+ "integrity": "sha512-4Ivz0fsyFofe0bslNsYcGN9+iETdHX4v+BFwIPr+K/BAt61sHXECP63ff9FntU9zcfVQELJFdUG9so44OjUlBQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@peculiar/asn1-schema": "^2.9.5",
+ "@peculiar/asn1-x509": "^2.9.5",
+ "@peculiar/asn1-x509-attr": "^2.9.5",
+ "asn1js": "^3.0.10",
+ "tslib": "^2.8.1"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@peculiar/asn1-csr": {
+ "version": "2.9.5",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@peculiar/asn1-csr/-/asn1-csr-2.9.5.tgz",
+ "integrity": "sha512-9dO6PcoJeI+1xJ4rG7eINMa6f9Ix/QdRs5UGZ0D7v/R3TzmsbVr5cqAgfYw4xgS9U54ouHYqEz0bIZBbM/UY1g==",
+ "license": "MIT",
+ "dependencies": {
+ "@peculiar/asn1-schema": "^2.9.5",
+ "@peculiar/asn1-x509": "^2.9.5",
+ "asn1js": "^3.0.10",
+ "tslib": "^2.8.1"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@peculiar/asn1-ecc": {
+ "version": "2.9.5",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@peculiar/asn1-ecc/-/asn1-ecc-2.9.5.tgz",
+ "integrity": "sha512-OD+HLlcV7wCL64w0rheX/C0J31DbJce0nf8ulv3UNftQ617JEZE3sQ4cMN6PotXWlJ1M5GQx90G3bywtdKOstw==",
+ "license": "MIT",
+ "dependencies": {
+ "@peculiar/asn1-schema": "^2.9.5",
+ "@peculiar/asn1-x509": "^2.9.5",
+ "asn1js": "^3.0.10",
+ "tslib": "^2.8.1"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@peculiar/asn1-pfx": {
+ "version": "2.9.5",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@peculiar/asn1-pfx/-/asn1-pfx-2.9.5.tgz",
+ "integrity": "sha512-btcH7lbcD4410qnjHvv7F0kEuMNKbX8CFAZSs9CDPWHKzT1byLPHYeR40AnUw9z4CzsijMY0daBFYUvVx75sdA==",
+ "license": "MIT",
+ "dependencies": {
+ "@peculiar/asn1-cms": "^2.9.5",
+ "@peculiar/asn1-pkcs8": "^2.9.5",
+ "@peculiar/asn1-rsa": "^2.9.5",
+ "@peculiar/asn1-schema": "^2.9.5",
+ "asn1js": "^3.0.10",
+ "tslib": "^2.8.1"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@peculiar/asn1-pkcs8": {
+ "version": "2.9.5",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@peculiar/asn1-pkcs8/-/asn1-pkcs8-2.9.5.tgz",
+ "integrity": "sha512-c7UghAGQdBfAHL9JdwcJkAc/lDJKNXfCdYXPXlf8BZdD/fVJjJnXKHxX4gyLhkFTvnGhME7caieSgc2ROtqYTQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@peculiar/asn1-schema": "^2.9.5",
+ "@peculiar/asn1-x509": "^2.9.5",
+ "asn1js": "^3.0.10",
+ "tslib": "^2.8.1"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@peculiar/asn1-pkcs9": {
+ "version": "2.9.5",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@peculiar/asn1-pkcs9/-/asn1-pkcs9-2.9.5.tgz",
+ "integrity": "sha512-4R/zMgLSHbQIZRBwP1KzX6iuNHmW3xFWwu9TS9A00N60fmQqp9DkkqnQFyd0mAYMQTrQefuzQ/yP4U8sOLGUgQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@peculiar/asn1-cms": "^2.9.5",
+ "@peculiar/asn1-pfx": "^2.9.5",
+ "@peculiar/asn1-pkcs8": "^2.9.5",
+ "@peculiar/asn1-schema": "^2.9.5",
+ "@peculiar/asn1-x509": "^2.9.5",
+ "@peculiar/asn1-x509-attr": "^2.9.5",
+ "asn1js": "^3.0.10",
+ "tslib": "^2.8.1"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@peculiar/asn1-rsa": {
+ "version": "2.9.5",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@peculiar/asn1-rsa/-/asn1-rsa-2.9.5.tgz",
+ "integrity": "sha512-kHwBLVMkm9ljlM521ovS7y4z4mr8xuHTdNyyoPlDvckBwFKSgs9HqKBryLBeqHqL2YpIgl+Vspl7kzNGG2phzA==",
+ "license": "MIT",
+ "dependencies": {
+ "@peculiar/asn1-schema": "^2.9.5",
+ "@peculiar/asn1-x509": "^2.9.5",
+ "asn1js": "^3.0.10",
+ "tslib": "^2.8.1"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@peculiar/asn1-schema": {
+ "version": "2.9.5",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@peculiar/asn1-schema/-/asn1-schema-2.9.5.tgz",
+ "integrity": "sha512-Ez3wLKVjaxdsLcgeWN4OE31QkM7oBOgKuuBJxldRYAkfYw2C+8zJPcSd/SThnbhszsEOlAmoaS5kIIkN29fGKQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@peculiar/utils": "^2.0.2",
+ "asn1js": "^3.0.10",
+ "tslib": "^2.8.1"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@peculiar/asn1-x509": {
+ "version": "2.9.5",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@peculiar/asn1-x509/-/asn1-x509-2.9.5.tgz",
+ "integrity": "sha512-NP3ecvN6zTDlwCvogIWL7MJN9AZNuskkIbnlhrlkB97Mn2EqirBUQ8GKzsOmdAL3pRvjGu1Uk/a4DNfiZrWxhw==",
+ "license": "MIT",
+ "dependencies": {
+ "@peculiar/asn1-schema": "^2.9.5",
+ "@peculiar/utils": "^2.0.2",
+ "asn1js": "^3.0.10",
+ "tslib": "^2.8.1"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@peculiar/asn1-x509-attr": {
+ "version": "2.9.5",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@peculiar/asn1-x509-attr/-/asn1-x509-attr-2.9.5.tgz",
+ "integrity": "sha512-PlbL1a74RZiry7puPCZ5hdk/puvivxYJPbjadr2i7DBjHCJFEKCfTRPKL3DILeZFtzJjn95J5EBtSc4/TB9/6Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@peculiar/asn1-schema": "^2.9.5",
+ "@peculiar/asn1-x509": "^2.9.5",
+ "asn1js": "^3.0.10",
+ "tslib": "^2.8.1"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@peculiar/asn1-x509-post-quantum": {
+ "version": "2.9.5",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@peculiar/asn1-x509-post-quantum/-/asn1-x509-post-quantum-2.9.5.tgz",
+ "integrity": "sha512-CTznDkboSgwRpXSFhta+Pe5cQ12JtojdMrmOZTWYkBSvbW/1R5pflPIHkpSlaILIfGcAaxIVpXq880xCfJYzow==",
+ "license": "MIT",
+ "dependencies": {
+ "@peculiar/asn1-asym-key": "^2.9.5",
+ "@peculiar/asn1-schema": "^2.9.5",
+ "@peculiar/asn1-x509": "^2.9.5",
+ "asn1js": "^3.0.10",
+ "tslib": "^2.8.1"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@peculiar/json-schema": {
+ "version": "1.1.12",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@peculiar/json-schema/-/json-schema-1.1.12.tgz",
+ "integrity": "sha512-coUfuoMeIB7B8/NMekxaDzLhaYmp0HZNPEjYRm9goRou8UZIC3z21s0sL9AWoCw4EG876QyO3kYrc61WNF9B/w==",
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
+ "node_modules/@peculiar/utils": {
+ "version": "2.0.3",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@peculiar/utils/-/utils-2.0.3.tgz",
+ "integrity": "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==",
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "^2.8.1"
+ }
+ },
+ "node_modules/@peculiar/webcrypto": {
+ "version": "1.7.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@peculiar/webcrypto/-/webcrypto-1.7.1.tgz",
+ "integrity": "sha512-ODOov0sGMJMf3jPonOkgGqPknTsu+DdQ7kD++gz8aI+aFMOMHFbWAA2taqXXVTdP+OTOQR/znGvSpmkeI0WTYQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@peculiar/asn1-schema": "^2.7.0",
+ "@peculiar/json-schema": "^1.1.12",
+ "@peculiar/utils": "^2.0.2",
+ "tslib": "^2.8.1",
+ "webcrypto-core": "^1.9.2"
+ },
+ "engines": {
+ "node": ">=14.18.0"
+ }
+ },
+ "node_modules/@peculiar/x509": {
+ "version": "2.1.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@peculiar/x509/-/x509-2.1.0.tgz",
+ "integrity": "sha512-IYbg1R03CSQGWwl24kGyqrdVtixNSbRaDvBg1r5wyYjTP+VwPQkka1BzTgU5+vxiuwqg04OxdvdJ1xYYFIdUSA==",
+ "license": "MIT",
+ "dependencies": {
+ "@peculiar/asn1-cms": "^2.9.4",
+ "@peculiar/asn1-csr": "^2.9.4",
+ "@peculiar/asn1-ecc": "^2.9.4",
+ "@peculiar/asn1-pkcs9": "^2.9.4",
+ "@peculiar/asn1-rsa": "^2.9.4",
+ "@peculiar/asn1-schema": "^2.9.4",
+ "@peculiar/asn1-x509": "^2.9.4",
+ "@peculiar/asn1-x509-post-quantum": "^2.9.4",
+ "pvtsutils": "^1.3.6",
+ "tslib": "^2.8.1",
+ "tsyringe": "^4.10.0"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@sindresorhus/fnv1a": {
+ "version": "3.1.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@sindresorhus/fnv1a/-/fnv1a-3.1.0.tgz",
+ "integrity": "sha512-KV321z5m/0nuAg83W1dPLy85HpHDk7Sdi4fJbwvacWsEhAh+rZUW4ZfGcXmUIvjZg4ss2bcwNlRhJ7GBEUG08w==",
+ "license": "MIT",
+ "engines": {
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/@types/node": {
"version": "22.20.4",
"resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@types/node/-/node-22.20.4.tgz",
@@ -100,6 +826,64 @@
"typescript": "*"
}
},
+ "node_modules/abort-error": {
+ "version": "1.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/abort-error/-/abort-error-1.0.2.tgz",
+ "integrity": "sha512-lVgvB2NyPLqbXXhVmXcYFTC1x5K7CiVdPgdY7LGgFQWC8506oN01sPN3i9cl9ynuwF4iJ0TS9exnR7cZ9FuX4w==",
+ "license": "Apache-2.0 OR MIT"
+ },
+ "node_modules/any-signal": {
+ "version": "4.2.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/any-signal/-/any-signal-4.2.0.tgz",
+ "integrity": "sha512-LndMvYuAPf4rC195lk7oSFuHOYFpOszIYrNYv0gHAvz+aEhE9qPZLhmrIz5pXP2BSsPOXvsuHDXEGaiQhIh9wA==",
+ "license": "Apache-2.0 OR MIT",
+ "engines": {
+ "node": ">=16.0.0",
+ "npm": ">=7.0.0"
+ }
+ },
+ "node_modules/asn1js": {
+ "version": "3.0.10",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/asn1js/-/asn1js-3.0.10.tgz",
+ "integrity": "sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "pvtsutils": "^1.3.6",
+ "pvutils": "^1.1.5",
+ "tslib": "^2.8.1"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
+ "node_modules/cborg": {
+ "version": "6.1.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/cborg/-/cborg-6.1.2.tgz",
+ "integrity": "sha512-hQfFh6FuuCDoycN68FtUpjtQx5kCtxOLA8msbpJZxjtxaMqxgHl+4GNwO+0YexH/lHmVzhhAKa0ua+vtmTRoVw==",
+ "license": "Apache-2.0",
+ "bin": {
+ "cborg": "lib/bin.js"
+ }
+ },
+ "node_modules/datastore-core": {
+ "version": "12.0.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/datastore-core/-/datastore-core-12.0.1.tgz",
+ "integrity": "sha512-pfgIE5LG0Z5oyc6TxiLaF/0j4Gh1Yrs2+Ck/qssf9Oxw4s4YKC3zpqifuzThnKakAFWONr/vRv+66Koc0yJvyA==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@libp2p/logger": "^6.2.4",
+ "abort-error": "^1.0.2",
+ "interface-datastore": "^10.0.0",
+ "interface-store": "^8.0.0",
+ "it-drain": "^3.0.10",
+ "it-filter": "^3.1.4",
+ "it-map": "^3.1.4",
+ "it-merge": "^3.0.12",
+ "it-pipe": "^3.0.1",
+ "it-sort": "^3.0.9",
+ "it-take": "^3.0.9"
+ }
+ },
"node_modules/debug": {
"version": "4.4.3",
"resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/debug/-/debug-4.4.3.tgz",
@@ -118,6 +902,288 @@
}
}
},
+ "node_modules/delay": {
+ "version": "7.0.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/delay/-/delay-7.0.0.tgz",
+ "integrity": "sha512-C3vaGs818qzZjCvVJ98GQUMVyWeg7dr5w2Nwwb2t5K8G98jOyyVO2ti2bKYk5yoYElqH3F2yA53ykuEnwD6MCg==",
+ "license": "MIT",
+ "dependencies": {
+ "random-int": "^3.1.0",
+ "unlimited-timeout": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/eventemitter3": {
+ "version": "5.0.4",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/eventemitter3/-/eventemitter3-5.0.4.tgz",
+ "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
+ "license": "MIT"
+ },
+ "node_modules/hashlru": {
+ "version": "2.3.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/hashlru/-/hashlru-2.3.0.tgz",
+ "integrity": "sha512-0cMsjjIC8I+D3M44pOQdsy0OHXGLVz6Z0beRuufhKa0KfaD2wGwAev6jILzXsd3/vpnNQJmWyZtIILqM1N+n5A==",
+ "license": "MIT"
+ },
+ "node_modules/interface-datastore": {
+ "version": "10.0.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/interface-datastore/-/interface-datastore-10.0.1.tgz",
+ "integrity": "sha512-DYMj/Og5Cz1Qwkx6/x5KRvR8SYEX7rVAv3KKCm2NzTwWSfpNAC4PahjcYbHyoZBP6zPWrhQv5n5wE+vaDdgSAg==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "abort-error": "^1.0.2",
+ "interface-store": "^8.0.0",
+ "uint8arrays": "^6.1.1"
+ }
+ },
+ "node_modules/interface-store": {
+ "version": "8.0.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/interface-store/-/interface-store-8.0.0.tgz",
+ "integrity": "sha512-e2+s3EEROzM+Wlas4hU3zveTUscvVMf1BOvdsJfpzFm19SoEXLVadpACjWOnM491HqGpvtfFnevyiaN8W+I6Eg==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "abort-error": "^1.0.2"
+ }
+ },
+ "node_modules/is-loopback-addr": {
+ "version": "2.1.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/is-loopback-addr/-/is-loopback-addr-2.1.0.tgz",
+ "integrity": "sha512-77bB59Coq+vGTibZlnuYVU1bUuiboGZ62ZJ7TqmgYKb+hko9dSlqS5OfqvmPZhwJys48At4y4D1UJP3GuvoXtQ==",
+ "license": "MIT"
+ },
+ "node_modules/is-network-error": {
+ "version": "1.3.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/is-network-error/-/is-network-error-1.3.2.tgz",
+ "integrity": "sha512-PhBY86zaxNZUuWP6h13Vu5oFe0XY6/UlKzQnYFELzGVHygP3MxmvTfYSG7GN3aIab/iWudSMgjSnG9Dq+nHrgA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/it-all": {
+ "version": "3.0.11",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/it-all/-/it-all-3.0.11.tgz",
+ "integrity": "sha512-Gvqj6MO4GMLnFdtE68HZRpGBskNC+9+GQ+JevTGNYLyhjUuPhjDLU3jN1LpBemXJDW1bRSkczqA/qGyKlPKrcQ==",
+ "license": "Apache-2.0 OR MIT"
+ },
+ "node_modules/it-drain": {
+ "version": "3.0.12",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/it-drain/-/it-drain-3.0.12.tgz",
+ "integrity": "sha512-RaFA9X1PF2Pf1Jlqhgf5PlXLgf6CaZt7tSzhia+EkEVcAJRKa0Uhr8UnjVv0GmOA3Air9jDJfIX2KIvz5hZ1Ag==",
+ "license": "Apache-2.0 OR MIT"
+ },
+ "node_modules/it-filter": {
+ "version": "3.1.6",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/it-filter/-/it-filter-3.1.6.tgz",
+ "integrity": "sha512-yXiGPAvJn/exXjVFSCMQc3+J/7RLpOMwKoY2DH1yMhF4lYkdRoAdOwU0vnDACAlRAexf7AZvESZIc9mzhEoi/A==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "it-peekable": "^3.0.0"
+ }
+ },
+ "node_modules/it-length-prefixed": {
+ "version": "11.0.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/it-length-prefixed/-/it-length-prefixed-11.0.1.tgz",
+ "integrity": "sha512-0Cy4RHFiL2CH060Lkigq0N37VaPg7oSylG6YjXErq+ccJFYcNEWNzxNjbqceio/sY1C+q84vZXOCE6/C0flYfQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "it-reader": "^7.0.0",
+ "it-stream-types": "^2.0.1",
+ "uint8-varint": "^3.0.0",
+ "uint8arraylist": "^3.0.1",
+ "uint8arrays": "^6.1.0"
+ }
+ },
+ "node_modules/it-length-prefixed/node_modules/uint8arraylist": {
+ "version": "3.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8arraylist/-/uint8arraylist-3.0.2.tgz",
+ "integrity": "sha512-LDVoq9BQaGJzGDUovEnoX6rpKCvnY/Jbtws4ikwnBzjRbq5qBAFpBZevUEbSmMM87aO0Sp+wOZy2ZXf5yODmXQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "uint8arrays": "^6.0.0"
+ }
+ },
+ "node_modules/it-map": {
+ "version": "3.1.6",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/it-map/-/it-map-3.1.6.tgz",
+ "integrity": "sha512-wCix0FXImtIPIxhCnbz35RqWs00e/CReSZX9nZq1j46JcAzBBp57ob9/2l1WnDYEaUURIR8xCyg2NsWbOwBJFQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "it-peekable": "^3.0.0"
+ }
+ },
+ "node_modules/it-merge": {
+ "version": "3.0.15",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/it-merge/-/it-merge-3.0.15.tgz",
+ "integrity": "sha512-rUskoyECUdJsUwpfBtiLXddm56J+vukMztq+PpfTss1mRl/aHv1YJs+6Q2XnpvDThFC2y4Xm636X0xh6IecPGg==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "it-queueless-pushable": "^2.0.0"
+ }
+ },
+ "node_modules/it-parallel": {
+ "version": "3.0.16",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/it-parallel/-/it-parallel-3.0.16.tgz",
+ "integrity": "sha512-qr3nTgj4fraSfr6Ix9JkHsy/Yb/4vmS3QIAu3fsX52r2SOTLbohXoixKp6AIhTJcorpKwjP0VFcpHr5V54jivA==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "p-defer": "^4.0.1"
+ }
+ },
+ "node_modules/it-peekable": {
+ "version": "3.0.10",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/it-peekable/-/it-peekable-3.0.10.tgz",
+ "integrity": "sha512-2E6+p1pelZOhzp69aaiiBuEybWzAl10uYbIdCR3Pxy8bFNnS/kgpbLtGbNbIZ6RVdU7yHHkmATYwjy52GfFEKA==",
+ "license": "Apache-2.0 OR MIT"
+ },
+ "node_modules/it-pipe": {
+ "version": "3.0.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/it-pipe/-/it-pipe-3.0.1.tgz",
+ "integrity": "sha512-sIoNrQl1qSRg2seYSBH/3QxWhJFn9PKYvOf/bHdtCBF0bnghey44VyASsWzn5dAx0DCDDABq1hZIuzKmtBZmKA==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "it-merge": "^3.0.0",
+ "it-pushable": "^3.1.2",
+ "it-stream-types": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=16.0.0",
+ "npm": ">=7.0.0"
+ }
+ },
+ "node_modules/it-pushable": {
+ "version": "3.2.4",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/it-pushable/-/it-pushable-3.2.4.tgz",
+ "integrity": "sha512-WSD7Ss4oCRfDZJT4ldLWr0Bom/muY90xxoJ5PQnU3uSKf0kxCOeehqZtiJX1ARqn+ymXGh1bxpDW9bDNHp2ivQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "p-defer": "^4.0.0"
+ }
+ },
+ "node_modules/it-queue": {
+ "version": "1.1.4",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/it-queue/-/it-queue-1.1.4.tgz",
+ "integrity": "sha512-cGH0+YfMPmwQ+lV+MhJcOXqOgE04h0zQCXvDUmvGGTyW0VqxJZbi7V+PQFEuPVN/5dHQg5RY9aVjMCgmxXaE5Q==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "abort-error": "^1.0.2",
+ "it-pushable": "^3.2.3",
+ "main-event": "^1.0.1",
+ "race-event": "^1.6.1",
+ "race-signal": "^2.0.0"
+ }
+ },
+ "node_modules/it-queueless-pushable": {
+ "version": "2.0.5",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/it-queueless-pushable/-/it-queueless-pushable-2.0.5.tgz",
+ "integrity": "sha512-BaKqGLL1AQMR1AEaxiM09vzJQVXHHhfhh9UV0qPqORw/8Rm8igDQqT1qHregfHIb1NIW9jxQ/aXBibHJyuivuQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "abort-error": "^1.0.2",
+ "p-defer": "^4.0.1",
+ "race-signal": "^2.0.0"
+ }
+ },
+ "node_modules/it-reader": {
+ "version": "7.0.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/it-reader/-/it-reader-7.0.0.tgz",
+ "integrity": "sha512-bTWQPHH1if8N1K9XeidDjhTDm51ALbOksMa9uCZVVsQkoIPXP0XVKM88/Ynqr7HS18La/P1Kvu7C73j4rRoKWQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "it-stream-types": "^2.0.1",
+ "uint8arraylist": "^3.0.1"
+ }
+ },
+ "node_modules/it-reader/node_modules/uint8arraylist": {
+ "version": "3.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8arraylist/-/uint8arraylist-3.0.2.tgz",
+ "integrity": "sha512-LDVoq9BQaGJzGDUovEnoX6rpKCvnY/Jbtws4ikwnBzjRbq5qBAFpBZevUEbSmMM87aO0Sp+wOZy2ZXf5yODmXQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "uint8arrays": "^6.0.0"
+ }
+ },
+ "node_modules/it-sort": {
+ "version": "3.0.11",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/it-sort/-/it-sort-3.0.11.tgz",
+ "integrity": "sha512-eZ22LAoNLx4i4gVV44tJPoUYf/o+mHKa6+OigdVH/hmsdA2qoJN6MNPvKZyZKBf6+S/8PBE44zyvkzdYGkRhbA==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "it-all": "^3.0.0"
+ }
+ },
+ "node_modules/it-stream-types": {
+ "version": "2.0.4",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/it-stream-types/-/it-stream-types-2.0.4.tgz",
+ "integrity": "sha512-tsX+klvMQ53J4Jm2B52vCIs7WD609ck+VS9X2TKMEv7VPY9VwaYKmSWyHek5QS0wHBtP0bWj9KMqCtAHgVKiXw==",
+ "license": "Apache-2.0 OR MIT"
+ },
+ "node_modules/it-take": {
+ "version": "3.0.11",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/it-take/-/it-take-3.0.11.tgz",
+ "integrity": "sha512-zvoeEjLViGFyhYT5KNCgmcIH90Si8lCve4aTMvgej/ZQRfB9YzrcJW3UHIJjbQ9TiAnsT4vsWDImEFQNk5xmnA==",
+ "license": "Apache-2.0 OR MIT"
+ },
+ "node_modules/libp2p": {
+ "version": "3.3.11",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/libp2p/-/libp2p-3.3.11.tgz",
+ "integrity": "sha512-+J3Dw1RnGdcpQaPN1HD+Z6xVS3qY0vnsqE2Tu//pfoiJxabaZVkc2FBNnNQ1Sj+Th2qoloeJ11jvxuNXSa1gtA==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "@chainsafe/is-ip": "^2.1.0",
+ "@chainsafe/netmask": "^2.0.0",
+ "@libp2p/crypto": "^5.1.23",
+ "@libp2p/interface": "^3.3.0",
+ "@libp2p/interface-internal": "^3.1.13",
+ "@libp2p/logger": "^6.2.13",
+ "@libp2p/multistream-select": "^7.0.28",
+ "@libp2p/peer-collections": "^7.0.28",
+ "@libp2p/peer-id": "^6.0.15",
+ "@libp2p/peer-store": "^12.0.28",
+ "@libp2p/utils": "^7.4.1",
+ "@multiformats/dns": "^1.0.6",
+ "@multiformats/multiaddr": "^13.0.3",
+ "@multiformats/multiaddr-matcher": "^3.0.2",
+ "any-signal": "^4.1.1",
+ "datastore-core": "^12.0.1",
+ "interface-datastore": "^10.0.1",
+ "it-merge": "^3.0.12",
+ "it-parallel": "^3.0.13",
+ "main-event": "^1.0.1",
+ "multiformats": "^14.0.0",
+ "p-defer": "^4.0.1",
+ "p-event": "^7.0.0",
+ "p-retry": "^8.0.0",
+ "progress-events": "^1.1.0",
+ "race-signal": "^2.0.0",
+ "uint8arrays": "^6.1.1"
+ }
+ },
+ "node_modules/main-event": {
+ "version": "1.0.5",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/main-event/-/main-event-1.0.5.tgz",
+ "integrity": "sha512-4l9z8r7Q446mhhVTwdHmfPksOYBwN2xa7ewEW2yxPVNQapIaAf57ORFLMB91SpMEMa4wXowect7fq3uMLjDnGA==",
+ "license": "Apache-2.0 OR MIT"
+ },
+ "node_modules/mortice": {
+ "version": "3.3.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/mortice/-/mortice-3.3.1.tgz",
+ "integrity": "sha512-t3oESfijIPGsmsdLEKjF+grHfrbnKSXflJtgb1wY14cjxZpS6GnhHRXTxxzCAoCCnq1YYfpEPwY3gjiCPhOufQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "abort-error": "^1.0.0",
+ "it-queue": "^1.1.0",
+ "main-event": "^1.0.0"
+ }
+ },
"node_modules/ms": {
"version": "2.1.3",
"resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/ms/-/ms-2.1.3.tgz",
@@ -125,6 +1191,228 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/multiformats": {
+ "version": "14.0.5",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/multiformats/-/multiformats-14.0.5.tgz",
+ "integrity": "sha512-vbIm83F2yZ1pWJGS0yl0ysracIvv56LtbrIyiIQHoLdYDJOMoLfVFsXhh9DUH4SFdkdkFhucyWniihsNzVEjkQ==",
+ "license": "Apache-2.0 OR MIT"
+ },
+ "node_modules/nanoid": {
+ "version": "6.0.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/nanoid/-/nanoid-6.0.1.tgz",
+ "integrity": "sha512-3wVS3i51pE2pi1k5FFL/95BGfVS0kSsvDVuGXHOtxox/TywUmtgq+3qiTOTbs9J7KfHaXPiN171k/A6dBnaXFw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.js"
+ },
+ "engines": {
+ "node": "^22 || ^24 || >=26"
+ }
+ },
+ "node_modules/netmask": {
+ "version": "2.1.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/netmask/-/netmask-2.1.1.tgz",
+ "integrity": "sha512-eonl3sLUha+S1GzTPxychyhnUzKyeQkZ7jLjKrBagJgPla13F+uQ71HgpFefyHgqrjEbCPkDArxYsjY8/+gLKA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4.0"
+ }
+ },
+ "node_modules/p-defer": {
+ "version": "4.0.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/p-defer/-/p-defer-4.0.1.tgz",
+ "integrity": "sha512-Mr5KC5efvAK5VUptYEIopP1bakB85k2IWXaRC0rsh1uwn1L6M0LVml8OIQ4Gudg4oyZakf7FmeRLkMMtZW1i5A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/p-event": {
+ "version": "7.1.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/p-event/-/p-event-7.1.1.tgz",
+ "integrity": "sha512-T629EpxCTho6yxIZz2dFZwMkyWUM5jh/0h1+u/Xo4+Fllu0DuKQF6ghqIgSWVTluIvHSXL+XBRScH+E+y9TQ0g==",
+ "license": "MIT",
+ "dependencies": {
+ "p-timeout": "^7.0.1"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/p-queue": {
+ "version": "9.3.3",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/p-queue/-/p-queue-9.3.3.tgz",
+ "integrity": "sha512-NXAOdnEe5FsZJfT4oK84lE1Y5cFFdWlRuOo5tww8DyNMxyRXwn39fIkUtNLKppcPC+UYU/bXujNCUGDv01y7CA==",
+ "license": "MIT",
+ "dependencies": {
+ "eventemitter3": "^5.0.4",
+ "p-timeout": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/p-retry": {
+ "version": "8.0.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/p-retry/-/p-retry-8.0.1.tgz",
+ "integrity": "sha512-NAigyu8hfvJe7MsS18mnc4is0MZtau3QMdBklaJKK23oBQb6occO3UPM3vHmTckW8KhfyjMZaUOqdTFEYliHgg==",
+ "license": "MIT",
+ "dependencies": {
+ "is-network-error": "^1.3.0"
+ },
+ "engines": {
+ "node": ">=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/p-timeout": {
+ "version": "7.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/p-timeout/-/p-timeout-7.0.2.tgz",
+ "integrity": "sha512-prbX4Z3YszrFNgH+MW5Zoeq3baXrMtP/MQnFeET90UB/GtGcGDQ5Usg9OCy6ETjTTntOw1SL2z9fMPUppN3Guw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=20"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/progress-events": {
+ "version": "1.1.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/progress-events/-/progress-events-1.1.0.tgz",
+ "integrity": "sha512-82DVc5tI36neVB3IjdXR11ztwGuoBc98em9ijzubeZKxI47OlV2Znq6mlPqE5xPDzO2Uw98GHiQSjj2favBCRQ==",
+ "license": "Apache-2.0 OR MIT"
+ },
+ "node_modules/protons-runtime": {
+ "version": "7.1.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/protons-runtime/-/protons-runtime-7.1.2.tgz",
+ "integrity": "sha512-j7Y7MfCwPCxYwopyqDt8+CoJULzdajSBrFAzzfBHEhOTfdvOJ2z1QLK9aK34bSBz6V/9JAAlrsc/rFkIbqppuw==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "uint8-varint": "^3.0.0",
+ "uint8arraylist": "^3.0.0",
+ "uint8arrays": "^6.0.0"
+ }
+ },
+ "node_modules/protons-runtime/node_modules/uint8arraylist": {
+ "version": "3.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8arraylist/-/uint8arraylist-3.0.2.tgz",
+ "integrity": "sha512-LDVoq9BQaGJzGDUovEnoX6rpKCvnY/Jbtws4ikwnBzjRbq5qBAFpBZevUEbSmMM87aO0Sp+wOZy2ZXf5yODmXQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "uint8arrays": "^6.0.0"
+ }
+ },
+ "node_modules/pvtsutils": {
+ "version": "1.3.6",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/pvtsutils/-/pvtsutils-1.3.6.tgz",
+ "integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "^2.8.1"
+ }
+ },
+ "node_modules/pvutils": {
+ "version": "1.2.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/pvutils/-/pvutils-1.2.0.tgz",
+ "integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=16.0.0"
+ }
+ },
+ "node_modules/race-event": {
+ "version": "1.6.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/race-event/-/race-event-1.6.1.tgz",
+ "integrity": "sha512-vi7WH5g5KoTFpu2mme/HqZiWH14XSOtg5rfp6raBskBHl7wnmy3F/biAIyY5MsK+BHWhoPhxtZ1Y2R7OHHaWyQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "abort-error": "^1.0.1"
+ }
+ },
+ "node_modules/race-signal": {
+ "version": "2.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/race-signal/-/race-signal-2.0.2.tgz",
+ "integrity": "sha512-IuNNNY5NLriMFEGl3BVei2xq9NIcpkuAklhPWamhu5tRJrJz0w9sloUMz73YXpmUluE2EZocmJm9rpQqXmCPiA==",
+ "license": "Apache-2.0 OR MIT"
+ },
+ "node_modules/random-int": {
+ "version": "3.1.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/random-int/-/random-int-3.1.0.tgz",
+ "integrity": "sha512-h8CRz8cpvzj0hC/iH/1Gapgcl2TQ6xtnCpyOI5WvWfXf/yrDx2DOU+tD9rX23j36IF11xg1KqB9W11Z18JPMdw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/reflect-metadata": {
+ "version": "0.2.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
+ "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/retimeable-signal": {
+ "version": "1.0.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/retimeable-signal/-/retimeable-signal-1.0.1.tgz",
+ "integrity": "sha512-Cy26CYfbWnYu8HMoJeDhaMpW/EYFIbne3vMf6G9RSrOyWYXbPehja/BEdzpqmM84uy2bfBD7NPZhoQ4GZEtgvg==",
+ "license": "Apache-2.0 OR MIT"
+ },
+ "node_modules/supports-color": {
+ "version": "10.2.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/supports-color/-/supports-color-10.2.2.tgz",
+ "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/supports-color?sponsor=1"
+ }
+ },
+ "node_modules/tslib": {
+ "version": "2.8.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/tslib/-/tslib-2.8.1.tgz",
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+ "license": "0BSD"
+ },
+ "node_modules/tsyringe": {
+ "version": "4.10.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/tsyringe/-/tsyringe-4.10.0.tgz",
+ "integrity": "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==",
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "^1.9.3"
+ },
+ "engines": {
+ "node": ">= 6.0.0"
+ }
+ },
+ "node_modules/tsyringe/node_modules/tslib": {
+ "version": "1.14.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/tslib/-/tslib-1.14.1.tgz",
+ "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",
+ "license": "0BSD"
+ },
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/typescript/-/typescript-5.9.3.tgz",
@@ -139,12 +1427,114 @@
"node": ">=14.17"
}
},
+ "node_modules/uint8-varint": {
+ "version": "3.0.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8-varint/-/uint8-varint-3.0.0.tgz",
+ "integrity": "sha512-S4DdpXBaLwKcFo7f0bWzWfHjbZ/i3QhM842qn+ZvHjxqFCfUcEB9SQNcmI69S+zMlcmIcKxsk9Iyw77S2Kxv6Q==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "uint8arraylist": "^3.0.1",
+ "uint8arrays": "^6.1.0"
+ }
+ },
+ "node_modules/uint8-varint/node_modules/uint8arraylist": {
+ "version": "3.0.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8arraylist/-/uint8arraylist-3.0.2.tgz",
+ "integrity": "sha512-LDVoq9BQaGJzGDUovEnoX6rpKCvnY/Jbtws4ikwnBzjRbq5qBAFpBZevUEbSmMM87aO0Sp+wOZy2ZXf5yODmXQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "uint8arrays": "^6.0.0"
+ }
+ },
+ "node_modules/uint8arraylist": {
+ "version": "2.4.9",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8arraylist/-/uint8arraylist-2.4.9.tgz",
+ "integrity": "sha512-KxWjyEFzchzik3aoQlK66oaoxIReoMo5bQRm1fcjBUZvE8xv/tyR3CTKhjh6K/faV8VaF6hd5pjr45CzbwuwkA==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "uint8arrays": "^5.0.1"
+ }
+ },
+ "node_modules/uint8arraylist/node_modules/multiformats": {
+ "version": "13.4.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/multiformats/-/multiformats-13.4.2.tgz",
+ "integrity": "sha512-eh6eHCrRi1+POZ3dA+Dq1C6jhP1GNtr9CRINMb67OKzqW9I5DUuZM/3jLPlzhgpGeiNUlEGEbkCYChXMCc/8DQ==",
+ "license": "Apache-2.0 OR MIT"
+ },
+ "node_modules/uint8arraylist/node_modules/uint8arrays": {
+ "version": "5.1.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8arrays/-/uint8arrays-5.1.1.tgz",
+ "integrity": "sha512-9muQwa4wZG4dKi9gMAIBtnk2Pw87SRpvWTH6lOGm19V2Uqxr4uomUf2PGqPnWc+qs06sN8owUU4jfcoWOcfwVQ==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "multiformats": "^13.0.0"
+ }
+ },
+ "node_modules/uint8arrays": {
+ "version": "6.1.1",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/uint8arrays/-/uint8arrays-6.1.1.tgz",
+ "integrity": "sha512-iz7JN0XCSZYA111lhFG2Ui9EhFvTNekqSRHw3lvMHq+dzwWy1OQftxFQREEh4rffU0oSoXdQHsk2TiHKVm4fsA==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "multiformats": "^14.0.0"
+ }
+ },
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
+ },
+ "node_modules/unlimited-timeout": {
+ "version": "0.1.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/unlimited-timeout/-/unlimited-timeout-0.1.0.tgz",
+ "integrity": "sha512-D4g+mxFeQGQHzCfnvij+R35ukJ0658Zzudw7j16p4tBBbNasKkKM4SocYxqhwT5xA7a9JYWDzKkEFyMlRi5sng==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=20"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/utf8-codec": {
+ "version": "1.0.0",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/utf8-codec/-/utf8-codec-1.0.0.tgz",
+ "integrity": "sha512-S/QSLezp3qvG4ld5PUfXiH7mCFxLKjSVZRFkB3DOjgwHuJPFDkInAXc/anf7BAbHt/D38ozDzL+QMZ6/7gsI6w==",
+ "license": "MIT"
+ },
+ "node_modules/weald": {
+ "version": "1.1.3",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/weald/-/weald-1.1.3.tgz",
+ "integrity": "sha512-vMWtNbYuPb58NeG2+0sKA0Een4VMDwzf+3oHqh68buWRSOMUBlUeRb11LhV28czV+DUpJHRykifijZDuS9bInA==",
+ "license": "Apache-2.0 OR MIT",
+ "dependencies": {
+ "ms": "^4.0.0-nightly.202508271359",
+ "supports-color": "^10.0.0"
+ }
+ },
+ "node_modules/weald/node_modules/ms": {
+ "version": "4.0.0-nightly.202508271359",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/ms/-/ms-4.0.0-nightly.202508271359.tgz",
+ "integrity": "sha512-WC/Eo7NzFrOV/RRrTaI0fxKVbNCzEy76j2VqNV8SxDf9D69gSE2Lh0QwYvDlhiYmheBYExAvEAxVf5NoN0cj2A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/webcrypto-core": {
+ "version": "1.9.2",
+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/webcrypto-core/-/webcrypto-core-1.9.2.tgz",
+ "integrity": "sha512-gsXecm82UQNlTBURJGuqOWy1Ww08S3kZUcr3aOJS02Pk0xLtkfeUAVC0u0xhgdonFme80edSJUIJyuvL/7250Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@peculiar/asn1-schema": "^2.7.0",
+ "@peculiar/json-schema": "^1.1.12",
+ "@peculiar/utils": "^2.0.2",
+ "asn1js": "^3.0.10",
+ "tslib": "^2.8.1"
+ }
}
}
}
diff --git a/sdk/js/package.json b/sdk/js/package.json
index bdb16c85..93b4059c 100644
--- a/sdk/js/package.json
+++ b/sdk/js/package.json
@@ -29,7 +29,18 @@
"test": "node --test 'build/**/*.test.js'"
},
"dependencies": {
- "@bufbuild/protobuf": "^2.15.0"
+ "@biscuit-auth/biscuit-wasm": "^0.6.0",
+ "@bufbuild/protobuf": "^2.15.0",
+ "@chainsafe/libp2p-yamux": "^8.0.1",
+ "@libp2p/circuit-relay-v2": "^4.2.13",
+ "@libp2p/crypto": "^5.1.23",
+ "@libp2p/identify": "^4.1.14",
+ "@libp2p/interface": "^3.3.0",
+ "@libp2p/tcp": "^11.0.28",
+ "@libp2p/tls": "^3.1.10",
+ "@libp2p/utils": "^7.4.1",
+ "@multiformats/multiaddr": "^13.0.3",
+ "libp2p": "^3.3.11"
},
"devDependencies": {
"@bufbuild/protoc-gen-es": "^2.15.0",
diff --git a/sdk/js/src/auth.ts b/sdk/js/src/auth.ts
new file mode 100644
index 00000000..cb983865
--- /dev/null
+++ b/sdk/js/src/auth.ts
@@ -0,0 +1,110 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// The /sam/auth/1.0.0 handshake, both sides. One varint-length-prefixed
+// AuthFrame, one AuthResponse back; go-msgio framing on the Go side is
+// the same unsigned varint prefix lpStream uses.
+
+import { create, fromBinary, toBinary } from "@bufbuild/protobuf";
+import type { Connection, Stream, StreamHandler } from "@libp2p/interface";
+import { lpStream } from "@libp2p/utils";
+import { BiscuitVerificationError, verifyPeerBiscuit, type VerifiedBiscuit } from "./biscuit.ts";
+import { decodeAuthResponse } from "./credential.ts";
+import { AuthFrameSchema, AuthResponseSchema } from "./gen/sam_pb.ts";
+
+export const AUTH_PROTOCOL = "/sam/auth/1.0.0";
+export const MCP_PROTOCOL = "/sam/mcp/1.0.0";
+
+/** The first frame on a stream is capped, as msgio.NewVarintReaderSize(s, 64 KiB). */
+export const MAX_AUTH_FRAME_BYTES = 64 * 1024;
+/** How long either side waits for the other's frame. */
+export const AUTH_HANDSHAKE_TIMEOUT_MS = 10_000;
+
+export class AuthRejectedError extends Error {
+ constructor(peerId: string, reason: string) {
+ super(`peer ${peerId} rejected the auth handshake: ${reason}`);
+ this.name = "AuthRejectedError";
+ }
+}
+
+function framed(stream: Stream) {
+ return lpStream(stream, { maxDataLength: MAX_AUTH_FRAME_BYTES });
+}
+
+/**
+ * Client side: presents frame on a new /sam/auth/1.0.0 stream and returns
+ * the peer's verified credential. trustedKeys are the control plane keys.
+ */
+export async function authenticateWithPeer(conn: Connection, frame: Uint8Array, trustedKeys: Uint8Array[]): Promise<VerifiedBiscuit> {
+ const signal = AbortSignal.timeout(AUTH_HANDSHAKE_TIMEOUT_MS);
+ // A peer behind a router is reached over a relayed, limited connection.
+ const stream = await conn.newStream(AUTH_PROTOCOL, { signal, runOnLimitedConnection: true });
+ try {
+ const lp = framed(stream);
+ await lp.write(frame, { signal });
+ const resp = decodeAuthResponse((await lp.read({ signal })).subarray());
+ if (!resp.success) {
+ throw new AuthRejectedError(conn.remotePeer.toString(), resp.error || "no reason given");
+ }
+ if (resp.biscuit.length === 0) {
+ throw new AuthRejectedError(conn.remotePeer.toString(), "empty credential in the mutual response");
+ }
+ // Discovery names whoever answered; only this says the peer is enrolled.
+ return await verifyPeerBiscuit(resp.biscuit, conn.remotePeer.toString(), trustedKeys);
+ } finally {
+ await stream.close().catch(() => stream.abort(new Error("auth stream close failed")));
+ }
+}
+
+export interface AuthServerOptions {
+ /** This member's current biscuit, read per handshake so a refresh takes effect. */
+ ownBiscuit(): Uint8Array;
+ trustedKeys(): Uint8Array[];
+ /** Called with every peer that passes; the session keeps the admitted set. */
+ onAuthenticated?(peerId: string, verified: VerifiedBiscuit): void;
+}
+
+/** Options for libp2p.handle() so the handshake also runs over relayed connections. */
+export const AUTH_HANDLER_OPTIONS = { runOnLimitedConnection: true };
+
+/**
+ * Server side of /sam/auth/1.0.0, mirroring sam-node's HandleAuthHandshake:
+ * verify the caller's biscuit against the control plane keys and its
+ * connection peer ID, then answer with our own. A failed verification gets
+ * no answer, only a closed stream, as on the Go side.
+ */
+export function authStreamHandler(options: AuthServerOptions): StreamHandler {
+ return async (stream: Stream, connection: Connection) => {
+ const peerId = connection.remotePeer.toString();
+ const signal = AbortSignal.timeout(AUTH_HANDSHAKE_TIMEOUT_MS);
+ try {
+ const lp = framed(stream);
+ const frame = fromBinary(AuthFrameSchema, (await lp.read({ signal })).subarray());
+ let verified: VerifiedBiscuit;
+ try {
+ verified = await verifyPeerBiscuit(frame.biscuit, peerId, options.trustedKeys());
+ } catch (err) {
+ if (err instanceof BiscuitVerificationError) {
+ stream.log?.("auth handshake from %s refused: %s", peerId, err.message);
+ return;
+ }
+ throw err;
+ }
+ options.onAuthenticated?.(peerId, verified);
+ await lp.write(toBinary(AuthResponseSchema, create(AuthResponseSchema, { success: true, biscuit: options.ownBiscuit() })), { signal });
+ } finally {
+ await stream.close().catch(() => stream.abort(new Error("auth stream close failed")));
+ }
+ };
+}
diff --git a/sdk/js/src/biscuit.test.ts b/sdk/js/src/biscuit.test.ts
new file mode 100644
index 00000000..f9980d8c
--- /dev/null
+++ b/sdk/js/src/biscuit.test.ts
@@ -0,0 +1,95 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { test } from "node:test";
+import { BiscuitVerificationError, ROLE_ROUTER, loadBiscuit, requireRole, verifyPeerBiscuit } from "./biscuit.ts";
+import { ROLE_NODE } from "./controlplane.ts";
+
+interface Vector {
+ name: string;
+ biscuit: string;
+ peer_id: string;
+ trusted_keys: string[];
+ valid: boolean;
+ reason?: string;
+ expiration?: number;
+ roles?: string[];
+ has_router_role: boolean;
+}
+
+const fixture = JSON.parse(readFileSync(new URL("../../testdata/biscuit_vectors.json", import.meta.url), "utf8")) as {
+ control_plane_key: string;
+ node_token_labels: Record<string, string>;
+ vectors: Vector[];
+};
+const hex = (s: string) => new Uint8Array(Buffer.from(s, "hex"));
+const b64 = (s: string) => new Uint8Array(Buffer.from(s, "base64"));
+
+// The vectors expire in 2035; pin "now" so they stay valid for the test's lifetime.
+const NOW = new Date("2026-09-23T00:00:00Z");
+
+for (const v of fixture.vectors) {
+ test(`go-minted biscuit: ${v.name}`, async () => {
+ const trusted = v.trusted_keys.map(hex);
+ if (!v.valid) {
+ await assert.rejects(verifyPeerBiscuit(b64(v.biscuit), v.peer_id, trusted, NOW), BiscuitVerificationError);
+ return;
+ }
+ const verified = await verifyPeerBiscuit(b64(v.biscuit), v.peer_id, trusted, NOW);
+ assert.equal(verified.peerId, v.peer_id);
+ assert.equal(verified.expiration.getTime() / 1000, v.expiration);
+ assert.deepEqual(verified.roles, v.roles);
+ assert.equal(Buffer.from(verified.verifyingKey).toString("hex"), fixture.control_plane_key);
+ if (v.has_router_role) {
+ requireRole(verified, ROLE_ROUTER);
+ assert.throws(() => requireRole(verified, ROLE_NODE), BiscuitVerificationError);
+ } else {
+ requireRole(verified, ROLE_NODE);
+ assert.throws(() => requireRole(verified, ROLE_ROUTER), BiscuitVerificationError);
+ assert.deepEqual(verified.labels, fixture.node_token_labels);
+ }
+ });
+}
+
+test("a valid token is refused once the clock passes its expiration", async () => {
+ const v = fixture.vectors.find((x) => x.valid) as Vector;
+ const after = new Date((v.expiration as number) * 1000 + 1000);
+ await assert.rejects(verifyPeerBiscuit(b64(v.biscuit), v.peer_id, v.trusted_keys.map(hex), after), /expired/);
+});
+
+test("no trusted keys means nothing verifies", async () => {
+ const v = fixture.vectors.find((x) => x.valid) as Vector;
+ await assert.rejects(verifyPeerBiscuit(b64(v.biscuit), v.peer_id, [], NOW), /no trusted control plane key/);
+});
+
+test("tokens minted here verify and report their facts", async () => {
+ const wasm = await loadBiscuit();
+ const kp = new wasm.KeyPair(wasm.SignatureAlgorithm.Ed25519);
+ const builder = wasm.Biscuit.builder();
+ builder.addFact(wasm.Fact.fromString('node("12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB")'));
+ builder.addFact(wasm.Fact.fromString("expiration(2035-01-01T00:00:00Z)"));
+ builder.addFact(wasm.Fact.fromString("expiration(2034-06-01T00:00:00Z)"));
+ builder.addFact(wasm.Fact.fromString('role("sam:role:node")'));
+ builder.addFact(wasm.Fact.fromString('label("team", "plat\\"form")'));
+ const token = builder.build(kp.getPrivateKey());
+ const key = new Uint8Array(Buffer.from(kp.getPublicKey().toString().replace(/^ed25519\//, ""), "hex"));
+
+ const verified = await verifyPeerBiscuit(token.toBytes(), "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB", [key], NOW);
+ // The earliest expiration binds.
+ assert.equal(verified.expiration.toISOString(), "2034-06-01T00:00:00.000Z");
+ assert.deepEqual(verified.labels, { team: 'plat"form' });
+ assert.deepEqual(verified.roles, ["sam:role:node"]);
+});
diff --git a/sdk/js/src/biscuit.ts b/sdk/js/src/biscuit.ts
new file mode 100644
index 00000000..2ef5bd0f
--- /dev/null
+++ b/sdk/js/src/biscuit.ts
@@ -0,0 +1,180 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Verification of a peer's biscuit, mirroring internal/identity.verifyBiscuit:
+// signed by a trusted control plane key, authority block only, unexpired,
+// and bound to the peer at the other end of the connection.
+
+import { readFile } from "node:fs/promises";
+import { fileURLToPath } from "node:url";
+
+// biscuit-wasm is built for bundlers and imports its .wasm as a module,
+// which Node only does behind a flag. Instantiating it by hand avoids the
+// flag; the module's import list says what it needs.
+type BiscuitWasm = typeof import("@biscuit-auth/biscuit-wasm");
+
+let loading: Promise<BiscuitWasm> | undefined;
+
+export function loadBiscuit(): Promise<BiscuitWasm> {
+ loading ??= (async () => {
+ const dir = new URL("./", import.meta.resolve("@biscuit-auth/biscuit-wasm"));
+ const bindings = (await import(new URL("biscuit_bg.js", dir).href)) as BiscuitWasm & {
+ __wbg_set_wasm(exports: WebAssembly.Exports): void;
+ };
+ const module = await WebAssembly.compile(await readFile(fileURLToPath(new URL("biscuit_bg.wasm", dir))));
+ const imports: WebAssembly.Imports = {};
+ for (const imp of WebAssembly.Module.imports(module)) {
+ const ns = (imports[imp.module] ??= {}) as Record<string, WebAssembly.ImportValue>;
+ if (imp.module === "./biscuit_bg.js") {
+ ns[imp.name] = (bindings as unknown as Record<string, WebAssembly.ImportValue>)[imp.name] as WebAssembly.ImportValue;
+ } else if (imp.name === "performance_now") {
+ ns[imp.name] = () => performance.now();
+ } else {
+ throw new Error(`biscuit-wasm needs an unknown import ${imp.module}:${imp.name}`);
+ }
+ }
+ const instance = await WebAssembly.instantiate(module, imports);
+ bindings.__wbg_set_wasm(instance.exports);
+ // The module's start hook logs a greeting to the console.
+ const log = console.log;
+ console.log = () => {};
+ try {
+ (instance.exports as { __wbindgen_start(): void }).__wbindgen_start();
+ } finally {
+ console.log = log;
+ }
+ return bindings;
+ })();
+ return loading;
+}
+
+/** Datalog evaluation budget, as in internal/identity.AuthorizerOptions. */
+export const AUTHORIZER_LIMITS = { max_facts: 1000, max_iterations: 100, max_time_micro: 1_000_000 };
+
+export const ROLE_ROUTER = "sam:role:router";
+
+export class BiscuitVerificationError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = "BiscuitVerificationError";
+ }
+}
+
+/** What a verified peer biscuit says about its holder. */
+export interface VerifiedBiscuit {
+ /** The peer the token is bound to (its node() fact). */
+ peerId: string;
+ /** When the token lapses; the earliest expiration() fact. */
+ expiration: Date;
+ /** The trusted key that verified the signature. */
+ verifyingKey: Uint8Array;
+ roles: string[];
+ labels: Record<string, string>;
+}
+
+function describe(err: unknown): string {
+ if (err instanceof Error) {
+ return err.message;
+ }
+ try {
+ return JSON.stringify(err);
+ } catch {
+ return String(err);
+ }
+}
+
+type QueriedFact = { terms(): unknown[] };
+
+/**
+ * Verifies a biscuit received from expectedPeerId over an authenticated
+ * connection. Every trusted key is tried, so a token minted under a
+ * retiring key still verifies during rotation.
+ */
+export async function verifyPeerBiscuit(
+ biscuitBytes: Uint8Array,
+ expectedPeerId: string,
+ trustedKeys: Uint8Array[],
+ now: Date = new Date(),
+): Promise<VerifiedBiscuit> {
+ const wasm = await loadBiscuit();
+ if (trustedKeys.length === 0) {
+ throw new BiscuitVerificationError("no trusted control plane key to verify against");
+ }
+
+ let token: ReturnType<BiscuitWasm["Biscuit"]["fromBytes"]> | undefined;
+ let verifyingKey: Uint8Array | undefined;
+ let lastErr: unknown;
+ for (const key of trustedKeys) {
+ try {
+ token = wasm.Biscuit.fromBytes(biscuitBytes, wasm.PublicKey.fromBytes(key, wasm.SignatureAlgorithm.Ed25519));
+ verifyingKey = key;
+ break;
+ } catch (err) {
+ lastErr = err;
+ }
+ }
+ if (!token || !verifyingKey) {
+ throw new BiscuitVerificationError(`biscuit is not signed by a trusted control plane key: ${describe(lastErr)}`);
+ }
+
+ // Appending needs no root key, so appended blocks are the one place a
+ // holder can put Datalog of their own. SAM tokens are authority-only.
+ if (token.countBlocks() !== 1) {
+ throw new BiscuitVerificationError(`biscuit carries appended blocks; SAM tokens are authority-block only (${token.countBlocks() - 1})`);
+ }
+
+ const builder = new wasm.AuthorizerBuilder();
+ builder.addFact(wasm.Fact.fromString(`time(${now.toISOString().replace(/\.\d{3}Z$/, "Z")})`));
+ builder.addCheck(wasm.Check.fromString("check if time($t), expiration($e), $t <= $e"));
+ builder.addPolicy(wasm.Policy.fromString("allow if true"));
+ const authorizer = builder.buildAuthenticated(token);
+ try {
+ authorizer.authorizeWithLimits(AUTHORIZER_LIMITS);
+ } catch (err) {
+ throw new BiscuitVerificationError(`biscuit is expired or fails its checks: ${describe(err)}`);
+ }
+
+ const query = (rule: string) => authorizer.queryWithLimits(wasm.Rule.fromString(rule), AUTHORIZER_LIMITS) as QueriedFact[];
+ const strings = (facts: QueriedFact[]) => facts.map((f) => f.terms()[0]).filter((t): t is string => typeof t === "string");
+
+ const bound = strings(query("p($p) <- node($p)"));
+ if (!bound.includes(expectedPeerId)) {
+ throw new BiscuitVerificationError(`biscuit is not bound to peer ${expectedPeerId}`);
+ }
+
+ const expirations = query("e($e) <- expiration($e)")
+ .map((f) => f.terms()[0])
+ .filter((t): t is Date => t instanceof Date && !Number.isNaN(t.getTime()));
+ if (expirations.length === 0) {
+ throw new BiscuitVerificationError("biscuit carries no expiration fact");
+ }
+ const expiration = new Date(Math.min(...expirations.map((d) => d.getTime())));
+
+ const labels: Record<string, string> = {};
+ for (const f of query("l($k, $v) <- label($k, $v)")) {
+ const [k, v] = f.terms();
+ if (typeof k === "string" && typeof v === "string") {
+ labels[k] = v;
+ }
+ }
+
+ return { peerId: expectedPeerId, expiration, verifyingKey, roles: strings(query("r($r) <- role($r)")), labels };
+}
+
+/** Requires role(<role>) on an already verified token, as identity.RequireRole. */
+export function requireRole(verified: VerifiedBiscuit, role: string): void {
+ if (!verified.roles.includes(role)) {
+ throw new BiscuitVerificationError(`biscuit lacks expected role ${JSON.stringify(role)}`);
+ }
+}
diff --git a/sdk/js/src/conformance-join.ts b/sdk/js/src/conformance-join.ts
new file mode 100644
index 00000000..c2be17a9
--- /dev/null
+++ b/sdk/js/src/conformance-join.ts
@@ -0,0 +1,113 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Mesh member driven by tests/integration/sdk_mesh_test.go: enrolls, joins
+// the mesh through a real router, prints one JSON line describing the
+// session, then takes JSON commands on stdin, one per line, until stdin
+// closes:
+//
+// {"cmd": "auth", "addr": "<multiaddr>"} connect (through a relay when the
+// address says /p2p-circuit) and
+// run the auth handshake
+// {"cmd": "peers"} peers that authenticated to us
+// {"cmd": "quit"} leave the mesh and exit
+//
+// Each command gets one JSON line back. Same environment as conformance.ts;
+// the Python SDK ships the same runner (python -m agent_mesh.conformance_join).
+
+import { createInterface } from "node:readline";
+import { AgentMesh } from "./mesh.ts";
+import type { MeshSession } from "./session.ts";
+
+function requireEnv(name: string): string {
+ const v = process.env[name];
+ if (!v) {
+ throw new Error(`${name} is required`);
+ }
+ return v;
+}
+
+function emit(obj: unknown): void {
+ process.stdout.write(JSON.stringify(obj) + "\n");
+}
+
+async function handle(session: MeshSession, command: { cmd?: string; addr?: string }): Promise<unknown> {
+ switch (command.cmd) {
+ case "auth": {
+ try {
+ const verified = await session.authenticate(command.addr ?? "", AbortSignal.timeout(15_000));
+ return {
+ cmd: "auth",
+ ok: true,
+ peer_id: verified.peerId,
+ roles: verified.roles,
+ labels: verified.labels,
+ expiration: Math.floor(verified.expiration.getTime() / 1000),
+ };
+ } catch (err) {
+ return { cmd: "auth", ok: false, error: err instanceof Error ? `${err.name}: ${err.message}` : String(err) };
+ }
+ }
+ case "peers":
+ return { cmd: "peers", authenticated_peers: [...session.authenticatedPeers.keys()].sort() };
+ default:
+ return { cmd: command.cmd, ok: false, error: `unknown command ${JSON.stringify(command.cmd)}` };
+ }
+}
+
+async function main(): Promise<void> {
+ const controlPlaneUrl = requireEnv("SAM_CONTROL_PLANE_URL");
+ const bootstrapTokenPath = requireEnv("SAM_BOOTSTRAP_TOKEN_PATH");
+ const stateDir = requireEnv("SAM_SDK_STATE_DIR");
+ const allowInsecure = process.env.SAM_INSECURE_CONTROL_PLANE === "1";
+ const listenAddrs = (process.env.SAM_SDK_LISTEN_ADDRS ?? "").split(",").filter((a) => a !== "");
+
+ const mesh = await AgentMesh.enroll({ controlPlaneUrl, allowInsecure, stateDir, bootstrapTokenPath, pollIntervalMs: 200 });
+ const session = await mesh.join({ listenAddrs, signal: AbortSignal.timeout(20_000) });
+
+ emit({
+ sdk: "js",
+ peer_id: session.peerId,
+ routers: session.routers.map((r) => ({ peer_id: r.peerId, addr: r.addr.toString(), roles: r.credential.roles })),
+ relay_addresses: session.relayAddresses.map((ma) => ma.toString()),
+ direct_addresses: session.addresses.filter((ma) => !ma.toString().includes("/p2p-circuit")).map((ma) => ma.toString()),
+ biscuit: Buffer.from(mesh.credential.biscuit).toString("base64"),
+ });
+
+ for await (const line of createInterface({ input: process.stdin })) {
+ if (line.trim() === "") {
+ continue;
+ }
+ let command: { cmd?: string; addr?: string };
+ try {
+ command = JSON.parse(line) as { cmd?: string; addr?: string };
+ } catch (err) {
+ emit({ ok: false, error: `not JSON: ${err instanceof Error ? err.message : String(err)}` });
+ continue;
+ }
+ if (command.cmd === "quit") {
+ emit({ cmd: "quit", ok: true });
+ break;
+ }
+ emit(await handle(session, command));
+ }
+ // Leaving must not depend on every peer closing its side promptly.
+ await Promise.race([session.close(), new Promise((resolve) => setTimeout(resolve, 5_000).unref())]);
+ process.exit(0);
+}
+
+main().catch((err: unknown) => {
+ process.stderr.write(`${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);
+ process.exit(1);
+});
diff --git a/sdk/js/src/host.ts b/sdk/js/src/host.ts
new file mode 100644
index 00000000..b973da64
--- /dev/null
+++ b/sdk/js/src/host.ts
@@ -0,0 +1,60 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// The libp2p host a member joins the mesh with, configured the way
+// sam-node's is (internal/node/node.go): TLS is the only security
+// protocol, yamux the muxer, circuit relay v2 for reachability through
+// the routers.
+
+import { yamux } from "@chainsafe/libp2p-yamux";
+import { circuitRelayTransport } from "@libp2p/circuit-relay-v2";
+import { privateKeyFromProtobuf } from "@libp2p/crypto/keys";
+import { identify } from "@libp2p/identify";
+import type { Libp2p } from "@libp2p/interface";
+import { tcp } from "@libp2p/tcp";
+import { tls } from "@libp2p/tls";
+import type { Multiaddr } from "@multiformats/multiaddr";
+import { createLibp2p } from "libp2p";
+import type { Identity } from "./identity.ts";
+
+export interface MeshHostOptions {
+ /**
+ * Addresses to accept direct connections on, e.g. "/ip4/0.0.0.0/tcp/0".
+ * Empty by default: an agent is reached through a router's relay.
+ */
+ listenAddrs?: string[];
+}
+
+export async function createMeshHost(identity: Identity, options: MeshHostOptions = {}): Promise<Libp2p> {
+ return createLibp2p({
+ privateKey: privateKeyFromProtobuf(identity.toLibp2pPrivateKey()),
+ addresses: { listen: options.listenAddrs ?? [] },
+ transports: [tcp(), circuitRelayTransport()],
+ connectionEncrypters: [tls()],
+ streamMuxers: [yamux()],
+ services: { identify: identify() },
+ });
+}
+
+/**
+ * Starts listening on a relay after the caller has authenticated with it.
+ * js-libp2p reserves a relay slot when it starts listening on
+ * `<relay>/p2p-circuit`; a router refuses that until the peer has passed
+ * the auth handshake, so the listen cannot be part of the host's config.
+ * The transport manager is not on the public Libp2p interface.
+ */
+export async function listenThroughRelay(node: Libp2p, relayAddr: Multiaddr): Promise<void> {
+ const internals = node as unknown as { components: { transportManager: { listen(addrs: Multiaddr[]): Promise<void> } } };
+ await internals.components.transportManager.listen([relayAddr.encapsulate("/p2p-circuit")]);
+}
diff --git a/sdk/js/src/index.ts b/sdk/js/src/index.ts
index d66a0002..904e6d9c 100644
--- a/sdk/js/src/index.ts
+++ b/sdk/js/src/index.ts
@@ -38,3 +38,7 @@ export {
type MeshCredential,
} from "./credential.ts";
export { enrollChallenge, enrollStatusChallenge, refreshChallenge, registerChallenge } from "./challenges.ts";
+export { MeshSession, type AdmittedRouter, type JoinOptions } from "./session.ts";
+export { BiscuitVerificationError, ROLE_ROUTER, requireRole, verifyPeerBiscuit, type VerifiedBiscuit } from "./biscuit.ts";
+export { AUTH_HANDLER_OPTIONS, AUTH_PROTOCOL, MCP_PROTOCOL, AuthRejectedError, authenticateWithPeer, authStreamHandler } from "./auth.ts";
+export { createMeshHost, type MeshHostOptions } from "./host.ts";
diff --git a/sdk/js/src/mesh.ts b/sdk/js/src/mesh.ts
index c614ff47..2b7162dc 100644
--- a/sdk/js/src/mesh.ts
+++ b/sdk/js/src/mesh.ts
@@ -17,6 +17,7 @@ import { join } from "node:path";
import { ControlPlaneClient, ROLE_NODE, type Enrollment } from "./controlplane.ts";
import { credentialFromJSON, credentialToJSON, encodeAuthFrame, type MeshCredential } from "./credential.ts";
import { Identity } from "./identity.ts";
+import { joinMesh, type JoinOptions, type MeshSession } from "./session.ts";
const IDENTITY_FILE = "identity.key";
const CREDENTIAL_FILE = "credential.json";
@@ -56,10 +57,8 @@ export interface EnrollOptions extends AgentMeshOptions {
/**
* A member of the mesh: an identity, the credential the control plane minted
- * for it, and the client that keeps that credential fresh.
- *
- * This is the enrollment half of the SDK. Joining the mesh over libp2p and
- * serving or calling MCP tools build on top of it (see sdk/README.md).
+ * for it, and the client that keeps that credential fresh. join() puts it on
+ * the mesh over libp2p.
*/
export class AgentMesh {
readonly identity: Identity;
@@ -172,6 +171,15 @@ export class AgentMesh {
return encodeAuthFrame(this.#credential.biscuit, targetService, agent);
}
+ /**
+ * Joins the mesh: connects to the routers in the credential, passes the
+ * auth handshake with them, reserves a relay slot and keeps the credential
+ * fresh for as long as the session is open.
+ */
+ join(options?: JoinOptions): Promise<MeshSession> {
+ return joinMesh(this, options);
+ }
+
/** Writes identity and credential to the state directory, if one is configured. */
async save(): Promise<void> {
if (this.#stateDir === undefined) {
diff --git a/sdk/js/src/session.test.ts b/sdk/js/src/session.test.ts
new file mode 100644
index 00000000..42b537a7
--- /dev/null
+++ b/sdk/js/src/session.test.ts
@@ -0,0 +1,204 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// A mesh in one process: a fake control plane behind fetch, a fake router
+// (js-libp2p with a relay server and the auth handshake) and a peer that
+// reaches the member through the router. The real router and control
+// plane are exercised by tests/integration/sdk_join_test.go.
+
+import { create, fromBinary, toBinary } from "@bufbuild/protobuf";
+import { yamux } from "@chainsafe/libp2p-yamux";
+import { circuitRelayServer, circuitRelayTransport } from "@libp2p/circuit-relay-v2";
+import { privateKeyFromProtobuf } from "@libp2p/crypto/keys";
+import { identify } from "@libp2p/identify";
+import type { Libp2p } from "@libp2p/interface";
+import { tcp } from "@libp2p/tcp";
+import { tls } from "@libp2p/tls";
+import { multiaddr } from "@multiformats/multiaddr";
+import { createLibp2p } from "libp2p";
+import assert from "node:assert/strict";
+import { after, before, test } from "node:test";
+import { AUTH_PROTOCOL, AuthRejectedError, authenticateWithPeer, authStreamHandler } from "./auth.ts";
+import { ROLE_ROUTER, loadBiscuit, verifyPeerBiscuit } from "./biscuit.ts";
+import { ROLE_NODE } from "./controlplane.ts";
+import { BootstrapEnrollRequestSchema, BootstrapEnrollResponseSchema, EnrollmentStatus, KeysResponseSchema, AuthFrameSchema } from "./gen/sam_pb.ts";
+import { Identity } from "./identity.ts";
+import { AgentMesh } from "./mesh.ts";
+
+type Wasm = Awaited<ReturnType<typeof loadBiscuit>>;
+
+let wasm: Wasm;
+let cpKeyPair: InstanceType<Wasm["KeyPair"]>;
+let cpKey: Uint8Array;
+let router: Libp2p;
+let routerAddr: string;
+let routerBiscuit: Uint8Array;
+
+function mint(peerId: string, role: string, expiration = "2035-01-01T00:00:00Z"): Uint8Array {
+ const b = wasm.Biscuit.builder();
+ b.addFact(wasm.Fact.fromString(`node(${JSON.stringify(peerId)})`));
+ b.addFact(wasm.Fact.fromString(`expiration(${expiration})`));
+ b.addFact(wasm.Fact.fromString(`role(${JSON.stringify(role)})`));
+ return b.build(cpKeyPair.getPrivateKey()).toBytes();
+}
+
+function proto(bytes: Uint8Array): Response {
+ return new Response(Buffer.from(bytes), { status: 200, headers: { "Content-Type": "application/x-protobuf" } });
+}
+
+/** Approves every enrollment with a biscuit bound to the requesting peer. */
+function fakeControlPlane(routerAddresses: string[]): typeof fetch {
+ return (async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {
+ const req = new Request(input, init);
+ const path = new URL(req.url).pathname;
+ if (req.method === "POST" && path === "/enroll") {
+ const enroll = fromBinary(BootstrapEnrollRequestSchema, new Uint8Array(await req.arrayBuffer()));
+ return proto(
+ toBinary(
+ BootstrapEnrollResponseSchema,
+ create(BootstrapEnrollResponseSchema, {
+ status: EnrollmentStatus.APPROVED,
+ biscuitToken: mint(enroll.peerId, ROLE_NODE),
+ controlPlanePublicKey: cpKey,
+ routerAddresses,
+ expiration: BigInt(Math.floor(Date.now() / 1000) + 3600),
+ }),
+ ),
+ );
+ }
+ if (req.method === "GET" && path === "/keys") {
+ // Unsigned: the client keeps the enrollment key when /keys cannot be verified.
+ return proto(toBinary(KeysResponseSchema, create(KeysResponseSchema, { publicKeys: [cpKey], timestamp: BigInt(Date.now()) })));
+ }
+ return new Response(`no route for ${req.method} ${path}`, { status: 404 });
+ }) as typeof fetch;
+}
+
+before(async () => {
+ wasm = await loadBiscuit();
+ cpKeyPair = new wasm.KeyPair(wasm.SignatureAlgorithm.Ed25519);
+ cpKey = new Uint8Array(Buffer.from(cpKeyPair.getPublicKey().toString().replace(/^ed25519\//, ""), "hex"));
+
+ router = await createLibp2p({
+ addresses: { listen: ["/ip4/127.0.0.1/tcp/0"] },
+ transports: [tcp()],
+ connectionEncrypters: [tls()],
+ streamMuxers: [yamux()],
+ services: { identify: identify(), relay: circuitRelayServer() },
+ });
+ routerBiscuit = mint(router.peerId.toString(), ROLE_ROUTER);
+ await router.handle(
+ AUTH_PROTOCOL,
+ authStreamHandler({ ownBiscuit: () => routerBiscuit, trustedKeys: () => [cpKey] }),
+ );
+ routerAddr = `${(router.getMultiaddrs()[0] as ReturnType<typeof multiaddr>).toString()}`;
+ assert.match(routerAddr, /\/p2p\/12D3Koo/);
+});
+
+after(async () => {
+ await router.stop();
+});
+
+test("join authenticates with the router, reserves a relay slot and answers peers", async () => {
+ const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "sbt", fetch: fakeControlPlane([routerAddr]) });
+ const session = await mesh.join({ refreshLeadMs: 0 });
+ try {
+ assert.equal(session.routers.length, 1);
+ assert.equal(session.routers[0]?.peerId, router.peerId.toString());
+ assert.ok(session.routers[0]?.credential.roles.includes(ROLE_ROUTER));
+ assert.ok(session.relayAddresses.length > 0, "no relayed address after the reservation");
+ const relayed = session.relayAddresses.find((ma) => ma.toString().startsWith(routerAddr));
+ assert.ok(relayed, `relayed address ${session.relayAddresses.map(String).join(",")} does not go through ${routerAddr}`);
+
+ // A peer reaches the member through the router and both sides verify each other.
+ const peerIdentity = Identity.generate();
+ const peerBiscuit = mint(peerIdentity.peerId, ROLE_NODE);
+ const peer = await createLibp2p({
+ privateKey: privateKeyFromProtobuf(peerIdentity.toLibp2pPrivateKey()),
+ transports: [tcp(), circuitRelayTransport()],
+ connectionEncrypters: [tls()],
+ streamMuxers: [yamux()],
+ services: { identify: identify() },
+ });
+ try {
+ const conn = await peer.dial(relayed);
+ assert.equal(conn.remotePeer.toString(), mesh.peerId);
+ const frame = toBinary(AuthFrameSchema, create(AuthFrameSchema, { biscuit: peerBiscuit }));
+ const memberCredential = await authenticateWithPeer(conn, frame, [cpKey]);
+ assert.equal(memberCredential.peerId, mesh.peerId);
+ assert.deepEqual(memberCredential.roles, [ROLE_NODE]);
+ assert.equal(session.authenticatedPeers.get(peerIdentity.peerId)?.toISOString(), "2035-01-01T00:00:00.000Z");
+
+ // A forged credential gets no answer, only a closed stream.
+ const forged = new wasm.KeyPair(wasm.SignatureAlgorithm.Ed25519);
+ const fb = wasm.Biscuit.builder();
+ fb.addFact(wasm.Fact.fromString(`node(${JSON.stringify(peerIdentity.peerId)})`));
+ fb.addFact(wasm.Fact.fromString("expiration(2035-01-01T00:00:00Z)"));
+ const forgedFrame = toBinary(AuthFrameSchema, create(AuthFrameSchema, { biscuit: fb.build(forged.getPrivateKey()).toBytes() }));
+ await assert.rejects(authenticateWithPeer(conn, forgedFrame, [cpKey]));
+ } finally {
+ await peer.stop();
+ }
+ } finally {
+ await session.close();
+ }
+});
+
+test("join fails closed when the router is not a router", async () => {
+ // A relay whose credential lacks the router role must not admit us to the mesh.
+ const impostor = await createLibp2p({
+ addresses: { listen: ["/ip4/127.0.0.1/tcp/0"] },
+ transports: [tcp()],
+ connectionEncrypters: [tls()],
+ streamMuxers: [yamux()],
+ services: { identify: identify(), relay: circuitRelayServer() },
+ });
+ try {
+ const impostorBiscuit = mint(impostor.peerId.toString(), ROLE_NODE);
+ await impostor.handle(AUTH_PROTOCOL, authStreamHandler({ ownBiscuit: () => impostorBiscuit, trustedKeys: () => [cpKey] }));
+ const addr = (impostor.getMultiaddrs()[0] as ReturnType<typeof multiaddr>).toString();
+ const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "sbt", fetch: fakeControlPlane([addr]) });
+ await assert.rejects(mesh.join(), /lacks expected role "sam:role:router"/);
+ } finally {
+ await impostor.stop();
+ }
+});
+
+test("join reports a router that refuses the handshake", async () => {
+ const strict = await createLibp2p({
+ addresses: { listen: ["/ip4/127.0.0.1/tcp/0"] },
+ transports: [tcp()],
+ connectionEncrypters: [tls()],
+ streamMuxers: [yamux()],
+ services: { identify: identify() },
+ });
+ try {
+ // Trusts a different control plane, so our credential never verifies.
+ const otherKey = new wasm.KeyPair(wasm.SignatureAlgorithm.Ed25519);
+ const other = new Uint8Array(Buffer.from(otherKey.getPublicKey().toString().replace(/^ed25519\//, ""), "hex"));
+ await strict.handle(AUTH_PROTOCOL, authStreamHandler({ ownBiscuit: () => routerBiscuit, trustedKeys: () => [other] }));
+ const addr = (strict.getMultiaddrs()[0] as ReturnType<typeof multiaddr>).toString();
+ const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "sbt", fetch: fakeControlPlane([addr]) });
+ await assert.rejects(mesh.join(), /no router admitted this member/);
+ } finally {
+ await strict.stop();
+ }
+});
+
+test("an explicit rejection is reported with its reason", async () => {
+ const reason = new AuthRejectedError("12D3KooWtest", "peer is revoked");
+ assert.match(reason.message, /12D3KooWtest.*peer is revoked/);
+ // The verifier does not depend on libp2p; a token for another peer is refused before any network I/O.
+ await assert.rejects(verifyPeerBiscuit(routerBiscuit, "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB", [cpKey]), /not bound to peer/);
+});
diff --git a/sdk/js/src/session.ts b/sdk/js/src/session.ts
new file mode 100644
index 00000000..1b313316
--- /dev/null
+++ b/sdk/js/src/session.ts
@@ -0,0 +1,189 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+import type { Connection, Libp2p } from "@libp2p/interface";
+import { multiaddr, type Multiaddr } from "@multiformats/multiaddr";
+import { AUTH_HANDLER_OPTIONS, AUTH_PROTOCOL, authenticateWithPeer, authStreamHandler } from "./auth.ts";
+import { ROLE_ROUTER, requireRole, type VerifiedBiscuit } from "./biscuit.ts";
+import { createMeshHost, listenThroughRelay, type MeshHostOptions } from "./host.ts";
+import type { AgentMesh } from "./mesh.ts";
+
+export interface JoinOptions extends MeshHostOptions {
+ /**
+ * Reserve a relay slot on the first router that admits us, so peers can
+ * reach this member through the router. On by default; a member that
+ * only calls out can turn it off.
+ */
+ reserveRelay?: boolean;
+ /** Refresh the credential this long before it expires. */
+ refreshLeadMs?: number;
+ /** Retry a failed refresh after this long. */
+ refreshRetryMs?: number;
+ /** Bounds the whole join. */
+ signal?: AbortSignal;
+}
+
+export interface AdmittedRouter {
+ peerId: string;
+ addr: Multiaddr;
+ credential: VerifiedBiscuit;
+}
+
+const DEFAULT_REFRESH_LEAD_MS = 60 * 60 * 1000;
+const DEFAULT_REFRESH_RETRY_MS = 30 * 1000;
+const MIN_REFRESH_DELAY_MS = 2_000;
+
+/**
+ * A member that is on the mesh: a libp2p host authenticated with at least
+ * one router, answering the auth handshake for peers that dial it, and
+ * keeping its credential fresh. Close it to leave.
+ */
+export class MeshSession {
+ readonly mesh: AgentMesh;
+ readonly node: Libp2p;
+ readonly routers: AdmittedRouter[];
+ /** Peers that passed the inbound auth handshake, with their credential's expiration. */
+ readonly authenticatedPeers: Map<string, Date>;
+ #refreshTimer: ReturnType<typeof setTimeout> | undefined;
+ readonly #refreshLeadMs: number;
+ readonly #refreshRetryMs: number;
+ #closed = false;
+
+ constructor(mesh: AgentMesh, node: Libp2p, routers: AdmittedRouter[], authenticatedPeers: Map<string, Date>, options: JoinOptions) {
+ this.mesh = mesh;
+ this.node = node;
+ this.routers = routers;
+ this.authenticatedPeers = authenticatedPeers;
+ this.#refreshLeadMs = options.refreshLeadMs ?? DEFAULT_REFRESH_LEAD_MS;
+ this.#refreshRetryMs = options.refreshRetryMs ?? DEFAULT_REFRESH_RETRY_MS;
+ this.#scheduleRefresh();
+ }
+
+ get peerId(): string {
+ return this.node.peerId.toString();
+ }
+
+ /** Addresses peers can dial this member on, including relayed ones. */
+ get addresses(): Multiaddr[] {
+ return this.node.getMultiaddrs();
+ }
+
+ /** The `.../p2p-circuit/p2p/<self>` addresses reserved on routers. */
+ get relayAddresses(): Multiaddr[] {
+ return this.node.getMultiaddrs().filter((ma) => ma.toString().includes("/p2p-circuit"));
+ }
+
+ /**
+ * Connects to a peer by address; a `/p2p-circuit` address goes through
+ * the named relay. Returns the connection, reused if one is already open.
+ */
+ connect(addr: string | Multiaddr, signal?: AbortSignal): Promise<Connection> {
+ const ma = typeof addr === "string" ? multiaddr(addr) : addr;
+ return this.node.dial(ma, signal !== undefined ? { signal } : {});
+ }
+
+ /** Connects to a peer and runs the mutual auth handshake, returning its verified credential. */
+ async authenticate(addr: string | Multiaddr, signal?: AbortSignal): Promise<VerifiedBiscuit> {
+ const conn = await this.connect(addr, signal);
+ return authenticateWithPeer(conn, this.mesh.authFrame(), this.mesh.credential.controlPlaneKeys);
+ }
+
+ /** Refreshes now and reschedules; exposed so a caller can force it. */
+ async refresh(): Promise<void> {
+ await this.mesh.refresh();
+ this.#scheduleRefresh();
+ }
+
+ #scheduleRefresh(): void {
+ if (this.#closed) {
+ return;
+ }
+ clearTimeout(this.#refreshTimer);
+ const dueMs = this.mesh.credential.expiration * 1000 - this.#refreshLeadMs - Date.now();
+ const delay = Math.max(MIN_REFRESH_DELAY_MS, dueMs);
+ this.#refreshTimer = setTimeout(() => {
+ this.mesh.refresh().then(
+ () => this.#scheduleRefresh(),
+ () => {
+ if (!this.#closed) {
+ this.#refreshTimer = setTimeout(() => this.#scheduleRefresh(), this.#refreshRetryMs);
+ this.#refreshTimer.unref?.();
+ }
+ },
+ );
+ }, delay);
+ // A pending refresh must not keep an otherwise finished process alive.
+ this.#refreshTimer.unref?.();
+ }
+
+ async close(): Promise<void> {
+ this.#closed = true;
+ clearTimeout(this.#refreshTimer);
+ await this.node.stop();
+ }
+}
+
+/** Implements AgentMesh.join(); lives here to keep mesh.ts free of libp2p. */
+export async function joinMesh(mesh: AgentMesh, options: JoinOptions = {}): Promise<MeshSession> {
+ const routerAddrs = mesh.credential.routerAddresses.map((a) => multiaddr(a));
+ if (routerAddrs.length === 0) {
+ throw new Error("credential lists no router addresses; the control plane had no active router at enrollment");
+ }
+
+ const node = await createMeshHost(mesh.identity, options);
+ const admitted: AdmittedRouter[] = [];
+ const authenticatedPeers = new Map<string, Date>();
+ try {
+ await node.handle(
+ AUTH_PROTOCOL,
+ authStreamHandler({
+ ownBiscuit: () => mesh.credential.biscuit,
+ trustedKeys: () => mesh.credential.controlPlaneKeys,
+ onAuthenticated: (peerId, verified) => authenticatedPeers.set(peerId, verified.expiration),
+ }),
+ AUTH_HANDLER_OPTIONS,
+ );
+
+ const failures: string[] = [];
+ for (const addr of routerAddrs) {
+ const routerPeer = addr.getComponents().findLast((c) => c.name === "p2p")?.value;
+ if (routerPeer === undefined) {
+ failures.push(`${addr.toString()}: no /p2p/<peer id> component`);
+ continue;
+ }
+ try {
+ const conn = await node.dial(addr, options.signal !== undefined ? { signal: options.signal } : {});
+ const credential = await authenticateWithPeer(conn, mesh.authFrame(), mesh.credential.controlPlaneKeys);
+ // Enforced under the key that verified the token; a relay that is
+ // not a router must not become our way onto the mesh.
+ requireRole(credential, ROLE_ROUTER);
+ admitted.push({ peerId: routerPeer, addr, credential });
+ } catch (err) {
+ failures.push(`${addr.toString()}: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }
+ if (admitted.length === 0) {
+ throw new Error(`no router admitted this member:\n ${failures.join("\n ")}`);
+ }
+
+ if (options.reserveRelay ?? true) {
+ await listenThroughRelay(node, (admitted[0] as AdmittedRouter).addr);
+ }
+ } catch (err) {
+ await Promise.resolve(node.stop()).catch(() => {});
+ throw err;
+ }
+
+ return new MeshSession(mesh, node, admitted, authenticatedPeers, options);
+}
diff --git a/sdk/js/tsconfig.json b/sdk/js/tsconfig.json
index 70811de8..6169c834 100644
--- a/sdk/js/tsconfig.json
+++ b/sdk/js/tsconfig.json
@@ -1,9 +1,9 @@
{
"compilerOptions": {
- "target": "es2022",
+ "target": "es2023",
"module": "nodenext",
"moduleResolution": "nodenext",
- "lib": ["es2022"],
+ "lib": ["es2023", "dom"],
"types": ["node"],
"strict": true,
"noUncheckedIndexedAccess": true,
diff --git a/sdk/python/README.md b/sdk/python/README.md
index b853843e..be28157b 100644
--- a/sdk/python/README.md
+++ b/sdk/python/README.md
@@ -4,9 +4,9 @@ Native Python SDK for joining a SAM agent mesh from inside the agent
process. It replaces the `sam-node` sidecar for agents written in Python.
Import it as `agent_mesh`.
-Status: **milestone 1** (identity, enrollment, credential refresh). The
-libp2p transport, service discovery and MCP over the mesh are the next
-milestones; see [../README.md](../README.md) for the plan.
+Status: **milestone 2** (identity, enrollment, credential refresh, joining
+the mesh over libp2p with mutual authentication). Discovering and calling
+tools are the next milestones; see [../README.md](../README.md) for the plan.
## Install
@@ -14,11 +14,13 @@ milestones; see [../README.md](../README.md) for the plan.
pip install -e 'sdk/python[test]'
```
-Runtime dependencies are `cryptography` (ed25519) and `protobuf`.
+Runtime dependencies are `cryptography`, `protobuf`, `biscuit-python`,
+`libp2p` (py-libp2p 0.7, trio-based) and `multiaddr`. Python 3.11 or later.
## Use
```python
+import trio
from agent_mesh import AgentMesh
mesh = AgentMesh.enroll(
@@ -27,14 +29,27 @@ mesh = AgentMesh.enroll(
state_dir="~/.config/sam-mesh/agent",
)
print(mesh.peer_id) # 12D3Koo...
-print(mesh.credential.time_to_live_seconds())
-mesh.refresh() # trades the biscuit for a fresh one
+
+
+async def main():
+ # On the mesh: authenticated with a router, reachable through it,
+ # credential kept fresh for as long as the block is open.
+ async with mesh.join() as session:
+ print(session.relay_addresses)
+ # Reach another member (directly or through a router) and verify it.
+ peer = await session.authenticate("/ip4/.../p2p/<router>/p2p-circuit/p2p/<peer>")
+ print(peer.roles, peer.labels, peer.expiration)
+
+
+trio.run(main)
# Later, in a new process:
mesh = AgentMesh.load("~/.config/sam-mesh/agent")
-frame = mesh.auth_frame("mcp://calculator") # first frame on a mesh stream
```
+py-libp2p runs on trio, so `join()` is a trio async context manager; under
+asyncio use it through `anyio` with the trio backend.
+
`enroll` takes exactly one of `bootstrap_token_path`, `bootstrap_token` or
`jwt`. Read tokens from a file or the environment; do not put them on a
command line.
@@ -51,14 +66,21 @@ A plaintext `http://` control plane is accepted only on loopback. Pass
- `agent_mesh.credential`: what a member holds, `AuthFrame` encoding.
- `agent_mesh.mesh`: `AgentMesh`, persistence under a state directory
(`identity.key` in the libp2p private key encoding, `credential.json`).
-- `agent_mesh._proto`: generated from `api/sam.proto` by
- `hack/gen-sdk-proto.sh`.
+- `agent_mesh.biscuit`: verification of a peer's credential with
+ biscuit-python, as `internal/identity.verifyBiscuit` does.
+- `agent_mesh.host`, `agent_mesh.auth`, `agent_mesh.relay`,
+ `agent_mesh.session`: the libp2p host, the `/sam/auth/1.0.0` handshake on
+ both sides, the circuit relay v2 client (reservation, dial, accept) and
+ `MeshSession` with the refresh loop.
+- `agent_mesh._proto`: generated from `api/sam.proto` and
+ `sdk/python/proto/circuit.proto` by `hack/gen-sdk-proto.sh`.
## Test
```bash
-pytest sdk/python/tests # unit tests, fake control plane
-go test ./tests/integration -run TestNativeSDKs # against a real control plane
+pytest sdk/python/tests # unit tests, fake control plane and router
+go test ./tests/integration -run TestNativeSDKs # real control plane, router and sam-node
```
-The integration test skips unless `agent_mesh` imports in `python3`.
+The integration tests skip unless `agent_mesh` imports in
+`sdk/python/.venv/bin/python` or `python3`.
diff --git a/sdk/python/proto/circuit.proto b/sdk/python/proto/circuit.proto
new file mode 100644
index 00000000..d635d311
--- /dev/null
+++ b/sdk/python/proto/circuit.proto
@@ -0,0 +1,77 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// The libp2p circuit relay v2 wire format, copied from go-libp2p
+// (p2p/protocol/circuitv2/pb/circuit.proto) so a client that only needs a
+// reservation can speak to a router without depending on a relay client
+// implementation. Messages travel varint-length-prefixed on the
+// /libp2p/circuit/relay/0.2.0/hop stream.
+
+syntax = "proto3";
+
+package circuit.pb;
+
+message HopMessage {
+ enum Type {
+ RESERVE = 0;
+ CONNECT = 1;
+ STATUS = 2;
+ }
+
+ optional Type type = 1;
+ optional Peer peer = 2;
+ optional Reservation reservation = 3;
+ optional Limit limit = 4;
+ optional Status status = 5;
+}
+
+message StopMessage {
+ enum Type {
+ CONNECT = 0;
+ STATUS = 1;
+ }
+
+ optional Type type = 1;
+ optional Peer peer = 2;
+ optional Limit limit = 3;
+ optional Status status = 4;
+}
+
+message Peer {
+ optional bytes id = 1;
+ repeated bytes addrs = 2;
+}
+
+message Reservation {
+ optional uint64 expire = 1; // Unix expiration time (UTC)
+ repeated bytes addrs = 2; // relay addrs for reserving peer
+ optional bytes voucher = 3; // reservation voucher
+}
+
+message Limit {
+ optional uint32 duration = 1; // seconds
+ optional uint64 data = 2; // bytes
+}
+
+enum Status {
+ UNUSED = 0;
+ OK = 100;
+ RESERVATION_REFUSED = 200;
+ RESOURCE_LIMIT_EXCEEDED = 201;
+ PERMISSION_DENIED = 202;
+ CONNECTION_FAILED = 203;
+ NO_RESERVATION = 204;
+ MALFORMED_MESSAGE = 400;
+ UNEXPECTED_MESSAGE = 401;
+}
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml
index dd906665..757a710f 100644
--- a/sdk/python/pyproject.toml
+++ b/sdk/python/pyproject.toml
@@ -8,11 +8,15 @@ version = "0.1.0"
description = "Native SDK for joining a SAM agent mesh from inside a Python agent process"
readme = "README.md"
license = "Apache-2.0"
-requires-python = ">=3.10"
+requires-python = ">=3.11"
dependencies = [
+ "biscuit-python>=0.4",
"cryptography>=42",
- # py-libp2p (the next milestone) requires protobuf<7; stay co-installable.
+ "libp2p>=0.7,<0.8",
+ "multiaddr>=0.2",
+ # py-libp2p requires protobuf<7; stay co-installable.
"protobuf>=4.25,<7",
+ "trio>=0.26",
]
[project.optional-dependencies]
diff --git a/sdk/python/src/agent_mesh/__init__.py b/sdk/python/src/agent_mesh/__init__.py
index cfb10ebf..b5b1f466 100644
--- a/sdk/python/src/agent_mesh/__init__.py
+++ b/sdk/python/src/agent_mesh/__init__.py
@@ -14,6 +14,8 @@
"""Native SDK for joining a SAM agent mesh from inside a Python process."""
+from .auth import AUTH_PROTOCOL, MCP_PROTOCOL, AuthRejectedError, auth_stream_handler, authenticate_with_peer
+from .biscuit import ROLE_ROUTER, BiscuitVerificationError, VerifiedBiscuit, require_role, verify_peer_biscuit
from .challenges import enroll_challenge, enroll_status_challenge, refresh_challenge, register_challenge
from .controlplane import (
ROLE_NODE,
@@ -29,21 +31,34 @@ from .controlplane import (
from .credential import MeshCredential, decode_auth_response, encode_auth_frame
from .identity import Identity, libp2p_public_key, peer_id_from_public_key, verify_ed25519
from .mesh import AgentMesh
+from .relay import dial_through_relay, reserve_relay
+from .session import AdmittedRouter, MeshSession
__version__ = "0.1.0"
__all__ = [
+ "AUTH_PROTOCOL",
+ "AdmittedRouter",
"AgentMesh",
+ "AuthRejectedError",
+ "BiscuitVerificationError",
"ControlPlaneClient",
"ControlPlaneError",
"Enrollment",
"EnrollmentRejectedError",
"Identity",
"InsecureControlPlaneURLError",
+ "MCP_PROTOCOL",
"MeshCredential",
+ "MeshSession",
"ROLE_NODE",
+ "ROLE_ROUTER",
"RefreshResult",
+ "VerifiedBiscuit",
+ "auth_stream_handler",
+ "authenticate_with_peer",
"decode_auth_response",
+ "dial_through_relay",
"encode_auth_frame",
"enroll_challenge",
"enroll_status_challenge",
@@ -51,7 +66,10 @@ __all__ = [
"peer_id_from_public_key",
"refresh_challenge",
"register_challenge",
+ "require_role",
+ "reserve_relay",
"validate_control_plane_url",
"verify_ed25519",
"verify_keys_response",
+ "verify_peer_biscuit",
]
diff --git a/sdk/python/src/agent_mesh/_proto/circuit_pb2.py b/sdk/python/src/agent_mesh/_proto/circuit_pb2.py
new file mode 100644
index 00000000..af6afb64
--- /dev/null
+++ b/sdk/python/src/agent_mesh/_proto/circuit_pb2.py
@@ -0,0 +1,39 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: circuit.proto
+"""Generated protocol buffer code."""
+from google.protobuf.internal import builder as _builder
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\rcircuit.proto\x12\ncircuit.pb\"\xc9\x02\n\nHopMessage\x12.\n\x04type\x18\x01 \x01(\x0e\x32\x1b.circuit.pb.HopMessage.TypeH\x00\x88\x01\x01\x12#\n\x04peer\x18\x02 \x01(\x0b\x32\x10.circuit.pb.PeerH\x01\x88\x01\x01\x12\x31\n\x0breservation\x18\x03 \x01(\x0b\x32\x17.circuit.pb.ReservationH\x02\x88\x01\x01\x12%\n\x05limit\x18\x04 \x01(\x0b\x32\x11.circuit.pb.LimitH\x03\x88\x01\x01\x12\'\n\x06status\x18\x05 \x01(\x0e\x32\x12.circuit.pb.StatusH\x04\x88\x01\x01\",\n\x04Type\x12\x0b\n\x07RESERVE\x10\x00\x12\x0b\n\x07\x43ONNECT\x10\x01\x12\n\n\x06STATUS\x10\x02\x42\x07\n\x05_typeB\x07\n\x05_peerB\x0e\n\x0c_reservationB\x08\n\x06_limitB\t\n\x07_status\"\xfb\x01\n\x0bStopMessage\x12/\n\x04type\x18\x01 \x01(\x0e\x32\x1c.circuit.pb.StopMessage.TypeH\x00\x88\x01\x01\x12#\n\x04peer\x18\x02 \x01(\x0b\x32\x10.circuit.pb.PeerH\x01\x88\x01\x01\x12%\n\x05limit\x18\x03 \x01(\x0b\x32\x11.circuit.pb.LimitH\x02\x88\x01\x01\x12\'\n\x06status\x18\x04 \x01(\x0e\x32\x12.circuit.pb.StatusH\x03\x88\x01\x01\"\x1f\n\x04Type\x12\x0b\n\x07\x43ONNECT\x10\x00\x12\n\n\x06STATUS\x10\x01\x42\x07\n\x05_typeB\x07\n\x05_peerB\x08\n\x06_limitB\t\n\x07_status\"-\n\x04Peer\x12\x0f\n\x02id\x18\x01 \x01(\x0cH\x00\x88\x01\x01\x12\r\n\x05\x61\x64\x64rs\x18\x02 \x03(\x0c\x42\x05\n\x03_id\"^\n\x0bReservation\x12\x13\n\x06\x65xpire\x18\x01 \x01(\x04H\x00\x88\x01\x01\x12\r\n\x05\x61\x64\x64rs\x18\x02 \x03(\x0c\x12\x14\n\x07voucher\x18\x03 \x01(\x0cH\x01\x88\x01\x01\x42\t\n\x07_expireB\n\n\x08_voucher\"G\n\x05Limit\x12\x15\n\x08\x64uration\x18\x01 \x01(\rH\x00\x88\x01\x01\x12\x11\n\x04\x64\x61ta\x18\x02 \x01(\x04H\x01\x88\x01\x01\x42\x0b\n\t_durationB\x07\n\x05_data*\xca\x01\n\x06Status\x12\n\n\x06UNUSED\x10\x00\x12\x06\n\x02OK\x10\x64\x12\x18\n\x13RESERVATION_REFUSED\x10\xc8\x01\x12\x1c\n\x17RESOURCE_LIMIT_EXCEEDED\x10\xc9\x01\x12\x16\n\x11PERMISSION_DENIED\x10\xca\x01\x12\x16\n\x11\x43ONNECTION_FAILED\x10\xcb\x01\x12\x13\n\x0eNO_RESERVATION\x10\xcc\x01\x12\x16\n\x11MALFORMED_MESSAGE\x10\x90\x03\x12\x17\n\x12UNEXPECTED_MESSAGE\x10\x91\x03\x62\x06proto3')
+
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'circuit_pb2', globals())
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+ DESCRIPTOR._options = None
+ _STATUS._serialized_start=832
+ _STATUS._serialized_end=1034
+ _HOPMESSAGE._serialized_start=30
+ _HOPMESSAGE._serialized_end=359
+ _HOPMESSAGE_TYPE._serialized_start=260
+ _HOPMESSAGE_TYPE._serialized_end=304
+ _STOPMESSAGE._serialized_start=362
+ _STOPMESSAGE._serialized_end=613
+ _STOPMESSAGE_TYPE._serialized_start=543
+ _STOPMESSAGE_TYPE._serialized_end=574
+ _PEER._serialized_start=615
+ _PEER._serialized_end=660
+ _RESERVATION._serialized_start=662
+ _RESERVATION._serialized_end=756
+ _LIMIT._serialized_start=758
+ _LIMIT._serialized_end=829
+# @@protoc_insertion_point(module_scope)
diff --git a/sdk/python/src/agent_mesh/_proto/circuit_pb2.pyi b/sdk/python/src/agent_mesh/_proto/circuit_pb2.pyi
new file mode 100644
index 00000000..5e0675f7
--- /dev/null
+++ b/sdk/python/src/agent_mesh/_proto/circuit_pb2.pyi
@@ -0,0 +1,80 @@
+from google.protobuf.internal import containers as _containers
+from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import message as _message
+from typing import ClassVar as _ClassVar, Iterable as _Iterable, Mapping as _Mapping, Optional as _Optional, Union as _Union
+
+CONNECTION_FAILED: Status
+DESCRIPTOR: _descriptor.FileDescriptor
+MALFORMED_MESSAGE: Status
+NO_RESERVATION: Status
+OK: Status
+PERMISSION_DENIED: Status
+RESERVATION_REFUSED: Status
+RESOURCE_LIMIT_EXCEEDED: Status
+UNEXPECTED_MESSAGE: Status
+UNUSED: Status
+
+class HopMessage(_message.Message):
+ __slots__ = ["limit", "peer", "reservation", "status", "type"]
+ class Type(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
+ __slots__ = []
+ CONNECT: HopMessage.Type
+ LIMIT_FIELD_NUMBER: _ClassVar[int]
+ PEER_FIELD_NUMBER: _ClassVar[int]
+ RESERVATION_FIELD_NUMBER: _ClassVar[int]
+ RESERVE: HopMessage.Type
+ STATUS: HopMessage.Type
+ STATUS_FIELD_NUMBER: _ClassVar[int]
+ TYPE_FIELD_NUMBER: _ClassVar[int]
+ limit: Limit
+ peer: Peer
+ reservation: Reservation
+ status: Status
+ type: HopMessage.Type
+ def __init__(self, type: _Optional[_Union[HopMessage.Type, str]] = ..., peer: _Optional[_Union[Peer, _Mapping]] = ..., reservation: _Optional[_Union[Reservation, _Mapping]] = ..., limit: _Optional[_Union[Limit, _Mapping]] = ..., status: _Optional[_Union[Status, str]] = ...) -> None: ...
+
+class Limit(_message.Message):
+ __slots__ = ["data", "duration"]
+ DATA_FIELD_NUMBER: _ClassVar[int]
+ DURATION_FIELD_NUMBER: _ClassVar[int]
+ data: int
+ duration: int
+ def __init__(self, duration: _Optional[int] = ..., data: _Optional[int] = ...) -> None: ...
+
+class Peer(_message.Message):
+ __slots__ = ["addrs", "id"]
+ ADDRS_FIELD_NUMBER: _ClassVar[int]
+ ID_FIELD_NUMBER: _ClassVar[int]
+ addrs: _containers.RepeatedScalarFieldContainer[bytes]
+ id: bytes
+ def __init__(self, id: _Optional[bytes] = ..., addrs: _Optional[_Iterable[bytes]] = ...) -> None: ...
+
+class Reservation(_message.Message):
+ __slots__ = ["addrs", "expire", "voucher"]
+ ADDRS_FIELD_NUMBER: _ClassVar[int]
+ EXPIRE_FIELD_NUMBER: _ClassVar[int]
+ VOUCHER_FIELD_NUMBER: _ClassVar[int]
+ addrs: _containers.RepeatedScalarFieldContainer[bytes]
+ expire: int
+ voucher: bytes
+ def __init__(self, expire: _Optional[int] = ..., addrs: _Optional[_Iterable[bytes]] = ..., voucher: _Optional[bytes] = ...) -> None: ...
+
+class StopMessage(_message.Message):
+ __slots__ = ["limit", "peer", "status", "type"]
+ class Type(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
+ __slots__ = []
+ CONNECT: StopMessage.Type
+ LIMIT_FIELD_NUMBER: _ClassVar[int]
+ PEER_FIELD_NUMBER: _ClassVar[int]
+ STATUS: StopMessage.Type
+ STATUS_FIELD_NUMBER: _ClassVar[int]
+ TYPE_FIELD_NUMBER: _ClassVar[int]
+ limit: Limit
+ peer: Peer
+ status: Status
+ type: StopMessage.Type
+ def __init__(self, type: _Optional[_Union[StopMessage.Type, str]] = ..., peer: _Optional[_Union[Peer, _Mapping]] = ..., limit: _Optional[_Union[Limit, _Mapping]] = ..., status: _Optional[_Union[Status, str]] = ...) -> None: ...
+
+class Status(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
+ __slots__ = []
diff --git a/sdk/python/src/agent_mesh/auth.py b/sdk/python/src/agent_mesh/auth.py
new file mode 100644
index 00000000..4c832c28
--- /dev/null
+++ b/sdk/python/src/agent_mesh/auth.py
@@ -0,0 +1,106 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""The /sam/auth/1.0.0 handshake, both sides. Frames are varint-length-prefixed
+protobufs, go-msgio style."""
+
+from __future__ import annotations
+
+import logging
+from typing import Callable, Optional, Sequence
+
+import trio
+from libp2p.abc import IHost, INetStream
+from libp2p.custom_types import TProtocol
+from libp2p.peer.id import ID
+from libp2p.utils.varint import encode_varint_prefixed, read_varint_prefixed_bytes
+
+from ._proto import sam_pb2 as pb
+from .biscuit import BiscuitVerificationError, VerifiedBiscuit, verify_peer_biscuit
+
+logger = logging.getLogger("agent_mesh")
+
+AUTH_PROTOCOL = TProtocol("/sam/auth/1.0.0")
+MCP_PROTOCOL = TProtocol("/sam/mcp/1.0.0")
+
+# The first frame on a stream is capped, as msgio.NewVarintReaderSize(s, 64 KiB).
+MAX_AUTH_FRAME_BYTES = 64 * 1024
+# How long either side waits for the other's frame.
+AUTH_HANDSHAKE_TIMEOUT = 10.0
+
+
+class AuthRejectedError(Exception):
+ def __init__(self, peer_id: str, reason: str):
+ super().__init__(f"peer {peer_id} rejected the auth handshake: {reason}")
+ self.peer_id = peer_id
+ self.reason = reason
+
+
+async def _read_frame(stream: INetStream) -> bytes:
+ data = await read_varint_prefixed_bytes(stream)
+ if len(data) > MAX_AUTH_FRAME_BYTES:
+ raise ValueError(f"frame of {len(data)} bytes exceeds the {MAX_AUTH_FRAME_BYTES} byte cap")
+ return data
+
+
+async def authenticate_with_peer(host: IHost, peer_id: ID, frame: bytes, trusted_keys: Sequence[bytes]) -> VerifiedBiscuit:
+ """Client side: presents `frame` on a new /sam/auth/1.0.0 stream to a
+ connected peer and returns the peer's verified credential."""
+ stream = await host.new_stream(peer_id, [AUTH_PROTOCOL])
+ try:
+ with trio.fail_after(AUTH_HANDSHAKE_TIMEOUT):
+ await stream.write(encode_varint_prefixed(frame))
+ resp = pb.AuthResponse.FromString(await _read_frame(stream))
+ if not resp.success:
+ raise AuthRejectedError(str(peer_id), resp.error or "no reason given")
+ if not resp.biscuit:
+ raise AuthRejectedError(str(peer_id), "empty credential in the mutual response")
+ # Discovery names whoever answered; only this says the peer is enrolled.
+ return verify_peer_biscuit(resp.biscuit, str(peer_id), trusted_keys)
+ except trio.TooSlowError as err:
+ raise AuthRejectedError(str(peer_id), "handshake timed out") from err
+ finally:
+ await stream.close()
+
+
+def auth_stream_handler(
+ own_biscuit: Callable[[], bytes],
+ trusted_keys: Callable[[], Sequence[bytes]],
+ on_authenticated: Optional[Callable[[str, VerifiedBiscuit], None]] = None,
+) -> Callable[[INetStream], "trio.lowlevel.Awaitable[None]"]:
+ """Server side of /sam/auth/1.0.0, mirroring sam-node's HandleAuthHandshake:
+ verify the caller's biscuit against the control plane keys and its
+ connection peer ID, then answer with our own. A failed verification gets no
+ answer, only a closed stream, as on the Go side."""
+
+ async def handle(stream: INetStream) -> None:
+ peer_id = str(stream.muxed_conn.peer_id)
+ try:
+ with trio.fail_after(AUTH_HANDSHAKE_TIMEOUT):
+ frame = pb.AuthFrame.FromString(await _read_frame(stream))
+ try:
+ verified = verify_peer_biscuit(frame.biscuit, peer_id, trusted_keys())
+ except BiscuitVerificationError as err:
+ logger.warning("auth handshake from %s refused: %s", peer_id, err)
+ return
+ if on_authenticated is not None:
+ on_authenticated(peer_id, verified)
+ resp = pb.AuthResponse(success=True, biscuit=own_biscuit())
+ await stream.write(encode_varint_prefixed(resp.SerializeToString()))
+ except (trio.TooSlowError, ValueError) as err:
+ logger.warning("auth handshake from %s failed: %s", peer_id, err)
+ finally:
+ await stream.close()
+
+ return handle
diff --git a/sdk/python/src/agent_mesh/biscuit.py b/sdk/python/src/agent_mesh/biscuit.py
new file mode 100644
index 00000000..62258058
--- /dev/null
+++ b/sdk/python/src/agent_mesh/biscuit.py
@@ -0,0 +1,135 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Verification of a peer's biscuit, mirroring internal/identity.verifyBiscuit:
+signed by a trusted control plane key, authority block only, unexpired, and
+bound to the peer at the other end of the connection."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta, timezone
+from typing import Optional, Sequence
+
+import biscuit_auth as ba
+
+ROLE_ROUTER = "sam:role:router"
+
+# Datalog evaluation budget, as in internal/identity.AuthorizerOptions.
+AUTHORIZER_MAX_FACTS = 1000
+AUTHORIZER_MAX_ITERATIONS = 100
+AUTHORIZER_MAX_TIME = timedelta(seconds=1)
+
+_EXPIRATION_CHECK = "check if time($t), expiration($e), $t <= $e"
+
+
+class BiscuitVerificationError(Exception):
+ pass
+
+
+@dataclass(frozen=True)
+class VerifiedBiscuit:
+ """What a verified peer biscuit says about its holder."""
+
+ # The peer the token is bound to (its node() fact).
+ peer_id: str
+ # When the token lapses; the earliest expiration() fact.
+ expiration: datetime
+ # The trusted key that verified the signature.
+ verifying_key: bytes
+ roles: list[str] = field(default_factory=list)
+ labels: dict[str, str] = field(default_factory=dict)
+
+
+def _limits() -> ba.AuthorizerLimits:
+ limits = ba.AuthorizerBuilder().limits()
+ limits.max_facts = AUTHORIZER_MAX_FACTS
+ limits.max_iterations = AUTHORIZER_MAX_ITERATIONS
+ limits.max_time = AUTHORIZER_MAX_TIME
+ return limits
+
+
+def verify_peer_biscuit(
+ biscuit: bytes,
+ expected_peer_id: str,
+ trusted_keys: Sequence[bytes],
+ now: Optional[datetime] = None,
+) -> VerifiedBiscuit:
+ """Verifies a biscuit received from expected_peer_id over an authenticated
+ connection. Every trusted key is tried, so a token minted under a retiring
+ key still verifies during rotation."""
+ if not trusted_keys:
+ raise BiscuitVerificationError("no trusted control plane key to verify against")
+ now = now or datetime.now(timezone.utc)
+
+ token = None
+ verifying_key = b""
+ last_err: Exception | None = None
+ for key in trusted_keys:
+ try:
+ token = ba.Biscuit.from_bytes(biscuit, ba.PublicKey.from_bytes(bytes(key), ba.Algorithm.Ed25519))
+ verifying_key = bytes(key)
+ break
+ except Exception as err: # noqa: BLE001 - biscuit-python raises several types here
+ last_err = err
+ if token is None:
+ raise BiscuitVerificationError(f"biscuit is not signed by a trusted control plane key: {last_err}")
+
+ # Appending needs no root key, so appended blocks are the one place a
+ # holder can put Datalog of their own. SAM tokens are authority-only.
+ if token.block_count() != 1:
+ raise BiscuitVerificationError(
+ f"biscuit carries appended blocks; SAM tokens are authority-block only ({token.block_count() - 1})"
+ )
+
+ builder = ba.AuthorizerBuilder()
+ builder.set_limits(_limits())
+ builder.add_fact(ba.Fact("time({now})", {"now": now}))
+ builder.add_check(ba.Check(_EXPIRATION_CHECK))
+ builder.add_policy(ba.Policy("allow if true"))
+ authorizer = builder.build(token)
+ try:
+ authorizer.authorize()
+ except Exception as err: # noqa: BLE001
+ raise BiscuitVerificationError(f"biscuit is expired or fails its checks: {err}") from err
+
+ def strings(rule: str) -> list[str]:
+ return [f.terms[0] for f in authorizer.query(ba.Rule(rule)) if isinstance(f.terms[0], str)]
+
+ if expected_peer_id not in strings("p($p) <- node($p)"):
+ raise BiscuitVerificationError(f"biscuit is not bound to peer {expected_peer_id}")
+
+ expirations = [f.terms[0] for f in authorizer.query(ba.Rule("e($e) <- expiration($e)")) if isinstance(f.terms[0], datetime)]
+ if not expirations:
+ raise BiscuitVerificationError("biscuit carries no expiration fact")
+
+ labels = {
+ f.terms[0]: f.terms[1]
+ for f in authorizer.query(ba.Rule("l($k, $v) <- label($k, $v)"))
+ if isinstance(f.terms[0], str) and isinstance(f.terms[1], str)
+ }
+
+ return VerifiedBiscuit(
+ peer_id=expected_peer_id,
+ expiration=min(expirations),
+ verifying_key=verifying_key,
+ roles=strings("r($r) <- role($r)"),
+ labels=labels,
+ )
+
+
+def require_role(verified: VerifiedBiscuit, role: str) -> None:
+ """Requires role(<role>) on an already verified token, as identity.RequireRole."""
+ if role not in verified.roles:
+ raise BiscuitVerificationError(f"biscuit lacks expected role {role!r}")
diff --git a/sdk/python/src/agent_mesh/conformance_join.py b/sdk/python/src/agent_mesh/conformance_join.py
new file mode 100644
index 00000000..bddbce2e
--- /dev/null
+++ b/sdk/python/src/agent_mesh/conformance_join.py
@@ -0,0 +1,118 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Mesh member driven by tests/integration/sdk_mesh_test.go: enrolls, joins
+the mesh through a real router, prints one JSON line describing the session,
+then takes JSON commands on stdin, one per line, until stdin closes:
+
+ {"cmd": "auth", "addr": "<multiaddr>"} connect (through a relay when the
+ address says /p2p-circuit) and run
+ the auth handshake
+ {"cmd": "peers"} peers that authenticated to us
+ {"cmd": "quit"} leave the mesh and exit
+
+Each command gets one JSON line back. Same environment as conformance.py; the
+JavaScript SDK ships the same runner (dist/conformance-join.js).
+"""
+
+import base64
+import json
+import logging
+import os
+import sys
+
+import trio
+
+from .mesh import AgentMesh
+from .session import MeshSession
+
+
+def _require_env(name: str) -> str:
+ value = os.environ.get(name)
+ if not value:
+ raise SystemExit(f"{name} is required")
+ return value
+
+
+def _emit(obj: dict) -> None:
+ print(json.dumps(obj), flush=True)
+
+
+async def _handle(session: MeshSession, command: dict) -> dict:
+ cmd = command.get("cmd")
+ if cmd == "auth":
+ try:
+ verified = await session.authenticate(command["addr"])
+ except Exception as err: # noqa: BLE001 - the driver wants the failure, not a dead runner
+ return {"cmd": cmd, "ok": False, "error": f"{type(err).__name__}: {err}"}
+ return {
+ "cmd": cmd,
+ "ok": True,
+ "peer_id": verified.peer_id,
+ "roles": verified.roles,
+ "labels": verified.labels,
+ "expiration": int(verified.expiration.timestamp()),
+ }
+ if cmd == "peers":
+ return {"cmd": cmd, "authenticated_peers": sorted(session.authenticated_peers)}
+ return {"cmd": cmd, "ok": False, "error": f"unknown command {cmd!r}"}
+
+
+async def main() -> None:
+ # stdout carries the protocol lines only; every log goes to stderr.
+ logging.basicConfig(stream=sys.stderr, level=logging.WARNING, force=True)
+ control_plane_url = _require_env("SAM_CONTROL_PLANE_URL")
+ bootstrap_token_path = _require_env("SAM_BOOTSTRAP_TOKEN_PATH")
+ state_dir = _require_env("SAM_SDK_STATE_DIR")
+ allow_insecure = os.environ.get("SAM_INSECURE_CONTROL_PLANE") == "1"
+ listen = [a for a in os.environ.get("SAM_SDK_LISTEN_ADDRS", "").split(",") if a]
+
+ mesh = AgentMesh.enroll(
+ control_plane_url,
+ bootstrap_token_path=bootstrap_token_path,
+ state_dir=state_dir,
+ allow_insecure=allow_insecure,
+ poll_interval=0.2,
+ )
+ async with mesh.join(listen_addrs=listen) as session:
+ _emit(
+ {
+ "sdk": "python",
+ "peer_id": session.peer_id,
+ "routers": [{"peer_id": r.peer_id, "addr": str(r.addr), "roles": r.credential.roles} for r in session.routers],
+ "relay_addresses": session.relay_addresses,
+ "direct_addresses": [str(a) for a in session.host.get_addrs()],
+ "biscuit": base64.b64encode(mesh.credential.biscuit).decode(),
+ }
+ )
+ while True:
+ line = await trio.to_thread.run_sync(sys.stdin.readline)
+ if not line:
+ break
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ command = json.loads(line)
+ except json.JSONDecodeError as err:
+ _emit({"ok": False, "error": f"not JSON: {err}"})
+ continue
+ if command.get("cmd") == "quit":
+ _emit({"cmd": "quit", "ok": True})
+ break
+ _emit(await _handle(session, command))
+
+
+if __name__ == "__main__":
+ trio.run(main)
diff --git a/sdk/python/src/agent_mesh/host.py b/sdk/python/src/agent_mesh/host.py
new file mode 100644
index 00000000..d03d5ec3
--- /dev/null
+++ b/sdk/python/src/agent_mesh/host.py
@@ -0,0 +1,73 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""The libp2p host a member joins the mesh with, configured the way sam-node's
+is (internal/node/node.go): TLS is the only security protocol and yamux the
+muxer. py-libp2p is trio-based, so everything here is trio async."""
+
+from __future__ import annotations
+
+import os
+from datetime import datetime, timedelta, timezone
+from typing import Sequence
+
+import multiaddr
+from cryptography import x509
+from cryptography.x509.oid import NameOID
+from libp2p import new_host
+from libp2p.abc import IHost
+from libp2p.crypto.ed25519 import create_new_key_pair
+from libp2p.custom_types import TProtocol
+from libp2p.security.tls.transport import PROTOCOL_ID as TLS_PROTOCOL_ID
+from libp2p.security.tls.transport import IdentityConfig, TLSTransport
+from libp2p.stream_muxer.yamux.yamux import PROTOCOL_ID as YAMUX_PROTOCOL_ID
+from libp2p.stream_muxer.yamux.yamux import Yamux
+
+from .identity import Identity
+
+
+def _certificate_template() -> x509.CertificateBuilder:
+ """The libp2p TLS certificate with nothing but the libp2p extension.
+ py-libp2p's default template also adds BasicConstraints and KeyUsage,
+ which the spec allows, but js-libp2p (@libp2p/tls) reads the libp2p
+ extension from `extensions[0]` and refuses the certificate otherwise."""
+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "libp2p")])
+ not_before = datetime.now(timezone.utc) - timedelta(hours=1)
+ return (
+ x509.CertificateBuilder()
+ .serial_number(int.from_bytes(os.urandom(8), "big"))
+ .not_valid_before(not_before)
+ .not_valid_after(not_before + timedelta(days=365 * 100))
+ .subject_name(name)
+ .issuer_name(name)
+ )
+
+
+def create_mesh_host(identity: Identity, listen_addrs: Sequence[str] = ()) -> tuple[IHost, list[multiaddr.Multiaddr]]:
+ """Builds the host for `identity`. Run it with `async with host.run(addrs)`.
+ listen_addrs are for direct connections, e.g. "/ip4/0.0.0.0/tcp/0"; an
+ agent is normally reached through a router's relay instead."""
+ key_pair = create_new_key_pair(identity.seed)
+ # No ALPN muxer list: py-libp2p 0.7 advertises early muxer negotiation
+ # but does not complete it, and go-libp2p then refuses the mux upgrade.
+ # Without it the muxer is negotiated with multistream-select as before.
+ tls = TLSTransport(key_pair, identity_config=IdentityConfig(cert_template=_certificate_template()))
+ host = new_host(
+ key_pair=key_pair,
+ sec_opt={TLS_PROTOCOL_ID: tls},
+ muxer_opt={TProtocol(YAMUX_PROTOCOL_ID): Yamux},
+ )
+ if str(host.get_id()) != identity.peer_id:
+ raise RuntimeError(f"libp2p derived peer {host.get_id()} for identity {identity.peer_id}")
+ return host, [multiaddr.Multiaddr(a) for a in listen_addrs]
diff --git a/sdk/python/src/agent_mesh/identity.py b/sdk/python/src/agent_mesh/identity.py
index efbe448a..aec1cb90 100644
--- a/sdk/python/src/agent_mesh/identity.py
+++ b/sdk/python/src/agent_mesh/identity.py
@@ -97,6 +97,11 @@ class Identity:
"""The libp2p protobuf private key encoding (seed || public key)."""
return _LIBP2P_PRIVATE_KEY_PREFIX + self._seed + self.public_key_raw
+ @property
+ def seed(self) -> bytes:
+ """The 32-byte ed25519 seed; what a libp2p implementation loads the key from."""
+ return self._seed
+
@property
def libp2p_public_key(self) -> bytes:
"""The libp2p protobuf public key encoding, what the control plane stores."""
diff --git a/sdk/python/src/agent_mesh/mesh.py b/sdk/python/src/agent_mesh/mesh.py
index 84d2ccbd..3a86bcfb 100644
--- a/sdk/python/src/agent_mesh/mesh.py
+++ b/sdk/python/src/agent_mesh/mesh.py
@@ -30,10 +30,8 @@ _CREDENTIAL_FILE = "credential.json"
class AgentMesh:
"""A member of the mesh: an identity, the credential the control plane
- minted for it, and the client that keeps that credential fresh.
-
- This is the enrollment half of the SDK. Joining the mesh over libp2p and
- serving or calling MCP tools build on top of it (see sdk/README.md)."""
+ minted for it, and the client that keeps that credential fresh. join()
+ puts it on the mesh over libp2p."""
def __init__(self, identity: Identity, control_plane: ControlPlaneClient, credential: MeshCredential, state_dir: Optional[Path]):
self.identity = identity
@@ -150,6 +148,17 @@ class AgentMesh:
the service it wants (e.g. "mcp://calculator") and the agent it speaks for."""
return encode_auth_frame(self._credential.biscuit, target_service, agent)
+ def join(self, **options): # type: ignore[no-untyped-def]
+ """Joins the mesh: connects to the routers in the credential, passes the
+ auth handshake with them, reserves a relay slot and keeps the credential
+ fresh. An async context manager to use under trio:
+
+ async with mesh.join() as session: ...
+ """
+ from .session import join_mesh
+
+ return join_mesh(self, **options)
+
def save(self) -> None:
"""Writes identity and credential to the state directory, if one is configured."""
if self._state_dir is None:
diff --git a/sdk/python/src/agent_mesh/relay.py b/sdk/python/src/agent_mesh/relay.py
new file mode 100644
index 00000000..709896b8
--- /dev/null
+++ b/sdk/python/src/agent_mesh/relay.py
@@ -0,0 +1,129 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Circuit relay v2 as a client of a router: reserve a slot, dial a peer
+through the router, accept a peer the router relays to us. Messages are
+varint-length-prefixed protobufs (go-libp2p's pbio framing); py-libp2p 0.7's
+own relay client sends them unframed and cannot talk to a Go relay, which is
+why this module speaks the protocol directly."""
+
+from __future__ import annotations
+
+import logging
+import time
+from typing import Callable
+
+import multiaddr
+import trio
+from libp2p.abc import IHost, INetConn, INetStream
+from libp2p.connection_types import ConnectionType
+from libp2p.custom_types import TProtocol
+from libp2p.network.connection.raw_connection import RawConnection
+from libp2p.peer.id import ID
+from libp2p.utils.varint import encode_varint_prefixed, read_varint_prefixed_bytes
+
+from ._proto import circuit_pb2 as circuit
+
+logger = logging.getLogger("agent_mesh")
+
+HOP_PROTOCOL = TProtocol("/libp2p/circuit/relay/0.2.0/hop")
+STOP_PROTOCOL = TProtocol("/libp2p/circuit/relay/0.2.0/stop")
+
+RELAY_MESSAGE_TIMEOUT = 10.0
+
+
+def split_circuit_address(addr: multiaddr.Multiaddr) -> tuple[multiaddr.Multiaddr, ID]:
+ """Splits `<relay>/p2p-circuit/p2p/<target>` into the relay address and the target."""
+ text = str(addr)
+ relay_text, _, tail = text.partition("/p2p-circuit")
+ if not _ or not relay_text:
+ raise ValueError(f"{addr} is not a /p2p-circuit address")
+ target = tail.removeprefix("/p2p/")
+ if not target:
+ raise ValueError(f"{addr} names no target peer after /p2p-circuit")
+ return multiaddr.Multiaddr(relay_text), ID.from_base58(target)
+
+
+async def reserve_relay(host: IHost, relay_peer_id: ID) -> circuit.Reservation:
+ """Asks a connected relay for a reservation and returns it. A router grants
+ one only to a peer that passed the auth handshake, so success is also proof
+ of admission."""
+ stream = await host.new_stream(relay_peer_id, [HOP_PROTOCOL])
+ try:
+ with trio.fail_after(RELAY_MESSAGE_TIMEOUT):
+ req = circuit.HopMessage(type=circuit.HopMessage.RESERVE)
+ await stream.write(encode_varint_prefixed(req.SerializeToString()))
+ resp = circuit.HopMessage.FromString(await read_varint_prefixed_bytes(stream))
+ finally:
+ await stream.close()
+ if resp.type != circuit.HopMessage.STATUS:
+ raise RuntimeError(f"relay {relay_peer_id} answered a RESERVE with message type {resp.type}")
+ if resp.status != circuit.OK:
+ raise RuntimeError(f"relay {relay_peer_id} refused the reservation: {circuit.Status.Name(resp.status)}")
+ if resp.reservation.expire <= int(time.time()):
+ raise RuntimeError(f"relay {relay_peer_id} granted a reservation that is already expired")
+ return resp.reservation
+
+
+async def dial_through_relay(host: IHost, relay_peer_id: ID, target: ID) -> INetConn:
+ """Opens a connection to `target` through a relay we are connected to, and
+ registers it with the host so streams can be opened on it."""
+ stream = await host.new_stream(relay_peer_id, [HOP_PROTOCOL])
+ try:
+ with trio.fail_after(RELAY_MESSAGE_TIMEOUT):
+ req = circuit.HopMessage(type=circuit.HopMessage.CONNECT, peer=circuit.Peer(id=target.to_bytes()))
+ await stream.write(encode_varint_prefixed(req.SerializeToString()))
+ resp = circuit.HopMessage.FromString(await read_varint_prefixed_bytes(stream))
+ if resp.type != circuit.HopMessage.STATUS or resp.status != circuit.OK:
+ raise RuntimeError(
+ f"relay {relay_peer_id} refused to connect to {target}: {circuit.Status.Name(resp.status) if resp.status else resp.type}"
+ )
+ except BaseException:
+ await stream.close()
+ raise
+ # From here the stream is the wire; the usual TLS + yamux upgrade runs on it.
+ circuit_addr = multiaddr.Multiaddr(f"/p2p/{relay_peer_id}/p2p-circuit/p2p/{target}")
+ raw = RawConnection(stream=stream, initiator=True, connection_type=ConnectionType.RELAYED, addresses=[circuit_addr])
+ return await host.upgrade_outbound_connection(raw, target)
+
+
+def stop_stream_handler(host: IHost) -> Callable[[INetStream], object]:
+ """Accepts connections a relay forwards to us: answers the STOP request and
+ upgrades the stream into an inbound connection the host then serves."""
+
+ async def handle(stream: INetStream) -> None:
+ relay_peer_id = stream.muxed_conn.peer_id
+ try:
+ with trio.fail_after(RELAY_MESSAGE_TIMEOUT):
+ msg = circuit.StopMessage.FromString(await read_varint_prefixed_bytes(stream))
+ if msg.type != circuit.StopMessage.CONNECT:
+ await stream.write(
+ encode_varint_prefixed(circuit.StopMessage(type=circuit.StopMessage.STATUS, status=circuit.UNEXPECTED_MESSAGE).SerializeToString())
+ )
+ await stream.close()
+ return
+ source = ID(msg.peer.id)
+ await stream.write(encode_varint_prefixed(circuit.StopMessage(type=circuit.StopMessage.STATUS, status=circuit.OK).SerializeToString()))
+ except (trio.TooSlowError, ValueError) as err:
+ logger.warning("relayed connection via %s not accepted: %s", relay_peer_id, err)
+ await stream.close()
+ return
+ circuit_addr = multiaddr.Multiaddr(f"/p2p/{relay_peer_id}/p2p-circuit/p2p/{source}")
+ raw = RawConnection(stream=stream, initiator=False, connection_type=ConnectionType.RELAYED, addresses=[circuit_addr])
+ try:
+ await host.upgrade_inbound_connection(raw, circuit_addr)
+ except Exception as err: # noqa: BLE001 - the relay's peer failed the upgrade; nothing of ours is affected
+ logger.warning("relayed connection from %s via %s failed to upgrade: %s", source, relay_peer_id, err)
+
+ return handle
diff --git a/sdk/python/src/agent_mesh/session.py b/sdk/python/src/agent_mesh/session.py
new file mode 100644
index 00000000..1c1c2315
--- /dev/null
+++ b/sdk/python/src/agent_mesh/session.py
@@ -0,0 +1,192 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import logging
+import time
+from contextlib import asynccontextmanager
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import TYPE_CHECKING, AsyncIterator, Sequence
+
+import multiaddr
+import trio
+from libp2p.abc import IHost
+from libp2p.peer.id import ID
+from libp2p.peer.peerinfo import info_from_p2p_addr
+
+from ._proto import circuit_pb2 as circuit
+from .auth import AUTH_PROTOCOL, auth_stream_handler, authenticate_with_peer
+from .biscuit import ROLE_ROUTER, VerifiedBiscuit, require_role
+from .host import create_mesh_host
+from .relay import STOP_PROTOCOL, dial_through_relay, reserve_relay, split_circuit_address, stop_stream_handler
+
+if TYPE_CHECKING:
+ from .mesh import AgentMesh
+
+logger = logging.getLogger("agent_mesh")
+
+DEFAULT_REFRESH_LEAD = 60 * 60.0
+DEFAULT_REFRESH_RETRY = 30.0
+MIN_REFRESH_DELAY = 2.0
+
+
+@dataclass(frozen=True)
+class AdmittedRouter:
+ peer_id: str
+ addr: multiaddr.Multiaddr
+ credential: VerifiedBiscuit
+ reservation: circuit.Reservation | None = None
+
+
+@dataclass
+class MeshSession:
+ """A member that is on the mesh: a libp2p host authenticated with at least
+ one router, answering the auth handshake for peers that dial it, and
+ keeping its credential fresh for as long as the `join` block is open."""
+
+ mesh: "AgentMesh"
+ host: IHost
+ routers: list[AdmittedRouter]
+ # Peers that passed the inbound auth handshake, with their credential's expiration.
+ authenticated_peers: dict[str, datetime] = field(default_factory=dict)
+
+ @property
+ def peer_id(self) -> str:
+ return str(self.host.get_id())
+
+ @property
+ def relay_addresses(self) -> list[str]:
+ """The `.../p2p-circuit/p2p/<self>` addresses reserved on routers."""
+ out = []
+ for r in self.routers:
+ if r.reservation is None:
+ continue
+ # A relay lists the addresses it wants advertised; go-libp2p keeps
+ # private ones out, so a router on loopback lists none and the
+ # address we reached it on is the one that works.
+ relay_addrs = [multiaddr.Multiaddr(raw) for raw in r.reservation.addrs] or [r.addr]
+ for ma in relay_addrs:
+ text = str(ma)
+ if f"/p2p/{r.peer_id}" not in text:
+ text = f"{text}/p2p/{r.peer_id}"
+ out.append(f"{text}/p2p-circuit/p2p/{self.peer_id}")
+ return out
+
+ async def connect(self, addr: str | multiaddr.Multiaddr) -> ID:
+ """Connects to a peer by address, through a relay when the address says
+ `/p2p-circuit`, and returns its peer ID."""
+ ma = multiaddr.Multiaddr(str(addr))
+ if "/p2p-circuit" in str(ma):
+ relay_addr, target = split_circuit_address(ma)
+ relay = info_from_p2p_addr(relay_addr)
+ if relay.peer_id not in self.host.get_connected_peers():
+ await self.host.connect(relay)
+ if target not in self.host.get_connected_peers():
+ await dial_through_relay(self.host, relay.peer_id, target)
+ return target
+ info = info_from_p2p_addr(ma)
+ await self.host.connect(info)
+ return info.peer_id
+
+ async def authenticate(self, addr: str | multiaddr.Multiaddr) -> VerifiedBiscuit:
+ """Connects to a peer and runs the mutual auth handshake, returning the
+ peer's verified credential."""
+ peer_id = await self.connect(addr)
+ return await authenticate_with_peer(self.host, peer_id, self.mesh.auth_frame(), self.mesh.credential.control_plane_keys)
+
+
+async def _refresh_loop(mesh: "AgentMesh", lead: float, retry: float) -> None:
+ while True:
+ due = mesh.credential.expiration - lead - time.time()
+ await trio.sleep(max(MIN_REFRESH_DELAY, due))
+ try:
+ # The control plane client is synchronous; keep the loop free.
+ await trio.to_thread.run_sync(mesh.refresh)
+ except Exception as err: # noqa: BLE001 - a failed refresh is retried, the session stays up
+ logger.warning("credential refresh failed, retrying in %.0fs: %s", retry, err)
+ await trio.sleep(retry)
+
+
+def _single_cause(group: BaseException) -> BaseException:
+ """trio wraps a failure inside `host.run` in one ExceptionGroup per nursery.
+ A join that failed for one reason should raise that reason."""
+ while isinstance(group, BaseExceptionGroup) and len(group.exceptions) == 1:
+ group = group.exceptions[0]
+ return group
+
+
+@asynccontextmanager
+async def join_mesh(
+ mesh: "AgentMesh",
+ *,
+ listen_addrs: Sequence[str] = (),
+ reserve: bool = True,
+ refresh_lead: float = DEFAULT_REFRESH_LEAD,
+ refresh_retry: float = DEFAULT_REFRESH_RETRY,
+) -> AsyncIterator[MeshSession]:
+ """Implements AgentMesh.join(); lives here to keep mesh.py free of libp2p."""
+ router_addrs = [multiaddr.Multiaddr(a) for a in mesh.credential.router_addresses]
+ if not router_addrs:
+ raise RuntimeError("credential lists no router addresses; the control plane had no active router at enrollment")
+
+ host, listen = create_mesh_host(mesh.identity, listen_addrs)
+ authenticated: dict[str, datetime] = {}
+ host.set_stream_handler(
+ AUTH_PROTOCOL,
+ auth_stream_handler(
+ own_biscuit=lambda: mesh.credential.biscuit,
+ trusted_keys=lambda: mesh.credential.control_plane_keys,
+ on_authenticated=lambda peer, verified: authenticated.__setitem__(peer, verified.expiration),
+ ),
+ )
+ host.set_stream_handler(STOP_PROTOCOL, stop_stream_handler(host))
+
+ try:
+ async with host.run(listen_addrs=listen):
+ admitted = await _admit(host, mesh, router_addrs, reserve)
+ async with trio.open_nursery() as nursery:
+ nursery.start_soon(_refresh_loop, mesh, refresh_lead, refresh_retry)
+ try:
+ yield MeshSession(mesh=mesh, host=host, routers=admitted, authenticated_peers=authenticated)
+ finally:
+ nursery.cancel_scope.cancel()
+ except BaseExceptionGroup as group:
+ cause = _single_cause(group)
+ if cause is group:
+ raise
+ raise cause from None
+
+
+async def _admit(host: IHost, mesh: "AgentMesh", router_addrs: list[multiaddr.Multiaddr], reserve: bool) -> list[AdmittedRouter]:
+ admitted: list[AdmittedRouter] = []
+ failures: list[str] = []
+ for addr in router_addrs:
+ try:
+ info = info_from_p2p_addr(addr)
+ await host.connect(info)
+ credential = await authenticate_with_peer(host, info.peer_id, mesh.auth_frame(), mesh.credential.control_plane_keys)
+ # Enforced under the key that verified the token; a relay that
+ # is not a router must not become our way onto the mesh.
+ require_role(credential, ROLE_ROUTER)
+ reservation = await reserve_relay(host, info.peer_id) if reserve else None
+ admitted.append(AdmittedRouter(peer_id=str(info.peer_id), addr=addr, credential=credential, reservation=reservation))
+ if reserve:
+ break
+ except Exception as err: # noqa: BLE001 - every router is tried, the summary names each failure
+ failures.append(f"{addr}: {err}")
+ if not admitted:
+ raise RuntimeError("no router admitted this member:\n " + "\n ".join(failures))
+ return admitted
diff --git a/sdk/python/tests/test_biscuit.py b/sdk/python/tests/test_biscuit.py
new file mode 100644
index 00000000..4427a4d5
--- /dev/null
+++ b/sdk/python/tests/test_biscuit.py
@@ -0,0 +1,79 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import base64
+import json
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+
+import biscuit_auth as ba
+import pytest
+
+from agent_mesh.biscuit import ROLE_ROUTER, BiscuitVerificationError, require_role, verify_peer_biscuit
+from agent_mesh.controlplane import ROLE_NODE
+
+FIXTURE = json.loads((Path(__file__).resolve().parents[2] / "testdata" / "biscuit_vectors.json").read_text())
+# The vectors expire in 2035; pin "now" so they stay valid for the test's lifetime.
+NOW = datetime(2026, 9, 23, tzinfo=timezone.utc)
+
+
[email protected]("v", FIXTURE["vectors"], ids=[v["name"] for v in FIXTURE["vectors"]])
+def test_go_minted_biscuit(v):
+ trusted = [bytes.fromhex(k) for k in v["trusted_keys"]]
+ token = base64.b64decode(v["biscuit"])
+ if not v["valid"]:
+ with pytest.raises(BiscuitVerificationError):
+ verify_peer_biscuit(token, v["peer_id"], trusted, NOW)
+ return
+ verified = verify_peer_biscuit(token, v["peer_id"], trusted, NOW)
+ assert verified.peer_id == v["peer_id"]
+ assert verified.expiration == datetime.fromtimestamp(v["expiration"], tz=timezone.utc)
+ assert verified.roles == v["roles"]
+ assert verified.verifying_key.hex() == FIXTURE["control_plane_key"]
+ if v["has_router_role"]:
+ require_role(verified, ROLE_ROUTER)
+ with pytest.raises(BiscuitVerificationError):
+ require_role(verified, ROLE_NODE)
+ else:
+ require_role(verified, ROLE_NODE)
+ with pytest.raises(BiscuitVerificationError):
+ require_role(verified, ROLE_ROUTER)
+ assert verified.labels == FIXTURE["node_token_labels"]
+
+
+def test_valid_token_is_refused_past_its_expiration():
+ v = next(x for x in FIXTURE["vectors"] if x["valid"])
+ after = datetime.fromtimestamp(v["expiration"], tz=timezone.utc) + timedelta(seconds=1)
+ with pytest.raises(BiscuitVerificationError, match="expired"):
+ verify_peer_biscuit(base64.b64decode(v["biscuit"]), v["peer_id"], [bytes.fromhex(k) for k in v["trusted_keys"]], after)
+
+
+def test_no_trusted_keys_means_nothing_verifies():
+ v = next(x for x in FIXTURE["vectors"] if x["valid"])
+ with pytest.raises(BiscuitVerificationError, match="no trusted control plane key"):
+ verify_peer_biscuit(base64.b64decode(v["biscuit"]), v["peer_id"], [], NOW)
+
+
+def test_tokens_minted_here_verify_and_report_their_facts():
+ kp = ba.KeyPair()
+ token = ba.BiscuitBuilder(
+ 'node("12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB");'
+ "expiration(2035-01-01T00:00:00Z); expiration(2034-06-01T00:00:00Z);"
+ 'role("sam:role:node"); label("team", "plat\\"form");'
+ ).build(kp.private_key)
+ verified = verify_peer_biscuit(token.to_bytes(), "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB", [kp.public_key.to_bytes()], NOW)
+ # The earliest expiration binds.
+ assert verified.expiration == datetime(2034, 6, 1, tzinfo=timezone.utc)
+ assert verified.labels == {"team": 'plat"form'}
+ assert verified.roles == ["sam:role:node"]
diff --git a/sdk/python/tests/test_session.py b/sdk/python/tests/test_session.py
new file mode 100644
index 00000000..9308bfc9
--- /dev/null
+++ b/sdk/python/tests/test_session.py
@@ -0,0 +1,210 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""A mesh in one process: a fake control plane behind the transport hook, a
+fake router (py-libp2p with the auth handshake and a hop handler) and a peer
+that dials the member directly. The real router and control plane are
+exercised by tests/integration/sdk_join_test.go."""
+
+import time
+import urllib.parse
+
+import biscuit_auth as ba
+import multiaddr
+import pytest
+import trio
+from libp2p import new_host
+from libp2p.crypto.ed25519 import create_new_key_pair
+from libp2p.custom_types import TProtocol
+from libp2p.peer.peerinfo import info_from_p2p_addr
+from libp2p.security.tls.transport import PROTOCOL_ID as TLS_PROTOCOL_ID
+from libp2p.security.tls.transport import TLSTransport
+from libp2p.stream_muxer.yamux.yamux import PROTOCOL_ID as YAMUX_PROTOCOL_ID
+from libp2p.stream_muxer.yamux.yamux import Yamux
+from libp2p.utils.varint import encode_varint_prefixed, read_varint_prefixed_bytes
+
+from agent_mesh._proto import circuit_pb2 as circuit
+from agent_mesh._proto import sam_pb2 as pb
+from agent_mesh.auth import AUTH_PROTOCOL, auth_stream_handler, authenticate_with_peer
+from agent_mesh.biscuit import ROLE_ROUTER
+from agent_mesh.controlplane import ROLE_NODE
+from agent_mesh.identity import Identity
+from agent_mesh.mesh import AgentMesh
+from agent_mesh.relay import HOP_PROTOCOL as RELAY_HOP_PROTOCOL
+
+CP = ba.KeyPair()
+CP_KEY = CP.public_key.to_bytes()
+
+
+def mint(peer_id: str, role: str, expiration: str = "2035-01-01T00:00:00Z") -> bytes:
+ return ba.BiscuitBuilder(
+ "node({p}); expiration(" + expiration + "); role({r});", {"p": peer_id, "r": role}
+ ).build(CP.private_key).to_bytes()
+
+
+def fake_control_plane(router_addresses):
+ """Approves every enrollment with a biscuit bound to the requesting peer."""
+
+ def transport(method, url, headers, body):
+ path = urllib.parse.urlsplit(url).path
+ if (method, path) == ("POST", "/enroll"):
+ req = pb.BootstrapEnrollRequest.FromString(body)
+ return 200, pb.BootstrapEnrollResponse(
+ status=pb.ENROLLMENT_STATUS_APPROVED,
+ biscuit_token=mint(req.peer_id, ROLE_NODE),
+ control_plane_public_key=CP_KEY,
+ router_addresses=router_addresses,
+ expiration=int(time.time()) + 3600,
+ ).SerializeToString()
+ if (method, path) == ("GET", "/keys"):
+ # Unsigned: the client keeps the enrollment key when /keys cannot be verified.
+ return 200, pb.KeysResponse(public_keys=[CP_KEY], timestamp=int(time.time() * 1000)).SerializeToString()
+ return 404, f"no route for {method} {path}".encode()
+
+ return transport
+
+
+def libp2p_host(identity: Identity):
+ kp = create_new_key_pair(identity.seed)
+ return new_host(
+ key_pair=kp,
+ sec_opt={TLS_PROTOCOL_ID: TLSTransport(kp)},
+ muxer_opt={TProtocol(YAMUX_PROTOCOL_ID): Yamux},
+ )
+
+
+def hop_handler(relay_addr: str, grants: bool):
+ """Answers RESERVE like a go-libp2p relay whose ACL either admits or refuses us."""
+
+ async def handle(stream):
+ req = circuit.HopMessage.FromString(await read_varint_prefixed_bytes(stream))
+ assert req.type == circuit.HopMessage.RESERVE
+ if grants:
+ resp = circuit.HopMessage(
+ type=circuit.HopMessage.STATUS,
+ status=circuit.OK,
+ reservation=circuit.Reservation(expire=int(time.time()) + 3600, addrs=[multiaddr.Multiaddr(relay_addr).to_bytes()]),
+ )
+ else:
+ resp = circuit.HopMessage(type=circuit.HopMessage.STATUS, status=circuit.PERMISSION_DENIED)
+ await stream.write(encode_varint_prefixed(resp.SerializeToString()))
+ await stream.close()
+
+ return handle
+
+
+async def start_router(nursery, role=ROLE_ROUTER, trusted=(CP_KEY,), grants=True):
+ identity = Identity.generate()
+ router = libp2p_host(identity)
+ router_biscuit = mint(identity.peer_id, role)
+ router.set_stream_handler(AUTH_PROTOCOL, auth_stream_handler(lambda: router_biscuit, lambda: list(trusted)))
+ started = trio.Event()
+ addr_box = []
+
+ async def run():
+ async with router.run(listen_addrs=[multiaddr.Multiaddr("/ip4/127.0.0.1/tcp/0")]):
+ addr = f"{router.get_addrs()[0]}"
+ router.set_stream_handler(RELAY_HOP_PROTOCOL, hop_handler(addr, grants))
+ addr_box.append(addr)
+ started.set()
+ await trio.sleep_forever()
+
+ nursery.start_soon(run)
+ await started.wait()
+ return router, addr_box[0]
+
+
+async def with_timeout(seconds, fn):
+ with trio.fail_after(seconds):
+ return await fn()
+
+
+def test_join_authenticates_reserves_and_answers_peers():
+ async def main():
+ async with trio.open_nursery() as nursery:
+ router, router_addr = await start_router(nursery)
+ assert "/p2p/12D3Koo" in router_addr
+
+ mesh = AgentMesh.enroll("http://127.0.0.1:1", bootstrap_token="sbt", transport=fake_control_plane([router_addr]))
+ async with mesh.join(listen_addrs=["/ip4/127.0.0.1/tcp/0"], refresh_lead=0) as session:
+ assert [r.peer_id for r in session.routers] == [str(router.get_id())]
+ assert ROLE_ROUTER in session.routers[0].credential.roles
+ assert session.relay_addresses == [f"{router_addr}/p2p-circuit/p2p/{mesh.peer_id}"]
+
+ # A peer dials the member and both sides verify each other.
+ peer_identity = Identity.generate()
+ peer = libp2p_host(peer_identity)
+ async with peer.run(listen_addrs=[]):
+ member_addr = multiaddr.Multiaddr(f"{session.host.get_addrs()[0]}")
+ await peer.connect(info_from_p2p_addr(member_addr))
+ frame = pb.AuthFrame(biscuit=mint(peer_identity.peer_id, ROLE_NODE)).SerializeToString()
+ member = await authenticate_with_peer(peer, session.host.get_id(), frame, [CP_KEY])
+ assert member.peer_id == mesh.peer_id
+ assert member.roles == [ROLE_NODE]
+ assert session.authenticated_peers[peer_identity.peer_id].year == 2035
+
+ # A forged credential gets no answer, only a closed stream.
+ forged = ba.KeyPair()
+ forged_frame = pb.AuthFrame(
+ biscuit=ba.BiscuitBuilder("node({p}); expiration(2035-01-01T00:00:00Z);", {"p": peer_identity.peer_id}).build(forged.private_key).to_bytes()
+ ).SerializeToString()
+ with pytest.raises(Exception):
+ await authenticate_with_peer(peer, session.host.get_id(), forged_frame, [CP_KEY])
+ nursery.cancel_scope.cancel()
+
+ trio.run(with_timeout, 30, main)
+
+
+def test_join_fails_closed_when_the_router_is_not_a_router():
+ async def main():
+ async with trio.open_nursery() as nursery:
+ _, addr = await start_router(nursery, role=ROLE_NODE)
+ mesh = AgentMesh.enroll("http://127.0.0.1:1", bootstrap_token="sbt", transport=fake_control_plane([addr]))
+ with pytest.raises(RuntimeError, match="lacks expected role 'sam:role:router'"):
+ async with mesh.join():
+ pass
+ nursery.cancel_scope.cancel()
+
+ trio.run(with_timeout, 30, main)
+
+
+def test_join_reports_a_router_that_refuses_the_handshake():
+ async def main():
+ async with trio.open_nursery() as nursery:
+ # Trusts a different control plane, so our credential never verifies.
+ _, addr = await start_router(nursery, trusted=(ba.KeyPair().public_key.to_bytes(),))
+ mesh = AgentMesh.enroll("http://127.0.0.1:1", bootstrap_token="sbt", transport=fake_control_plane([addr]))
+ with pytest.raises(RuntimeError, match="no router admitted this member"):
+ async with mesh.join():
+ pass
+ nursery.cancel_scope.cancel()
+
+ trio.run(with_timeout, 30, main)
+
+
+def test_join_fails_when_the_relay_refuses_the_reservation():
+ async def main():
+ async with trio.open_nursery() as nursery:
+ _, addr = await start_router(nursery, grants=False)
+ mesh = AgentMesh.enroll("http://127.0.0.1:1", bootstrap_token="sbt", transport=fake_control_plane([addr]))
+ with pytest.raises(RuntimeError, match="PERMISSION_DENIED"):
+ async with mesh.join():
+ pass
+ # Without a reservation the member still joins.
+ async with mesh.join(reserve=False) as session:
+ assert session.routers[0].reservation is None
+ assert session.relay_addresses == []
+ nursery.cancel_scope.cancel()
+
+ trio.run(with_timeout, 30, main)
diff --git a/sdk/testdata/biscuit_vectors.json b/sdk/testdata/biscuit_vectors.json
new file mode 100644
index 00000000..a77a9f8f
--- /dev/null
+++ b/sdk/testdata/biscuit_vectors.json
@@ -0,0 +1,118 @@
+{
+ "_comment": "Biscuits minted with internal/identity.MintBootstrapBiscuitToken (biscuit-go v2). control_plane_key and trusted_keys are raw ed25519 public keys (hex); biscuit is standard base64. valid is what identity.VerifyBiscuitAndGetExpiry reports for peer_id under trusted_keys.",
+ "control_plane_key": "4fd099ccd47d7893dfe9ec24414ecb0d9b5420232aad30d91c465be33cbe65c4",
+ "node_token_labels": {
+ "region": "eu"
+ },
+ "vectors": [
+ {
+ "name": "node token verifies for its peer",
+ "biscuit": "EqUCCroBCgpleHBpcmF0aW9uCjQxMkQzS29vV0E0WG9wMUphVDNNSHh3WU1rQ2VwWXN2NGlQVm9wTVh3Q3o1aUhZZEJmZVNCCg5jbGllbnRfcGVlcl9pZAoGcmVnaW9uCgJldQoFbGFiZWwKDXNhbTpyb2xlOm5vZGUSABgDIg0KCwiACBIGIIDXjNIHIgkKBwgYEgMYgQgiCgoICIIIEgMYgQgiDwoNCIUIEgMYgwgSAxiECCIJCgcIBhIDGIYIEiQIABIgZEu7DUtv3qJ81Sm5wmg9qmruPkHiZjlqAx29OSagaZ8aQKnD453uvN8Ekk2X95Ar9zwYwFth8rQmOgjDlY/1wgmwYldny2ZcV5TvKXl3sHeVKwxGpuYI2MB/A5FY8dL1rQgiIgogCsZHENhe6A3gZkQSRFJry6nDss3zU7r7JqhbS60neUU=",
+ "peer_id": "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB",
+ "trusted_keys": [
+ "4fd099ccd47d7893dfe9ec24414ecb0d9b5420232aad30d91c465be33cbe65c4"
+ ],
+ "valid": true,
+ "expiration": 2051222400,
+ "roles": [
+ "sam:role:node"
+ ],
+ "has_router_role": false
+ },
+ {
+ "name": "node token verifies when the signer is one of several trusted keys",
+ "biscuit": "EqUCCroBCgpleHBpcmF0aW9uCjQxMkQzS29vV0E0WG9wMUphVDNNSHh3WU1rQ2VwWXN2NGlQVm9wTVh3Q3o1aUhZZEJmZVNCCg5jbGllbnRfcGVlcl9pZAoGcmVnaW9uCgJldQoFbGFiZWwKDXNhbTpyb2xlOm5vZGUSABgDIg0KCwiACBIGIIDXjNIHIgkKBwgYEgMYgQgiCgoICIIIEgMYgQgiDwoNCIUIEgMYgwgSAxiECCIJCgcIBhIDGIYIEiQIABIgZEu7DUtv3qJ81Sm5wmg9qmruPkHiZjlqAx29OSagaZ8aQKnD453uvN8Ekk2X95Ar9zwYwFth8rQmOgjDlY/1wgmwYldny2ZcV5TvKXl3sHeVKwxGpuYI2MB/A5FY8dL1rQgiIgogCsZHENhe6A3gZkQSRFJry6nDss3zU7r7JqhbS60neUU=",
+ "peer_id": "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB",
+ "trusted_keys": [
+ "74fca2a3b389fb1a64d9bf52cc0dd4c2964f3804c0cf7c755e8513c6db8198dc",
+ "4fd099ccd47d7893dfe9ec24414ecb0d9b5420232aad30d91c465be33cbe65c4"
+ ],
+ "valid": true,
+ "expiration": 2051222400,
+ "roles": [
+ "sam:role:node"
+ ],
+ "has_router_role": false
+ },
+ {
+ "name": "router token carries the router role",
+ "biscuit": "ErECCsYBCgpleHBpcmF0aW9uCjQxMkQzS29vV1A4aUtoRGYzaUNNbzJIM2J1dE5WZmRUVXRZd1lXWVE3NWpUR255blhQRk1wCg5jbGllbnRfcGVlcl9pZAoPc2FtOnJvbGU6cm91dGVyCgVyZWxheQoTdGFyZ2V0X3VucmVzdHJpY3RlZBIAGAMiDQoLCIAIEgYggNeM0gciCQoHCBgSAxiBCCIKCggIgggSAxiBCCIJCgcIBhIDGIMIIgkKBwgEEgMYhAgiBQoDCIUIEiQIABIgEan+x/Zyn3EyN9dkytqi0NYkhPjvxCpxC/2lBxjfDyoaQK7mjGDLy/CuVTs0l50ctE3aq1hZARdtLM2E9njdZMDhwr9zQNhmCoEtB86id6E/W8Ismu0t3bzKOgNaRNhVNgMiIgogcd8hyvwGyyLvkXsyI7Zz1ke65tknx89ZV22FuF7RBXM=",
+ "peer_id": "12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp",
+ "trusted_keys": [
+ "4fd099ccd47d7893dfe9ec24414ecb0d9b5420232aad30d91c465be33cbe65c4"
+ ],
+ "valid": true,
+ "expiration": 2051222400,
+ "roles": [
+ "sam:role:router"
+ ],
+ "has_router_role": true
+ },
+ {
+ "name": "token bound to another peer is refused",
+ "biscuit": "EqUCCroBCgpleHBpcmF0aW9uCjQxMkQzS29vV0E0WG9wMUphVDNNSHh3WU1rQ2VwWXN2NGlQVm9wTVh3Q3o1aUhZZEJmZVNCCg5jbGllbnRfcGVlcl9pZAoGcmVnaW9uCgJldQoFbGFiZWwKDXNhbTpyb2xlOm5vZGUSABgDIg0KCwiACBIGIIDXjNIHIgkKBwgYEgMYgQgiCgoICIIIEgMYgQgiDwoNCIUIEgMYgwgSAxiECCIJCgcIBhIDGIYIEiQIABIgZEu7DUtv3qJ81Sm5wmg9qmruPkHiZjlqAx29OSagaZ8aQKnD453uvN8Ekk2X95Ar9zwYwFth8rQmOgjDlY/1wgmwYldny2ZcV5TvKXl3sHeVKwxGpuYI2MB/A5FY8dL1rQgiIgogCsZHENhe6A3gZkQSRFJry6nDss3zU7r7JqhbS60neUU=",
+ "peer_id": "12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp",
+ "trusted_keys": [
+ "4fd099ccd47d7893dfe9ec24414ecb0d9b5420232aad30d91c465be33cbe65c4"
+ ],
+ "valid": false,
+ "reason": "not bound to peer",
+ "has_router_role": false
+ },
+ {
+ "name": "expired token is refused",
+ "biscuit": "EoECCpYBCgpleHBpcmF0aW9uCjQxMkQzS29vV0E0WG9wMUphVDNNSHh3WU1rQ2VwWXN2NGlQVm9wTVh3Q3o1aUhZZEJmZVNCCg5jbGllbnRfcGVlcl9pZAoNc2FtOnJvbGU6bm9kZRIAGAMiDQoLCIAIEgYggMKv8AUiCQoHCBgSAxiBCCIKCggIgggSAxiBCCIJCgcIBhIDGIMIEiQIABIgoPZcftk3ja08cojPf2GL1mxS9Hp4kiWx+SW++f19eZkaQAFJaKnnSD5+ApcDFR5MXRYUvDuw6+yXuMvtC06h0b6AA5DkuXNMVE+Uta0p7FrMdpfdUylSMlT7Vb0ASR4gSwsiIgogNYDc5YuH5ZouZ2DG73+lwyGg731neVEnY3dxTsTe0yA=",
+ "peer_id": "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB",
+ "trusted_keys": [
+ "4fd099ccd47d7893dfe9ec24414ecb0d9b5420232aad30d91c465be33cbe65c4"
+ ],
+ "valid": false,
+ "reason": "expired",
+ "has_router_role": false
+ },
+ {
+ "name": "token signed by an untrusted key is refused",
+ "biscuit": "EoECCpYBCgpleHBpcmF0aW9uCjQxMkQzS29vV0E0WG9wMUphVDNNSHh3WU1rQ2VwWXN2NGlQVm9wTVh3Q3o1aUhZZEJmZVNCCg5jbGllbnRfcGVlcl9pZAoNc2FtOnJvbGU6bm9kZRIAGAMiDQoLCIAIEgYggNeM0gciCQoHCBgSAxiBCCIKCggIgggSAxiBCCIJCgcIBhIDGIMIEiQIABIgLH6K1R5zUdIwvzO0AubjijjCp8QbSfSdnG6yJEg4BdUaQB3M924M3uZ3kN7G/UL3TdYV/ha+8diKnoE3Jy/YHnRjAEWYjn3/vo122CoimB5Nn9IijKPZoTAqdDVofRL24ggiIgogicr29FanYgaGRDcKr05/9OTr20Jciz5xSWJkPqlKpKs=",
+ "peer_id": "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB",
+ "trusted_keys": [
+ "4fd099ccd47d7893dfe9ec24414ecb0d9b5420232aad30d91c465be33cbe65c4"
+ ],
+ "valid": false,
+ "reason": "signature",
+ "has_router_role": false
+ },
+ {
+ "name": "token with an appended block is refused even for the bound peer",
+ "biscuit": "EqUCCroBCgpleHBpcmF0aW9uCjQxMkQzS29vV0E0WG9wMUphVDNNSHh3WU1rQ2VwWXN2NGlQVm9wTVh3Q3o1aUhZZEJmZVNCCg5jbGllbnRfcGVlcl9pZAoGcmVnaW9uCgJldQoFbGFiZWwKDXNhbTpyb2xlOm5vZGUSABgDIg0KCwiACBIGIIDXjNIHIgkKBwgYEgMYgQgiCgoICIIIEgMYgQgiDwoNCIUIEgMYgwgSAxiECCIJCgcIBhIDGIYIEiQIABIgZEu7DUtv3qJ81Sm5wmg9qmruPkHiZjlqAx29OSagaZ8aQKnD453uvN8Ekk2X95Ar9zwYwFth8rQmOgjDlY/1wgmwYldny2ZcV5TvKXl3sHeVKwxGpuYI2MB/A5FY8dL1rQgarwEKRQo0MTJEM0tvb1dQOGlLaERmM2lDTW8ySDNidXROVmZkVFV0WXdZV1lRNzVqVEdueW5YUEZNcBIAGAMiCQoHCBgSAxiHCBIkCAASIG3ccXHqENKuo3uJxviytjqMwcKepU0bgwdB3bH3onePGkDMkz29kwPRfdreIjjTfhNA7W+6O5xHSGZoLqv5vzsAiR0p/kdGkcZcFTGXWE7hVbtXJnqpiJG/2vpIv1kTUMsIIiIKIL2l0GXG7A3dPufrA7Itl2K0NgSz3D57Zf0FFUNiEqgd",
+ "peer_id": "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB",
+ "trusted_keys": [
+ "4fd099ccd47d7893dfe9ec24414ecb0d9b5420232aad30d91c465be33cbe65c4"
+ ],
+ "valid": false,
+ "reason": "appended block",
+ "has_router_role": false
+ },
+ {
+ "name": "appended node fact does not rebind the token",
+ "biscuit": "EqUCCroBCgpleHBpcmF0aW9uCjQxMkQzS29vV0E0WG9wMUphVDNNSHh3WU1rQ2VwWXN2NGlQVm9wTVh3Q3o1aUhZZEJmZVNCCg5jbGllbnRfcGVlcl9pZAoGcmVnaW9uCgJldQoFbGFiZWwKDXNhbTpyb2xlOm5vZGUSABgDIg0KCwiACBIGIIDXjNIHIgkKBwgYEgMYgQgiCgoICIIIEgMYgQgiDwoNCIUIEgMYgwgSAxiECCIJCgcIBhIDGIYIEiQIABIgZEu7DUtv3qJ81Sm5wmg9qmruPkHiZjlqAx29OSagaZ8aQKnD453uvN8Ekk2X95Ar9zwYwFth8rQmOgjDlY/1wgmwYldny2ZcV5TvKXl3sHeVKwxGpuYI2MB/A5FY8dL1rQgarwEKRQo0MTJEM0tvb1dQOGlLaERmM2lDTW8ySDNidXROVmZkVFV0WXdZV1lRNzVqVEdueW5YUEZNcBIAGAMiCQoHCBgSAxiHCBIkCAASIG3ccXHqENKuo3uJxviytjqMwcKepU0bgwdB3bH3onePGkDMkz29kwPRfdreIjjTfhNA7W+6O5xHSGZoLqv5vzsAiR0p/kdGkcZcFTGXWE7hVbtXJnqpiJG/2vpIv1kTUMsIIiIKIL2l0GXG7A3dPufrA7Itl2K0NgSz3D57Zf0FFUNiEqgd",
+ "peer_id": "12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp",
+ "trusted_keys": [
+ "4fd099ccd47d7893dfe9ec24414ecb0d9b5420232aad30d91c465be33cbe65c4"
+ ],
+ "valid": false,
+ "reason": "appended block",
+ "has_router_role": false
+ },
+ {
+ "name": "garbage is refused",
+ "biscuit": "bm90IGEgYmlzY3VpdA==",
+ "peer_id": "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB",
+ "trusted_keys": [
+ "4fd099ccd47d7893dfe9ec24414ecb0d9b5420232aad30d91c465be33cbe65c4"
+ ],
+ "valid": false,
+ "reason": "malformed",
+ "has_router_role": false
+ }
+ ]
+}
diff --git a/tests/integration/sdk_mesh_test.go b/tests/integration/sdk_mesh_test.go
new file mode 100644
index 00000000..cb60e552
--- /dev/null
+++ b/tests/integration/sdk_mesh_test.go
@@ -0,0 +1,550 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package integration_test
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/google/sam/api"
+ "github.com/google/sam/internal/controlplane"
+ "github.com/google/sam/internal/identity"
+ "github.com/google/sam/internal/storage"
+ "github.com/libp2p/go-libp2p"
+ "github.com/libp2p/go-libp2p/core/host"
+ "github.com/libp2p/go-libp2p/core/network"
+ "github.com/libp2p/go-libp2p/core/peer"
+ libp2ptls "github.com/libp2p/go-libp2p/p2p/security/tls"
+ "github.com/libp2p/go-msgio"
+ "github.com/multiformats/go-multiaddr"
+ "google.golang.org/protobuf/proto"
+)
+
+// sdkMember is a running SDK conformance-join runner: a mesh member written
+// in another language that the test drives over stdin/stdout. Both runners
+// (sdk/js/src/conformance-join.ts, sdk/python/src/agent_mesh/conformance_join.py)
+// speak the same line protocol.
+type sdkMember struct {
+ name string
+ report sdkJoinReport
+ cmd *exec.Cmd
+ stdin io.WriteCloser
+ lines *bufio.Scanner
+ stderr *bytes.Buffer
+}
+
+// sdkJoinReport is the first line a runner prints once on the mesh.
+type sdkJoinReport struct {
+ SDK string `json:"sdk"`
+ PeerID string `json:"peer_id"`
+ Routers []struct {
+ PeerID string `json:"peer_id"`
+ Addr string `json:"addr"`
+ Roles []string `json:"roles"`
+ } `json:"routers"`
+ RelayAddresses []string `json:"relay_addresses"`
+ DirectAddresses []string `json:"direct_addresses"`
+ Biscuit string `json:"biscuit"`
+}
+
+// sdkAuthResult answers an {"cmd":"auth"} command.
+type sdkAuthResult struct {
+ OK bool `json:"ok"`
+ Error string `json:"error"`
+ PeerID string `json:"peer_id"`
+ Roles []string `json:"roles"`
+ Labels map[string]string `json:"labels"`
+ Expiration int64 `json:"expiration"`
+}
+
+var sdkMemberLaunchers = []sdkRunner{
+ {
+ name: "js",
+ cmd: func(root string) (*exec.Cmd, string) {
+ entry := filepath.Join(root, "sdk", "js", "dist", "conformance-join.js")
+ if _, err := exec.LookPath("node"); err != nil {
+ return nil, "node is not installed"
+ }
+ if _, err := os.Stat(entry); err != nil {
+ return nil, "sdk/js is not built (cd sdk/js && npm ci && npm run build)"
+ }
+ return exec.Command("node", entry), ""
+ },
+ },
+ {
+ name: "python",
+ cmd: func(root string) (*exec.Cmd, string) {
+ python := filepath.Join(root, "sdk", "python", ".venv", "bin", "python")
+ if _, err := os.Stat(python); err != nil {
+ var lookErr error
+ if python, lookErr = exec.LookPath("python3"); lookErr != nil {
+ return nil, "python3 is not installed"
+ }
+ }
+ if err := exec.Command(python, "-c", "import agent_mesh.session").Run(); err != nil {
+ return nil, "agent_mesh is not importable with libp2p (pip install -e sdk/python)"
+ }
+ return exec.Command(python, "-m", "agent_mesh.conformance_join"), ""
+ },
+ },
+}
+
+// TestNativeSDKsMesh runs one mesh: a control plane, a sam-router, a
+// sam-node and one member per SDK, all real. It then walks the connectivity
+// matrix. Every member authenticates with the router and gets a relay
+// reservation, which the router grants only to admitted peers. Each SDK
+// member reaches the sam-node directly and the other SDK member both
+// directly and through the router, and on every path both ends verify each
+// other's credential with the /sam/auth/1.0.0 handshake. The sam-node
+// reaches each SDK member through the router. A Go peer that is itself
+// admitted does the same and also checks that a forged credential gets no
+// answer. Any SDK whose toolchain is missing is skipped, and the matrix
+// shrinks to the members present.
+func TestNativeSDKsMesh(t *testing.T) {
+ root := repoRoot(t)
+ oidcURL, mintToken := startCustomMockOIDC(t)
+
+ store, err := storage.NewSQLStore("sqlite", filepath.Join(t.TempDir(), "cp.db"))
+ if err != nil {
+ t.Fatalf("failed to create store: %v", err)
+ }
+ t.Cleanup(func() { _ = store.Close() })
+
+ const adminToken = "test-admin-token"
+ srv, err := controlplane.NewServer(controlplane.Options{
+ ListenAddr: "127.0.0.1:0",
+ AdminToken: adminToken,
+ OIDCIssuer: oidcURL,
+ AllowedAudiences: []string{"sam-mesh-audience"},
+ AutoApproveEnrollment: true,
+ }, store)
+ if err != nil {
+ t.Fatalf("failed to create control plane: %v", err)
+ }
+ if err := srv.Start(); err != nil {
+ t.Fatalf("failed to start control plane: %v", err)
+ }
+ t.Cleanup(func() { _ = srv.Close() })
+ baseURL := "http://" + srv.Addr()
+ _, portStr, _ := net.SplitHostPort(srv.Addr())
+ cpPort, _ := strconv.Atoi(portStr)
+
+ // The router enrolls through OIDC with group "routers" and the node with
+ // user mock-user; the policy binds both to their roles.
+ policyFile := filepath.Join(t.TempDir(), "policy.yaml")
+ writePolicyWithRouter(t, policyFile, fmt.Sprintf("bindings:\n - members: [\"user:mock-user\"]\n role: %s\nroles: []\n", api.RoleNode))
+ injectPolicyYAML(t, cpPort, adminToken, policyFile)
+
+ routerAddr, _ := startRouter(t, t.TempDir(), cpPort, mintToken, "router")
+ routerPeer := extractPeerID(routerAddr)
+
+ ctx := context.Background()
+ cpPriv, cpPub, err := store.GetCurrentKey(ctx)
+ if err != nil {
+ t.Fatalf("failed to load control plane signing key: %v", err)
+ }
+
+ // The Go node: a sam-node enrolled through OIDC, listening on loopback.
+ nodeBin := buildBinary(t, "./cmd/sam-node")
+ nodeHome := filepath.Join(t.TempDir(), "node")
+ samNode := launchNode(t, nodeBin,
+ append(os.Environ(), "HOME="+nodeHome, "XDG_CONFIG_HOME="+filepath.Join(nodeHome, ".config")),
+ nodeHome, "run",
+ "--control-plane", baseURL,
+ "--jwt", mintToken(map[string]interface{}{"sub": "mock-user", "roles": []string{api.RoleNode}}),
+ "--allow-loopback",
+ "--api-token-path", tokenPath(t, "node-token"),
+ "--log-level", "debug",
+ )
+ nodeAPI := samNode.waitForAPI(t)
+
+ // One member per SDK, each listening directly on loopback too so both
+ // the direct and the relayed path can be walked.
+ var members []*sdkMember
+ for _, launcher := range sdkMemberLaunchers {
+ cmd, skip := launcher.cmd(root)
+ if skip != "" {
+ t.Logf("%s SDK skipped: %s", launcher.name, skip)
+ continue
+ }
+ members = append(members, startSDKMember(t, launcher.name, cmd, root, baseURL, adminToken, routerAddr, routerPeer))
+ }
+ if len(members) == 0 {
+ t.Skip("no SDK toolchain available; see sdk/README.md")
+ }
+
+ // The router reports every member connected to the control plane.
+ waitForPeerOnRouter(t, cpPort, adminToken, samNode.peerID.String(), 5*time.Second)
+ for _, m := range members {
+ waitForPeerOnRouter(t, cpPort, adminToken, m.report.PeerID, 5*time.Second)
+ }
+
+ goPeer := newAdmittedGoPeer(t, ctx, cpPriv, routerAddr)
+
+ for _, m := range members {
+ m := m
+ t.Run(m.name, func(t *testing.T) {
+ // SDK -> sam-node, directly: the node's HandleAuthHandshake
+ // verifies the member's biscuit and answers with its own.
+ nodeCred := m.auth(t, samNode.p2pAddr)
+ if nodeCred.PeerID != samNode.peerID.String() || !contains(nodeCred.Roles, api.RoleNode) {
+ t.Fatalf("%s verified the node as %+v", m.name, nodeCred)
+ }
+ if !strings.Contains(samNode.log(), "Successfully authenticated peer "+m.report.PeerID) {
+ t.Errorf("sam-node log does not record admitting %s", m.report.PeerID)
+ }
+
+ // sam-node -> SDK, through the router: the node reaches the member
+ // on its relayed address, which the router only serves for
+ // authenticated peers on both ends.
+ connectPeerWithToken(t, nodeAPI, "node-token", m.report.RelayAddresses[0])
+
+ // SDK -> every other SDK, directly and through the router.
+ for _, other := range members {
+ if other == m {
+ continue
+ }
+ for _, addr := range []string{pickDirectAddr(t, other.report.DirectAddresses, other.report.PeerID), other.report.RelayAddresses[0]} {
+ cred := m.auth(t, addr)
+ if cred.PeerID != other.report.PeerID || !contains(cred.Roles, api.RoleNode) {
+ t.Fatalf("%s verified %s at %s as %+v", m.name, other.name, addr, cred)
+ }
+ }
+ }
+
+ // Go peer -> SDK, through the router, both ways of the handshake.
+ target := multiaddr.StringCast(m.report.RelayAddresses[0])
+ sdkPeer, _ := peer.Decode(m.report.PeerID)
+ dialCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ if err := goPeer.Connect(dialCtx, peer.AddrInfo{ID: sdkPeer, Addrs: []multiaddr.Multiaddr{target}}); err != nil {
+ t.Fatalf("go peer could not reach %s at %s: %v", m.name, target, err)
+ }
+ memberBiscuit := authHandshake(t, ctx, goPeer, sdkPeer, goHostBiscuit(t, cpPriv, goPeer.ID()))
+ if _, err := identity.VerifyBiscuitAndGetExpiry(memberBiscuit, sdkPeer, []ed25519.PublicKey{cpPub}, 5*time.Second); err != nil {
+ t.Fatalf("%s answered with a credential that does not verify: %v", m.name, err)
+ }
+ if err := identity.VerifyBiscuitRole(memberBiscuit, cpPub, api.RoleNode, 5*time.Second); err != nil {
+ t.Fatalf("%s credential lacks the node role: %v", m.name, err)
+ }
+ if want, _ := base64.StdEncoding.DecodeString(m.report.Biscuit); !bytes.Equal(want, memberBiscuit) {
+ t.Fatal("member answered with a different biscuit than it reported holding")
+ }
+ refuseForgedFrame(t, ctx, goPeer, sdkPeer)
+
+ // A peer that is not on the mesh cannot be reached: the address
+ // names an unknown peer behind the router.
+ stranger, _ := peer.Decode("12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB")
+ if res := m.authRaw(t, routerAddr+"/p2p-circuit/p2p/"+stranger.String()); res.OK {
+ t.Fatalf("%s reached a peer that is not on the mesh", m.name)
+ }
+ })
+ }
+
+ // Everyone who ran the handshake against a member is in its admitted set.
+ for _, m := range members {
+ peers := m.peers(t)
+ if !contains(peers, goPeer.ID().String()) {
+ t.Errorf("%s admitted peers %v lack the Go peer %s", m.name, peers, goPeer.ID())
+ }
+ for _, other := range members {
+ if other != m && !contains(peers, other.report.PeerID) {
+ t.Errorf("%s admitted peers %v lack %s (%s)", m.name, peers, other.name, other.report.PeerID)
+ }
+ }
+ m.quit(t)
+ }
+}
+
+func startSDKMember(t *testing.T, name string, cmd *exec.Cmd, root, baseURL, adminToken, routerAddr, routerPeer string) *sdkMember {
+ t.Helper()
+ tokenPath := filepath.Join(t.TempDir(), "bootstrap.token")
+ if err := os.WriteFile(tokenPath, []byte(mintBootstrapToken(t, baseURL, adminToken)+"\n"), 0o600); err != nil {
+ t.Fatalf("failed to write bootstrap token: %v", err)
+ }
+ cmd.Env = append(os.Environ(),
+ "SAM_CONTROL_PLANE_URL="+baseURL,
+ "SAM_BOOTSTRAP_TOKEN_PATH="+tokenPath,
+ "SAM_SDK_STATE_DIR="+filepath.Join(t.TempDir(), "state"),
+ "SAM_SDK_LISTEN_ADDRS=/ip4/127.0.0.1/tcp/0",
+ )
+ cmd.Dir = root
+ m := &sdkMember{name: name, cmd: cmd, stderr: &bytes.Buffer{}}
+ cmd.Stderr = m.stderr
+ stdin, err := cmd.StdinPipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ m.stdin = stdin
+ m.lines = bufio.NewScanner(stdout)
+ m.lines.Buffer(make([]byte, 0, 64*1024), 1024*1024)
+ if err := cmd.Start(); err != nil {
+ t.Fatalf("failed to start %s member: %v", name, err)
+ }
+ t.Cleanup(func() {
+ _ = stdin.Close()
+ _ = cmd.Process.Kill()
+ if cmd.ProcessState == nil {
+ _ = cmd.Wait()
+ }
+ if t.Failed() {
+ t.Logf("%s member stderr:\n%s", name, m.stderr.String())
+ }
+ })
+
+ if line := m.readLine(t, 20*time.Second); json.Unmarshal(line, &m.report) != nil {
+ t.Fatalf("%s member printed no join report, got: %q", name, line)
+ }
+ if len(m.report.Routers) != 1 || m.report.Routers[0].PeerID != routerPeer {
+ t.Fatalf("%s report routers %+v, want the router %s", name, m.report.Routers, routerPeer)
+ }
+ if !contains(m.report.Routers[0].Roles, api.RoleRouter) {
+ t.Fatalf("%s: router credential roles %v lack %s", name, m.report.Routers[0].Roles, api.RoleRouter)
+ }
+ if _, err := peer.Decode(m.report.PeerID); err != nil {
+ t.Fatalf("%s report peer_id %q: %v", name, m.report.PeerID, err)
+ }
+ if len(m.report.RelayAddresses) == 0 {
+ t.Fatalf("%s: no relay address, the router did not grant a reservation", name)
+ }
+ for _, a := range m.report.RelayAddresses {
+ if !strings.HasPrefix(a, routerAddr) || !strings.HasSuffix(a, "/p2p-circuit/p2p/"+m.report.PeerID) {
+ t.Fatalf("%s relay address %s is not <router>/p2p-circuit/p2p/<self> for router %s", name, a, routerAddr)
+ }
+ }
+ return m
+}
+
+func (m *sdkMember) send(t *testing.T, command map[string]string) []byte {
+ t.Helper()
+ line, _ := json.Marshal(command)
+ if _, err := m.stdin.Write(append(line, '\n')); err != nil {
+ t.Fatalf("%s member: write command: %v", m.name, err)
+ }
+ return m.readLine(t, 20*time.Second)
+}
+
+// authRaw asks the member to connect to addr and run the auth handshake.
+func (m *sdkMember) authRaw(t *testing.T, addr string) sdkAuthResult {
+ t.Helper()
+ var res sdkAuthResult
+ if line := m.send(t, map[string]string{"cmd": "auth", "addr": addr}); json.Unmarshal(line, &res) != nil {
+ t.Fatalf("%s member: auth answered %q", m.name, line)
+ }
+ return res
+}
+
+// auth is authRaw that must succeed.
+func (m *sdkMember) auth(t *testing.T, addr string) sdkAuthResult {
+ t.Helper()
+ res := m.authRaw(t, addr)
+ if !res.OK {
+ t.Fatalf("%s member could not authenticate with %s: %s", m.name, addr, res.Error)
+ }
+ if res.Expiration <= time.Now().Unix() {
+ t.Fatalf("%s member accepted a credential from %s that is already expired", m.name, addr)
+ }
+ return res
+}
+
+func (m *sdkMember) peers(t *testing.T) []string {
+ t.Helper()
+ var res struct {
+ AuthenticatedPeers []string `json:"authenticated_peers"`
+ }
+ if line := m.send(t, map[string]string{"cmd": "peers"}); json.Unmarshal(line, &res) != nil {
+ t.Fatalf("%s member: peers answered %q", m.name, line)
+ }
+ return res.AuthenticatedPeers
+}
+
+func (m *sdkMember) quit(t *testing.T) {
+ t.Helper()
+ m.send(t, map[string]string{"cmd": "quit"})
+ _ = m.stdin.Close()
+ exited := make(chan error, 1)
+ go func() { exited <- m.cmd.Wait() }()
+ select {
+ case err := <-exited:
+ if err != nil {
+ t.Errorf("%s member exited with %v\nstderr:\n%s", m.name, err, m.stderr.String())
+ }
+ case <-time.After(15 * time.Second):
+ _ = m.cmd.Process.Kill()
+ <-exited
+ t.Errorf("%s member did not exit after quit\nstderr:\n%s", m.name, m.stderr.String())
+ }
+}
+
+// readLine returns the member's next stdout line or fails after timeout; a
+// runner that hangs must not hang the test.
+func (m *sdkMember) readLine(t *testing.T, timeout time.Duration) []byte {
+ t.Helper()
+ type result struct {
+ line []byte
+ err error
+ }
+ ch := make(chan result, 1)
+ go func() {
+ if m.lines.Scan() {
+ ch <- result{line: append([]byte(nil), m.lines.Bytes()...)}
+ return
+ }
+ err := m.lines.Err()
+ if err == nil {
+ err = io.EOF
+ }
+ ch <- result{err: err}
+ }()
+ select {
+ case r := <-ch:
+ if r.err != nil {
+ t.Fatalf("%s member stdout ended: %v\nstderr:\n%s", m.name, r.err, m.stderr.String())
+ }
+ return r.line
+ case <-time.After(timeout):
+ t.Fatalf("%s member printed nothing within %v\nstderr:\n%s", m.name, timeout, m.stderr.String())
+ return nil
+ }
+}
+
+// newAdmittedGoPeer is a libp2p host configured like sam-node's, connected
+// to the router and past its auth handshake, so the router relays for it.
+func newAdmittedGoPeer(t *testing.T, ctx context.Context, cpPriv ed25519.PrivateKey, routerAddr string) host.Host {
+ t.Helper()
+ h, err := libp2p.New(
+ libp2p.NoListenAddrs,
+ libp2p.Security(libp2ptls.ID, libp2ptls.New),
+ libp2p.EnableRelay(),
+ )
+ if err != nil {
+ t.Fatalf("failed to create go peer: %v", err)
+ }
+ t.Cleanup(func() { _ = h.Close() })
+ info, err := peer.AddrInfoFromString(routerAddr)
+ if err != nil {
+ t.Fatalf("router address %s: %v", routerAddr, err)
+ }
+ connectCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ if err := h.Connect(connectCtx, *info); err != nil {
+ t.Fatalf("go peer could not connect to the router: %v", err)
+ }
+ routerBiscuit := authHandshake(t, ctx, h, info.ID, goHostBiscuit(t, cpPriv, h.ID()))
+ if err := identity.VerifyBiscuitRole(routerBiscuit, cpPriv.Public().(ed25519.PublicKey), api.RoleRouter, 5*time.Second); err != nil {
+ t.Fatalf("router credential lacks the router role: %v", err)
+ }
+ return h
+}
+
+func goHostBiscuit(t *testing.T, cpPriv ed25519.PrivateKey, id peer.ID) []byte {
+ t.Helper()
+ b, err := identity.MintBootstrapBiscuitToken(cpPriv, id, api.RoleNode, time.Now().Add(time.Hour), nil, nil)
+ if err != nil {
+ t.Fatalf("failed to mint biscuit for %s: %v", id, err)
+ }
+ return b
+}
+
+// authHandshake runs the client side of /sam/auth/1.0.0 against target and
+// returns the credential target answers with.
+func authHandshake(t *testing.T, ctx context.Context, h host.Host, target peer.ID, biscuit []byte) []byte {
+ t.Helper()
+ streamCtx, cancel := context.WithTimeout(network.WithAllowLimitedConn(ctx, "auth"), 10*time.Second)
+ defer cancel()
+ s, err := h.NewStream(streamCtx, target, api.AuthProtocolID)
+ if err != nil {
+ t.Fatalf("open auth stream to %s: %v", target, err)
+ }
+ defer func() { _ = s.Close() }()
+ _ = s.SetDeadline(time.Now().Add(10 * time.Second))
+ frame, _ := proto.Marshal(&api.AuthFrame{Biscuit: biscuit})
+ if err := msgio.NewVarintWriter(s).WriteMsg(frame); err != nil {
+ t.Fatalf("write auth frame to %s: %v", target, err)
+ }
+ msg, err := msgio.NewVarintReaderSize(s, 64*1024).ReadMsg()
+ if err != nil {
+ t.Fatalf("read auth response from %s: %v", target, err)
+ }
+ var resp api.AuthResponse
+ if err := proto.Unmarshal(msg, &resp); err != nil {
+ t.Fatalf("auth response from %s: %v", target, err)
+ }
+ if !resp.Success {
+ t.Fatalf("%s refused the handshake: %s", target, resp.Error)
+ }
+ return resp.Biscuit
+}
+
+// refuseForgedFrame checks that target answers a frame it cannot verify
+// with a closed stream and nothing else, as sam-node does.
+func refuseForgedFrame(t *testing.T, ctx context.Context, h host.Host, target peer.ID) {
+ t.Helper()
+ s, err := h.NewStream(network.WithAllowLimitedConn(ctx, "auth"), target, api.AuthProtocolID)
+ if err != nil {
+ t.Fatalf("open auth stream for the forged frame: %v", err)
+ }
+ defer func() { _ = s.Close() }()
+ forged, _ := proto.Marshal(&api.AuthFrame{Biscuit: []byte("not a biscuit")})
+ if err := msgio.NewVarintWriter(s).WriteMsg(forged); err != nil {
+ t.Fatalf("write forged frame: %v", err)
+ }
+ _ = s.SetReadDeadline(time.Now().Add(5 * time.Second))
+ if msg, err := msgio.NewVarintReaderSize(s, 64*1024).ReadMsg(); err == nil {
+ t.Fatalf("%s answered a forged frame with %d bytes", target, len(msg))
+ }
+}
+
+// pickDirectAddr is the member's loopback TCP address with its peer ID.
+func pickDirectAddr(t *testing.T, addrs []string, peerID string) string {
+ t.Helper()
+ for _, a := range addrs {
+ if strings.HasPrefix(a, "/ip4/127.0.0.1/tcp/") {
+ if strings.Contains(a, "/p2p/") {
+ return a
+ }
+ return a + "/p2p/" + peerID
+ }
+ }
+ t.Fatalf("no loopback TCP address among %v", addrs)
+ return ""
+}
+
+func contains(values []string, want string) bool {
+ for _, v := range values {
+ if v == want {
+ return true
+ }
+ }
+ return false
+}