Skip to content

Agent Mesh

sdk/js: keep the relay reservation across a dropped router connection

Antonio Ojeab5c221442b95
diff --git a/sdk/js/src/host.ts b/sdk/js/src/host.ts
index e3c21de5..c33cd357 100644
--- a/sdk/js/src/host.ts
+++ b/sdk/js/src/host.ts
@@ -89,14 +89,31 @@ export async function createMeshHost(identity: Identity, options: MeshHostOption
});
}
+/** The relay listener a member holds, to ask for its reservation again. */
+export interface RelayListener {
+ listen(addr: Multiaddr): Promise<void>;
+}
+
/**
- * 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.
+ * Starts listening on a relay after the caller has authenticated with it,
+ * and returns the listener. 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.
+ *
+ * The reservation goes with the connection it was made on: a router that
+ * restarts or trims the connection drops it, and js-libp2p does not ask a
+ * configured relay again. Calling `listen` on the returned listener does,
+ * without registering a second listener.
*/
-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")]);
+export async function listenThroughRelay(node: Libp2p, relayAddr: Multiaddr): Promise<RelayListener> {
+ const internals = node as unknown as { components: { transportManager: { listen(addrs: Multiaddr[]): Promise<void>; getListeners(): RelayListener[] } } };
+ const manager = internals.components.transportManager;
+ const before = new Set(manager.getListeners());
+ await manager.listen([relayAddr.encapsulate("/p2p-circuit")]);
+ const listener = manager.getListeners().find((l) => !before.has(l));
+ if (listener === undefined) {
+ throw new Error("libp2p registered no listener for the relay address");
+ }
+ return listener;
}
diff --git a/sdk/js/src/session.test.ts b/sdk/js/src/session.test.ts
index e8ab8f3f..e2f53415 100644
--- a/sdk/js/src/session.test.ts
+++ b/sdk/js/src/session.test.ts
@@ -189,6 +189,70 @@ test("a router handed out as /dnsaddr still relays to peers", async () => {
}
});
+test("a dropped router connection is authenticated and reserved again", async () => {
+ // A router that restarts or trims the connection forgets the admission
+ // and drops the reservation with it; js-libp2p does not ask a configured
+ // relay again. The member notices within the check interval, runs the
+ // handshake again and holds a relayed address once more.
+ const handshakes: string[] = [];
+ const strict = await createLibp2p({
+ addresses: { listen: ["/ip4/127.0.0.1/tcp/0"] },
+ transports: [tcp()],
+ connectionEncrypters: [tls()],
+ streamMuxers: [yamux()],
+ services: { identify: identify(), relay: circuitRelayServer() },
+ });
+ try {
+ const strictBiscuit = mint(strict.peerId.toString(), ROLE_ROUTER);
+ await strict.handle(
+ AUTH_PROTOCOL,
+ authStreamHandler({ ownBiscuit: () => strictBiscuit, trustedKeys: () => [cpKey], onAuthenticated: (peerId) => handshakes.push(peerId) }),
+ );
+ 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]) });
+ const session = await mesh.join({ refreshLeadMs: 0, relayCheckIntervalMs: 200 });
+ try {
+ assert.deepEqual(handshakes, [mesh.peerId]);
+ const reserved = session.relayAddresses.map(String);
+ assert.equal(reserved.length, 1);
+
+ await strict.hangUp(session.node.peerId);
+ const deadline = Date.now() + 10_000;
+ while (session.relayAddresses.length > 0 && Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ assert.equal(session.relayAddresses.length, 0, "the reservation should go with the connection");
+
+ while ((session.relayAddresses.length === 0 || handshakes.length < 2) && Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ assert.deepEqual(session.relayAddresses.map(String), reserved, "the relayed address is back");
+ // Once on the connection js-libp2p reopened, once ahead of the new
+ // reservation; both are the member, and both after the drop.
+ assert.ok(handshakes.length >= 2, "the member authenticated again before reserving");
+ assert.ok(handshakes.every((p) => p === mesh.peerId));
+
+ // And a peer reaches the member through the router as before.
+ const peer = await createLibp2p({
+ transports: [tcp(), circuitRelayTransport()],
+ connectionEncrypters: [tls()],
+ streamMuxers: [yamux()],
+ services: { identify: identify() },
+ });
+ try {
+ const conn = await peer.dial(multiaddr(reserved[0] as string));
+ assert.equal(conn.remotePeer.toString(), mesh.peerId);
+ } finally {
+ await peer.stop();
+ }
+ } finally {
+ await session.close();
+ }
+ } finally {
+ await strict.stop();
+ }
+});
+
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({
diff --git a/sdk/js/src/session.ts b/sdk/js/src/session.ts
index 748f1586..18c994b1 100644
--- a/sdk/js/src/session.ts
+++ b/sdk/js/src/session.ts
@@ -21,7 +21,7 @@ import { AUTH_HANDLER_OPTIONS, AUTH_PROTOCOL, authenticateWithPeer, authStreamHa
import { ROLE_ROUTER, requireRole, type VerifiedBiscuit } from "./biscuit.ts";
import { canonicalPeerId } from "./identity.ts";
import { isServiceType, parseServiceTarget, serviceCID } from "./discovery.ts";
-import { createMeshHost, listenThroughRelay, type MeshHost, type MeshHostOptions } from "./host.ts";
+import { createMeshHost, listenThroughRelay, type MeshHost, type MeshHostOptions, type RelayListener } from "./host.ts";
import { openMCPSession, type MCPSession, type MCPSessionOptions } from "./mcp.ts";
import type { AgentMesh, ControlPlaneSync } from "./mesh.ts";
import {
@@ -62,6 +62,12 @@ export interface JoinOptions extends MeshHostOptions {
controlPlaneSyncIntervalMs?: number;
/** Upper bound of the random delay before a pull an event triggered. */
controlPlaneSyncJitterMs?: number;
+ /**
+ * How often the relay reservation is checked while reserveRelay is on: a
+ * router that restarted or trimmed the connection dropped it, and this is
+ * how long the member is unreachable at most before it reserves again.
+ */
+ relayCheckIntervalMs?: number;
/** Bounds the whole join. */
signal?: AbortSignal;
}
@@ -116,6 +122,7 @@ const DEFAULT_POLICY_SYNC_MS = 15 * 60 * 1000;
const DEFAULT_CONTROL_PLANE_SYNC_MS = 15 * 60 * 1000;
const FIRST_CONTROL_PLANE_SYNC_MS = 2_000;
const DEFAULT_CONTROL_PLANE_SYNC_JITTER_MS = 2_000;
+const DEFAULT_RELAY_CHECK_MS = 30 * 1000;
/**
* A member that is on the mesh: a libp2p host authenticated with at least
@@ -135,7 +142,10 @@ export class MeshSession {
#refreshTimer: ReturnType<typeof setTimeout> | undefined;
#policyTimer: ReturnType<typeof setInterval> | undefined;
#syncTimer: ReturnType<typeof setTimeout> | undefined;
+ #relayTimer: ReturnType<typeof setInterval> | undefined;
#syncing: Promise<ControlPlaneSync> | undefined;
+ #keepingRelay: Promise<void> | undefined;
+ readonly #relayListener: RelayListener | undefined;
readonly #refreshLeadMs: number;
readonly #refreshRetryMs: number;
readonly #policySyncMs: number;
@@ -144,12 +154,13 @@ export class MeshSession {
#policyRules: string[] | undefined;
#closed = false;
- constructor(mesh: AgentMesh, node: MeshHost, routers: AdmittedRouter[], authenticatedPeers: Map<string, Date>, banned: BanSet, options: JoinOptions) {
+ constructor(mesh: AgentMesh, node: MeshHost, routers: AdmittedRouter[], authenticatedPeers: Map<string, Date>, banned: BanSet, options: JoinOptions, relayListener?: RelayListener) {
this.mesh = mesh;
this.node = node;
this.routers = routers;
this.authenticatedPeers = authenticatedPeers;
this.banned = banned;
+ this.#relayListener = relayListener;
this.#refreshLeadMs = options.refreshLeadMs ?? DEFAULT_REFRESH_LEAD_MS;
this.#refreshRetryMs = options.refreshRetryMs ?? DEFAULT_REFRESH_RETRY_MS;
this.#policySyncMs = options.policySyncIntervalMs ?? DEFAULT_POLICY_SYNC_MS;
@@ -157,9 +168,14 @@ export class MeshSession {
this.#syncJitterMs = options.controlPlaneSyncJitterMs ?? DEFAULT_CONTROL_PLANE_SYNC_JITTER_MS;
this.#scheduleRefresh();
this.#listenForEvents();
+ this.#keepRouterAdmissions();
if (this.#syncIntervalMs > 0) {
this.#scheduleSync(Math.min(FIRST_CONTROL_PLANE_SYNC_MS, this.#syncIntervalMs));
}
+ if (relayListener !== undefined) {
+ this.#relayTimer = setInterval(() => void this.keepRelay().catch(() => {}), options.relayCheckIntervalMs ?? DEFAULT_RELAY_CHECK_MS);
+ this.#relayTimer.unref?.();
+ }
}
get peerId(): string {
@@ -190,6 +206,57 @@ export class MeshSession {
return this.node.getMultiaddrs().filter((ma) => ma.toString().includes("/p2p-circuit"));
}
+ /**
+ * A router forgets the admission with the connection it came on, and
+ * js-libp2p reconnects to a relay on its own, so every new connection to a
+ * router runs the handshake again: the relay's own renewal of the
+ * reservation then still passes the router's check.
+ */
+ #keepRouterAdmissions(): void {
+ const routers = new Set(this.routers.map((r) => r.peerId));
+ this.node.addEventListener("connection:open", (evt) => {
+ const conn = evt.detail;
+ if (this.#closed || !routers.has(conn.remotePeer.toString())) {
+ return;
+ }
+ void authenticateWithPeer(conn, this.mesh.authFrame(), this.mesh.credential.controlPlaneKeys).catch(() => {});
+ });
+ }
+
+ /**
+ * Makes sure this member holds a relay reservation when it asked for one
+ * at join: a router that restarted or trimmed the connection dropped it
+ * and with it the relayed address peers reach this member on. Routers are
+ * tried in order, each dialed and authenticated again first, since the
+ * router forgot the admission with the connection. Runs on
+ * relayCheckIntervalMs; exposed so a caller can force it. Concurrent
+ * calls share one attempt.
+ */
+ keepRelay(): Promise<void> {
+ this.#keepingRelay ??= this.#keepRelayOnce().finally(() => {
+ this.#keepingRelay = undefined;
+ });
+ return this.#keepingRelay;
+ }
+
+ async #keepRelayOnce(): Promise<void> {
+ if (this.#relayListener === undefined || this.#closed || this.relayAddresses.length > 0) {
+ return;
+ }
+ const failures: string[] = [];
+ for (const r of this.routers) {
+ try {
+ const conn = await this.node.dial(r.addr);
+ await authenticateWithPeer(conn, this.mesh.authFrame(), this.mesh.credential.controlPlaneKeys);
+ await this.#relayListener.listen(r.addr.encapsulate("/p2p-circuit"));
+ return;
+ } catch (err) {
+ failures.push(`${r.peerId}: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }
+ throw new Error(`no router granted a relay reservation:\n ${failures.join("\n ")}`);
+ }
+
/**
* Connects to a peer; see Peer for how it is named. Returns the
* connection, reused if one is already open. A banned peer is refused
@@ -525,6 +592,7 @@ export class MeshSession {
clearTimeout(this.#refreshTimer);
clearTimeout(this.#syncTimer);
clearInterval(this.#policyTimer);
+ clearInterval(this.#relayTimer);
await this.node.stop();
}
}
@@ -574,15 +642,15 @@ export async function joinMesh(mesh: AgentMesh, options: JoinOptions = {}): Prom
throw new Error(`no router admitted this member:\n ${failures.join("\n ")}`);
}
+ let relayListener: RelayListener | undefined;
if (options.reserveRelay ?? true) {
- await listenThroughRelay(node, (admitted[0] as AdmittedRouter).addr);
+ relayListener = await listenThroughRelay(node, (admitted[0] as AdmittedRouter).addr);
}
+ return new MeshSession(mesh, node, admitted, authenticatedPeers, banned, options, relayListener);
} catch (err) {
await Promise.resolve(node.stop()).catch(() => {});
throw err;
}
-
- return new MeshSession(mesh, node, admitted, authenticatedPeers, banned, options);
}
/** The peer a multiaddr ends at, in canonical form: its trailing `/p2p/<id>`, or undefined for a relay address with no target yet. */