Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
Rename hub references to control plane and router
Tomas Tormo2ab03be86e09
diff --git a/.github/k8s/sam-box-canary-template.yaml b/.github/k8s/sam-box-canary-template.yamlindex c7a4465c..d95b43ba 100644--- a/.github/k8s/sam-box-canary-template.yaml+++ b/.github/k8s/sam-box-canary-template.yaml@@ -67,7 +67,7 @@ spec:- "--uds-path=/var/run/sam/sam-box.sock"- "--config=/etc/sam/sam-node.yaml"- "--secrets-file=/etc/sam/secrets.yaml"- - "--hub=http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"+ - "--control-plane=http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"- "--jwt-path=/var/run/secrets/tokens/sam-token"- "--allow-loopback"- "--log-level=debug"diff --git a/.github/k8s/sam-console-template.yaml b/.github/k8s/sam-console-template.yamlindex 25cb5e93..7c238d8f 100644--- a/.github/k8s/sam-console-template.yaml+++ b/.github/k8s/sam-console-template.yaml@@ -32,7 +32,7 @@ spec:image: ghcr.io/google/sam-console:${IMAGE_TAG}imagePullPolicy: IfNotPresentargs:- - "--hub=http://sam-control-plane-${ENV_NAME}:8080"+ - "--control-plane=http://sam-control-plane-${ENV_NAME}:8080"- "--bind-addr=:8081"- "--static-dir=/app/public"- "--admin-token=$(SAM_ADMIN_TOKEN)"diff --git a/.github/k8s/sam-node-cop-template.yaml b/.github/k8s/sam-node-cop-template.yamlindex aef67a9f..fce837c9 100644--- a/.github/k8s/sam-node-cop-template.yaml+++ b/.github/k8s/sam-node-cop-template.yaml@@ -63,7 +63,7 @@ spec:args:- "run"- "--config=/etc/sam/sam-node.yaml"- - "--hub=http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"+ - "--control-plane=http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"- "--jwt-path=/var/run/secrets/tokens/sam-token"- "--api-token=secret-token"- "--bind-addr=127.0.0.1:8080"diff --git a/.github/k8s/sam-node-everything-template.yaml b/.github/k8s/sam-node-everything-template.yamlindex 30dd5631..aeb621ee 100644--- a/.github/k8s/sam-node-everything-template.yaml+++ b/.github/k8s/sam-node-everything-template.yaml@@ -51,7 +51,7 @@ spec:args:- "run"- "--config=/etc/sam/sam-node.yaml"- - "--hub=http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"+ - "--control-plane=http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"- "--jwt-path=/var/run/secrets/tokens/sam-token"- "--api-token=secret-token"- "--bind-addr=127.0.0.1:8080"diff --git a/.github/k8s/sam-node-openclaw-template.yaml b/.github/k8s/sam-node-openclaw-template.yamlindex 2a49a6f3..dc37fa08 100644--- a/.github/k8s/sam-node-openclaw-template.yaml+++ b/.github/k8s/sam-node-openclaw-template.yaml@@ -107,7 +107,7 @@ spec:args:- "run"- "--config=/etc/sam/sam-node.yaml"- - "--hub=http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"+ - "--control-plane=http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"- "--jwt-path=/var/run/secrets/tokens/sam-token"- "--api-token=secret-token"- "--bind-addr=127.0.0.1:8080"diff --git a/.github/k8s/sam-node-openrouter-template.yaml b/.github/k8s/sam-node-openrouter-template.yamlindex 3a5941ec..c29b1d9f 100644--- a/.github/k8s/sam-node-openrouter-template.yaml+++ b/.github/k8s/sam-node-openrouter-template.yaml@@ -57,7 +57,7 @@ spec:args:- "run"- "--config=/etc/sam/sam-node.yaml"- - "--hub=http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"+ - "--control-plane=http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"- "--jwt-path=/var/run/secrets/tokens/sam-token"- "--api-token=secret-token"- "--bind-addr=127.0.0.1:8080"diff --git a/.github/k8s/sam-node-template.yaml b/.github/k8s/sam-node-template.yamlindex c03a95a2..b3228b78 100644--- a/.github/k8s/sam-node-template.yaml+++ b/.github/k8s/sam-node-template.yaml@@ -45,7 +45,7 @@ spec:args:- "run"- "--config=/etc/sam/sam-node.yaml"- - "--hub=http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"+ - "--control-plane=http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"- "--jwt-path=/var/run/secrets/tokens/sam-token"- "--api-token=secret-token"ports:diff --git a/.github/k8s/sam-node-vllm-template.yaml b/.github/k8s/sam-node-vllm-template.yamlindex 81abbfad..f654b9ce 100644--- a/.github/k8s/sam-node-vllm-template.yaml+++ b/.github/k8s/sam-node-vllm-template.yaml@@ -100,7 +100,7 @@ spec:args:- "run"- "--config=/etc/sam/sam-node.yaml"- - "--hub=http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"+ - "--control-plane=http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"- "--jwt-path=/var/run/secrets/tokens/sam-token"- "--api-token=secret-token"- "--bind-addr=127.0.0.1:8080"diff --git a/AGENTS.md b/AGENTS.mdindex 16114e45..51b0ee3c 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -3,9 +3,9 @@You are an expert software engineering assistant helping to develop, maintain, and test the **SAM** repository.## 1. Architecture & Component Independence-* **Decoupled Architecture:** The `sam-hub` and `sam-node` components are strictly independent. They must not share internal state or tightly couple their logic.-* **API Communication:** All data communication between `sam-hub` and `sam-node` must happen exclusively via the common API defined in `api/sam.proto`.-* **Zero Trust:** Enforce a Zero Trust architecture. Assume no implicit trust between nodes, hubs, or external actors. All data passing through the API must be authenticated, authorized, and validated.+* **Decoupled Architecture:** The `sam-control-plane`, `sam-router` and `sam-node` components are strictly independent. They must not share internal state or tightly couple their logic.+* **API Communication:** All data communication between `sam-control-plane`, `sam-router` and `sam-node` must happen exclusively via the common API defined in `api/sam.proto`.+* **Zero Trust:** Enforce a Zero Trust architecture. Assume no implicit trust between nodes, control planes, routers, or external actors. All data passing through the API must be authenticated, authorized, and validated.* **Simple UX:** Maintain a very simple User Experience. Configuration, CLI usage, and error messages must be intuitive, minimal, and explicitly clear.## 2. Dependency Management (Strict Constraint)diff --git a/README.md b/README.mdindex 3f655515..0088f4ba 100644--- a/README.md+++ b/README.md@@ -31,7 +31,7 @@ Get a node running on the public testnet (`bananas.sam-mesh.dev`) in minutes:### For Developers & ContributorsCompile from source, run local clusters, or execute tests:-- 🛠️ **[Developer Guide](site/content/docs/development/_index.md)**: Prereqs, compilation, local hub setup, and Kubernetes Kind deployment.+- 🛠️ **[Developer Guide](site/content/docs/development/_index.md)**: Prereqs, compilation, local control plane setup, and Kubernetes Kind deployment.- 🧪 **[Testing Guide](site/content/docs/development/testing.md)**: Go tests, E2E BATS, and containerized mesh execution.---diff --git a/agents/skills/sam/SKILL.md b/agents/skills/sam/SKILL.mdindex d9dd6292..ac63ed16 100644--- a/agents/skills/sam/SKILL.md+++ b/agents/skills/sam/SKILL.md@@ -14,7 +14,7 @@ the capability needed to complete the task.Start by understanding the local node and mesh state:- Use `get_mesh_info` with `{}` to inspect `connected_peers`, `dht_size`, and- `hub_peer_id`.+ `router_peer_id`.- Use `list_local_services` with `{}` to see services registered on the localnode.diff --git a/api/datalog.go b/api/datalog.goindex 5f77c8e9..82f6253f 100644--- a/api/datalog.go+++ b/api/datalog.go@@ -33,7 +33,7 @@ import (//// 1. Replay Defense Facts:// - client_peer_id: The libp2p PeerID of the node that authenticated with the-// Hub to request this token. Embedded in the token authority block.+// control plane to request this token. Embedded in the token authority block.// - connection_peer_id: The libp2p PeerID of the caller initiating the connection// to the receiving node. Injected dynamically at runtime by the receiver.// - Replay Check: Verified using the check:@@ -46,7 +46,7 @@ import (// runtime from OIDC claims or node authentication.// - allow_network_target: Derived fact generated on the receiver node by matching// target_fact against the token's allowed targets (e.g., granted_target_exact).-// - target_unrestricted: Fact injected in the token by the Hub indicating that+// - target_unrestricted: Fact injected in the token by the control plane indicating that// the client has unrestricted network access and bypasses target constraints.// - Target Check: Verified using the check:// `check if allow_network_target($fact, $val) or target_unrestricted()`@@ -233,8 +233,8 @@ var (// TargetFactRules maps node and OIDC claims to target_fact datalog facts.TargetFactRules []biscuit.Rule- // HubStaticTimeCheck is the standard check for verifying OIDC token expiration.- HubStaticTimeCheck biscuit.Check+ // ControlPlaneStaticTimeCheck is the standard check for verifying OIDC token expiration.+ ControlPlaneStaticTimeCheck biscuit.Check// AllowIfTruePolicy is the static policy "allow if true" used during token verification.AllowIfTruePolicy biscuit.Policy@@ -277,7 +277,7 @@ func init() {}// 2. Target Evaluation Rules- // These rules satisfy the check if allow_network_target($fact, $val) injected by the Hub.+ // These rules satisfy the check if allow_network_target($fact, $val) injected by the control plane.ruleStrs := []string{// Exact Match: Derives allow_network_target if the token has a granted_target_exact fact matching a target_fact exactly.fmt.Sprintf(`%s($fact, $val) <- %s($fact, $val), %s($fact, $val)`, FactAllowNetworkTarget, FactTargetFact, FactGrantedTargetExact),@@ -309,7 +309,7 @@ func init() {var err error- // BaselineReplayCheck prevents token theft/replay by ensuring the client_peer_id fact (embedded by the Hub during issuance)+ // BaselineReplayCheck prevents token theft/replay by ensuring the client_peer_id fact (embedded by the control plane during issuance)// perfectly matches the connection_peer_id fact (provided by the local node verifying the incoming libp2p connection).BaselineReplayCheck, err = parser.FromStringCheck(fmt.Sprintf(`check if %s($id), %s($id)`, FactClientPeerID, FactConnectionPeerID))if err != nil {@@ -341,8 +341,8 @@ func init() {}TargetFactRules = append(TargetFactRules, r)- // HubStaticTimeCheck ensures the token is not expired at the time of evaluation.- HubStaticTimeCheck, err = parser.FromStringCheck(fmt.Sprintf(`check if %s($time), %s($exp), $time <= $exp`, FactTime, FactExpiration))+ // ControlPlaneStaticTimeCheck ensures the token is not expired at the time of evaluation.+ ControlPlaneStaticTimeCheck, err = parser.FromStringCheck(fmt.Sprintf(`check if %s($time), %s($exp), $time <= $exp`, FactTime, FactExpiration))if err != nil {panic(fmt.Sprintf("failed to parse static time check: %v", err))}@@ -350,7 +350,7 @@ func init() {// AllowIfTruePolicy is a permissive fallback policy used when explicit local node policies are omitted.// Note that this does NOT mean all requests are automatically allowed. Biscuit requires at least one policy// to evaluate to true AND all checks to pass. This simply satisfies the policy requirement, effectively- // deferring entirely to the Hub's checks and granted facts without imposing extra local restrictions.+ // deferring entirely to the control plane's checks and granted facts without imposing extra local restrictions.AllowIfTruePolicy, err = parser.FromStringPolicy("allow if true")if err != nil {panic(fmt.Sprintf("failed to parse static allow policy: %v", err))diff --git a/api/datalog_test.go b/api/datalog_test.goindex c3b299e5..320159d1 100644--- a/api/datalog_test.go+++ b/api/datalog_test.go@@ -301,7 +301,7 @@ func TestBaselineTargetCheck(t *testing.T) {}}-func TestHubStaticTimeCheck(t *testing.T) {+func TestControlPlaneStaticTimeCheck(t *testing.T) {pub, priv := makeKeyPair(t)tests := []struct {@@ -340,7 +340,7 @@ func TestHubStaticTimeCheck(t *testing.T) {IDs: []biscuit.Term{biscuit.Date(tt.timeNow)},}})- authorizer.AddCheck(HubStaticTimeCheck)+ authorizer.AddCheck(ControlPlaneStaticTimeCheck)authorizer.AddPolicy(AllowIfTruePolicy)err := authorizer.Authorize()diff --git a/api/network.go b/api/network.goindex 42dc8a12..0baa0b66 100644--- a/api/network.go+++ b/api/network.go@@ -40,8 +40,8 @@ const (// GossipEvents is the GossipSub topic used to broadcast mesh event updates (e.g., node bans).GossipEvents = "/sam/mesh/events/v1"- // GossipHubSync is the GossipSub topic used by the Hub to sync cluster state.- GossipHubSync = "/sam/hub/sync/v1"+ // GossipControlPlaneSync is the GossipSub topic used by the control plane to sync cluster state.+ GossipControlPlaneSync = "/sam/control-plane/sync/v1"// DefaultAudience is the default audience string used in OIDC token validation.DefaultAudience = "sam-mesh-audience"diff --git a/api/sam.pb.go b/api/sam.pb.goindex ecd03c30..e7a2a35e 100644--- a/api/sam.pb.go+++ b/api/sam.pb.go@@ -442,14 +442,14 @@ func (x *EnrollRequest) GetRequestedRole() string {}type EnrollResponse struct {- state protoimpl.MessageState `protogen:"open.v1"`- BiscuitToken []byte `protobuf:"bytes,1,opt,name=biscuit_token,json=biscuitToken,proto3" json:"biscuit_token,omitempty"`- ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"`- HubPublicKey []byte `protobuf:"bytes,3,opt,name=hub_public_key,json=hubPublicKey,proto3" json:"hub_public_key,omitempty"`- HubAddresses []string `protobuf:"bytes,4,rep,name=hub_addresses,json=hubAddresses,proto3" json:"hub_addresses,omitempty"`- Expiration int64 `protobuf:"varint,5,opt,name=expiration,proto3" json:"expiration,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ state protoimpl.MessageState `protogen:"open.v1"`+ BiscuitToken []byte `protobuf:"bytes,1,opt,name=biscuit_token,json=biscuitToken,proto3" json:"biscuit_token,omitempty"`+ ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"`+ ControlPlanePublicKey []byte `protobuf:"bytes,3,opt,name=control_plane_public_key,json=controlPlanePublicKey,proto3" json:"control_plane_public_key,omitempty"`+ RouterAddresses []string `protobuf:"bytes,4,rep,name=router_addresses,json=routerAddresses,proto3" json:"router_addresses,omitempty"`+ Expiration int64 `protobuf:"varint,5,opt,name=expiration,proto3" json:"expiration,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *EnrollResponse) Reset() {@@ -496,16 +496,16 @@ func (x *EnrollResponse) GetErrorMessage() string {return ""}-func (x *EnrollResponse) GetHubPublicKey() []byte {+func (x *EnrollResponse) GetControlPlanePublicKey() []byte {if x != nil {- return x.HubPublicKey+ return x.ControlPlanePublicKey}return nil}-func (x *EnrollResponse) GetHubAddresses() []string {+func (x *EnrollResponse) GetRouterAddresses() []string {if x != nil {- return x.HubAddresses+ return x.RouterAddresses}return nil}@@ -630,16 +630,16 @@ func (x *BootstrapEnrollRequest) GetRequestedRole() string {}type BootstrapEnrollResponse struct {- state protoimpl.MessageState `protogen:"open.v1"`- Status EnrollmentStatus `protobuf:"varint,1,opt,name=status,proto3,enum=sam.v1.EnrollmentStatus" json:"status,omitempty"`- BiscuitToken []byte `protobuf:"bytes,2,opt,name=biscuit_token,json=biscuitToken,proto3" json:"biscuit_token,omitempty"` // Populated only if APPROVED- PollIntervalSeconds int32 `protobuf:"varint,3,opt,name=poll_interval_seconds,json=pollIntervalSeconds,proto3" json:"poll_interval_seconds,omitempty"` // Recommended polling wait time- ErrorMessage string `protobuf:"bytes,4,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"`- HubPublicKey []byte `protobuf:"bytes,5,opt,name=hub_public_key,json=hubPublicKey,proto3" json:"hub_public_key,omitempty"` // Populated only if APPROVED- HubAddresses []string `protobuf:"bytes,6,rep,name=hub_addresses,json=hubAddresses,proto3" json:"hub_addresses,omitempty"` // Populated only if APPROVED- Expiration int64 `protobuf:"varint,7,opt,name=expiration,proto3" json:"expiration,omitempty"` // Populated only if APPROVED- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ state protoimpl.MessageState `protogen:"open.v1"`+ Status EnrollmentStatus `protobuf:"varint,1,opt,name=status,proto3,enum=sam.v1.EnrollmentStatus" json:"status,omitempty"`+ BiscuitToken []byte `protobuf:"bytes,2,opt,name=biscuit_token,json=biscuitToken,proto3" json:"biscuit_token,omitempty"` // Populated only if APPROVED+ PollIntervalSeconds int32 `protobuf:"varint,3,opt,name=poll_interval_seconds,json=pollIntervalSeconds,proto3" json:"poll_interval_seconds,omitempty"` // Recommended polling wait time+ ErrorMessage string `protobuf:"bytes,4,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"`+ ControlPlanePublicKey []byte `protobuf:"bytes,5,opt,name=control_plane_public_key,json=controlPlanePublicKey,proto3" json:"control_plane_public_key,omitempty"` // Populated only if APPROVED+ RouterAddresses []string `protobuf:"bytes,6,rep,name=router_addresses,json=routerAddresses,proto3" json:"router_addresses,omitempty"` // Populated only if APPROVED+ Expiration int64 `protobuf:"varint,7,opt,name=expiration,proto3" json:"expiration,omitempty"` // Populated only if APPROVED+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *BootstrapEnrollResponse) Reset() {@@ -700,16 +700,16 @@ func (x *BootstrapEnrollResponse) GetErrorMessage() string {return ""}-func (x *BootstrapEnrollResponse) GetHubPublicKey() []byte {+func (x *BootstrapEnrollResponse) GetControlPlanePublicKey() []byte {if x != nil {- return x.HubPublicKey+ return x.ControlPlanePublicKey}return nil}-func (x *BootstrapEnrollResponse) GetHubAddresses() []string {+func (x *BootstrapEnrollResponse) GetRouterAddresses() []string {if x != nil {- return x.HubAddresses+ return x.RouterAddresses}return nil}@@ -991,30 +991,30 @@ func (x *DiscoveredProvider) GetSrvDescription() string {return ""}-type HubInfoResponse struct {- state protoimpl.MessageState `protogen:"open.v1"`- OidcIssuer string `protobuf:"bytes,1,opt,name=oidc_issuer,json=oidcIssuer,proto3" json:"oidc_issuer,omitempty"`- ClientId string `protobuf:"bytes,2,opt,name=client_id,json=clientId,proto3" json:"client_id,omitempty"`- Audience string `protobuf:"bytes,3,opt,name=audience,proto3" json:"audience,omitempty"`- HubAddresses []string `protobuf:"bytes,4,rep,name=hub_addresses,json=hubAddresses,proto3" json:"hub_addresses,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+type ControlPlaneInfoResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ OidcIssuer string `protobuf:"bytes,1,opt,name=oidc_issuer,json=oidcIssuer,proto3" json:"oidc_issuer,omitempty"`+ ClientId string `protobuf:"bytes,2,opt,name=client_id,json=clientId,proto3" json:"client_id,omitempty"`+ Audience string `protobuf:"bytes,3,opt,name=audience,proto3" json:"audience,omitempty"`+ RouterAddresses []string `protobuf:"bytes,4,rep,name=router_addresses,json=routerAddresses,proto3" json:"router_addresses,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}-func (x *HubInfoResponse) Reset() {- *x = HubInfoResponse{}+func (x *ControlPlaneInfoResponse) Reset() {+ *x = ControlPlaneInfoResponse{}mi := &file_api_sam_proto_msgTypes[12]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}-func (x *HubInfoResponse) String() string {+func (x *ControlPlaneInfoResponse) String() string {return protoimpl.X.MessageStringOf(x)}-func (*HubInfoResponse) ProtoMessage() {}+func (*ControlPlaneInfoResponse) ProtoMessage() {}-func (x *HubInfoResponse) ProtoReflect() protoreflect.Message {+func (x *ControlPlaneInfoResponse) ProtoReflect() protoreflect.Message {mi := &file_api_sam_proto_msgTypes[12]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))@@ -1026,35 +1026,35 @@ func (x *HubInfoResponse) ProtoReflect() protoreflect.Message {return mi.MessageOf(x)}-// Deprecated: Use HubInfoResponse.ProtoReflect.Descriptor instead.-func (*HubInfoResponse) Descriptor() ([]byte, []int) {+// Deprecated: Use ControlPlaneInfoResponse.ProtoReflect.Descriptor instead.+func (*ControlPlaneInfoResponse) Descriptor() ([]byte, []int) {return file_api_sam_proto_rawDescGZIP(), []int{12}}-func (x *HubInfoResponse) GetOidcIssuer() string {+func (x *ControlPlaneInfoResponse) GetOidcIssuer() string {if x != nil {return x.OidcIssuer}return ""}-func (x *HubInfoResponse) GetClientId() string {+func (x *ControlPlaneInfoResponse) GetClientId() string {if x != nil {return x.ClientId}return ""}-func (x *HubInfoResponse) GetAudience() string {+func (x *ControlPlaneInfoResponse) GetAudience() string {if x != nil {return x.Audience}return ""}-func (x *HubInfoResponse) GetHubAddresses() []string {+func (x *ControlPlaneInfoResponse) GetRouterAddresses() []string {if x != nil {- return x.HubAddresses+ return x.RouterAddresses}return nil}@@ -1787,12 +1787,12 @@ const file_api_sam_proto_rawDesc = "" +"\apeer_id\x18\x02 \x01(\tR\x06peerId\x12\x1d\n" +"\n" +"public_key\x18\x03 \x01(\fR\tpublicKey\x12%\n" +- "\x0erequested_role\x18\x04 \x01(\tR\rrequestedRole\"\xc5\x01\n" ++ "\x0erequested_role\x18\x04 \x01(\tR\rrequestedRole\"\xde\x01\n" +"\x0eEnrollResponse\x12#\n" +"\rbiscuit_token\x18\x01 \x01(\fR\fbiscuitToken\x12#\n" +- "\rerror_message\x18\x02 \x01(\tR\ferrorMessage\x12$\n" +- "\x0ehub_public_key\x18\x03 \x01(\fR\fhubPublicKey\x12#\n" +- "\rhub_addresses\x18\x04 \x03(\tR\fhubAddresses\x12\x1e\n" ++ "\rerror_message\x18\x02 \x01(\tR\ferrorMessage\x127\n" ++ "\x18control_plane_public_key\x18\x03 \x01(\fR\x15controlPlanePublicKey\x12)\n" ++ "\x10router_addresses\x18\x04 \x03(\tR\x0frouterAddresses\x12\x1e\n" +"\n" +"expiration\x18\x05 \x01(\x03R\n" +"expiration\"2\n" +@@ -1803,14 +1803,14 @@ const file_api_sam_proto_rawDesc = "" +"\apeer_id\x18\x02 \x01(\tR\x06peerId\x12\x1d\n" +"\n" +"public_key\x18\x03 \x01(\fR\tpublicKey\x12%\n" +- "\x0erequested_role\x18\x04 \x01(\tR\rrequestedRole\"\xb4\x02\n" ++ "\x0erequested_role\x18\x04 \x01(\tR\rrequestedRole\"\xcd\x02\n" +"\x17BootstrapEnrollResponse\x120\n" +"\x06status\x18\x01 \x01(\x0e2\x18.sam.v1.EnrollmentStatusR\x06status\x12#\n" +"\rbiscuit_token\x18\x02 \x01(\fR\fbiscuitToken\x122\n" +"\x15poll_interval_seconds\x18\x03 \x01(\x05R\x13pollIntervalSeconds\x12#\n" +- "\rerror_message\x18\x04 \x01(\tR\ferrorMessage\x12$\n" +- "\x0ehub_public_key\x18\x05 \x01(\fR\fhubPublicKey\x12#\n" +- "\rhub_addresses\x18\x06 \x03(\tR\fhubAddresses\x12\x1e\n" ++ "\rerror_message\x18\x04 \x01(\tR\ferrorMessage\x127\n" ++ "\x18control_plane_public_key\x18\x05 \x01(\fR\x15controlPlanePublicKey\x12)\n" ++ "\x10router_addresses\x18\x06 \x03(\tR\x0frouterAddresses\x12\x1e\n" +"\n" +"expiration\x18\a \x01(\x03R\n" +"expiration\"l\n" +@@ -1834,13 +1834,13 @@ const file_api_sam_proto_rawDesc = "" +"\apeer_id\x18\x01 \x01(\tR\x06peerId\x12&\n" +"\x0flocal_proxy_url\x18\x02 \x01(\tR\rlocalProxyUrl\x12\x19\n" +"\bsrv_name\x18\x03 \x01(\tR\asrvName\x12'\n" +- "\x0fsrv_description\x18\x04 \x01(\tR\x0esrvDescription\"\x90\x01\n" +- "\x0fHubInfoResponse\x12\x1f\n" ++ "\x0fsrv_description\x18\x04 \x01(\tR\x0esrvDescription\"\x9f\x01\n" ++ "\x18ControlPlaneInfoResponse\x12\x1f\n" +"\voidc_issuer\x18\x01 \x01(\tR\n" +"oidcIssuer\x12\x1b\n" +"\tclient_id\x18\x02 \x01(\tR\bclientId\x12\x1a\n" +- "\baudience\x18\x03 \x01(\tR\baudience\x12#\n" +- "\rhub_addresses\x18\x04 \x03(\tR\fhubAddresses\"\xa9\x01\n" ++ "\baudience\x18\x03 \x01(\tR\baudience\x12)\n" ++ "\x10router_addresses\x18\x04 \x03(\tR\x0frouterAddresses\"\xa9\x01\n" +"\x12RouterLeaseRequest\x12\x17\n" +"\apeer_id\x18\x01 \x01(\tR\x06peerId\x12\x1c\n" +"\taddresses\x18\x02 \x03(\tR\taddresses\x12\x18\n" +@@ -1927,7 +1927,7 @@ var file_api_sam_proto_goTypes = []any{(*CommandBackend)(nil), // 12: sam.v1.CommandBackend(*RegisterServiceRequest)(nil), // 13: sam.v1.RegisterServiceRequest(*DiscoveredProvider)(nil), // 14: sam.v1.DiscoveredProvider- (*HubInfoResponse)(nil), // 15: sam.v1.HubInfoResponse+ (*ControlPlaneInfoResponse)(nil), // 15: sam.v1.ControlPlaneInfoResponse(*RouterLeaseRequest)(nil), // 16: sam.v1.RouterLeaseRequest(*RouterLeaseResponse)(nil), // 17: sam.v1.RouterLeaseResponse(*PolicyRole)(nil), // 18: sam.v1.PolicyRolediff --git a/api/sam.proto b/api/sam.protoindex 1a73a1e4..d5f1413e 100644--- a/api/sam.proto+++ b/api/sam.proto@@ -54,8 +54,8 @@ message EnrollRequest {message EnrollResponse {bytes biscuit_token = 1;string error_message = 2;- bytes hub_public_key = 3;- repeated string hub_addresses = 4;+ bytes control_plane_public_key = 3;+ repeated string router_addresses = 4;int64 expiration = 5;}@@ -82,8 +82,8 @@ message BootstrapEnrollResponse {bytes biscuit_token = 2; // Populated only if APPROVEDint32 poll_interval_seconds = 3; // Recommended polling wait timestring error_message = 4;- bytes hub_public_key = 5; // Populated only if APPROVED- repeated string hub_addresses = 6; // Populated only if APPROVED+ bytes control_plane_public_key = 5; // Populated only if APPROVED+ repeated string router_addresses = 6; // Populated only if APPROVEDint64 expiration = 7; // Populated only if APPROVED}@@ -121,11 +121,11 @@ message DiscoveredProvider {string srv_description = 4;}-message HubInfoResponse {+message ControlPlaneInfoResponse {string oidc_issuer = 1;string client_id = 2;string audience = 3;- repeated string hub_addresses = 4;+ repeated string router_addresses = 4;}message RouterLeaseRequest {diff --git a/charts/sam-mesh/templates/console-deployment.yaml b/charts/sam-mesh/templates/console-deployment.yamlindex 2d9b2898..54d5b01f 100644--- a/charts/sam-mesh/templates/console-deployment.yaml+++ b/charts/sam-mesh/templates/console-deployment.yaml@@ -55,7 +55,7 @@ spec:resources:{{- toYaml .Values.console.resources | nindent 10 }}args:- - "--hub=http://{{ include "sam-mesh.fullname" . }}-control-plane:{{ .Values.controlPlane.service.port }}"+ - "--control-plane=http://{{ include "sam-mesh.fullname" . }}-control-plane:{{ .Values.controlPlane.service.port }}"- "--bind-addr=:8081"- "--static-dir=/app/public"- "--admin-token=$(ADMIN_TOKEN)"diff --git a/charts/sam-mesh/templates/dex-deployment.yaml b/charts/sam-mesh/templates/dex-deployment.yamlindex f4a0a614..8f6a65a7 100644--- a/charts/sam-mesh/templates/dex-deployment.yaml+++ b/charts/sam-mesh/templates/dex-deployment.yaml@@ -46,7 +46,7 @@ spec:app: {{ include "sam-mesh.fullname" . }}-dexspec:nodeSelector:- sam-role: hub+ sam-role: control-planecontainers:- name: deximage: "{{ .Values.dex.image.repository }}:{{ .Values.dex.image.tag }}"diff --git a/cmd/sam-box/main.go b/cmd/sam-box/main.goindex 7e0f92df..664f4100 100644--- a/cmd/sam-box/main.go+++ b/cmd/sam-box/main.go@@ -51,33 +51,33 @@ func init() {}var (- hubAddr string- jwtFlag string- jwtPathFlag string- bootstrapTokenFlag string- clientIDFlag string- clientSecretFlag string- hubPublicKeyFlag string- meshFlag string- discoveryIntervalFlag string- listenAddrs []string- enableRelayFlag bool- configFile string- oidcIssuerFlag string- deviceAuthURLFlag string- audienceFlag string- dataDirFlag string- headlessFlag bool- offlineAccessFlag bool- logLevelFlag string- keyGracePeriodFlag time.Duration- allowLoopbackFlag bool- monitorBootstrapFlag time.Duration- monitorCheckIntervalFlag time.Duration- autoRelayMinIntervalFlag time.Duration- autoRelayBootDelayFlag time.Duration- autoRelayBackoffFlag time.Duration- hubConnectTimeoutFlag time.Duration+ controlPlaneAddr string+ jwtFlag string+ jwtPathFlag string+ bootstrapTokenFlag string+ clientIDFlag string+ clientSecretFlag string+ controlPlanePublicKeyFlag string+ meshFlag string+ discoveryIntervalFlag string+ listenAddrs []string+ enableRelayFlag bool+ configFile string+ oidcIssuerFlag string+ deviceAuthURLFlag string+ audienceFlag string+ dataDirFlag string+ headlessFlag bool+ offlineAccessFlag bool+ logLevelFlag string+ keyGracePeriodFlag time.Duration+ allowLoopbackFlag bool+ monitorBootstrapFlag time.Duration+ monitorCheckIntervalFlag time.Duration+ autoRelayMinIntervalFlag time.Duration+ autoRelayBootDelayFlag time.Duration+ autoRelayBackoffFlag time.Duration+ routerConnectTimeoutFlag time.Duration// sam-box specific flagsudsPathFlag string@@ -128,24 +128,24 @@ func main() {}}()- var hubPubKey ed25519.PublicKey- var hubAddrs []multiaddr.Multiaddr+ var controlPlanePubKey ed25519.PublicKey+ var routerAddrs []multiaddr.Multiaddr- storedPubKey, syncedAddrs, err := node.SyncHubConfig(ctx, store)+ storedPubKey, syncedAddrs, err := node.SyncMeshConfig(ctx, store)if err != nil {- logger.Warnf("Failed to sync hub config: %v", err)+ logger.Warnf("Failed to sync mesh config: %v", err)}if len(storedPubKey) > 0 {- hubPubKey = storedPubKey- hubAddrs = syncedAddrs+ controlPlanePubKey = storedPubKey+ routerAddrs = syncedAddrs}- if hubPublicKeyFlag != "" {- pubBytes, err := hex.DecodeString(strings.TrimSpace(hubPublicKeyFlag))+ if controlPlanePublicKeyFlag != "" {+ pubBytes, err := hex.DecodeString(strings.TrimSpace(controlPlanePublicKeyFlag))if err != nil {- logger.Fatalf("Invalid hub public key: %v", err)+ logger.Fatalf("Invalid control plane public key: %v", err)}- hubPubKey = pubBytes+ controlPlanePubKey = pubBytes}var meshNode *node.SamNode@@ -176,16 +176,16 @@ func main() {if jwtStr == "" && bootstrapTokenFlag == "" {token, _ := store.LoadIdentity()if len(token) == 0 {- displayHub := hubAddr- if displayHub == "" {- if h, err := store.LoadHubURL(); err == nil && h != "" {- displayHub = h+ displayControlPlane := controlPlaneAddr+ if displayControlPlane == "" {+ if h, err := store.LoadControlPlaneURL(); err == nil && h != "" {+ displayControlPlane = h} else {- displayHub = "https://bananas.sam-mesh.dev"+ displayControlPlane = "https://bananas.sam-mesh.dev"}}logger.Infof("No identity found. Starting unauthenticated sidecar for enrollment over MCP...")- unauthSrv, err := node.StartUnauthSidecarServer(displayHub, "127.0.0.1:8080", "", "")+ unauthSrv, err := node.StartUnauthSidecarServer(displayControlPlane, "127.0.0.1:8080", "", "")if err != nil {logger.Fatalf("Failed to start unauthenticated sidecar: %v", err)}@@ -197,14 +197,14 @@ func main() {}logger.Infoln("Using stored identity.")- if len(hubPubKey) == 0 {- logger.Fatal("Hub public key not found in store and not provided. Cannot verify peers.")+ if len(controlPlanePubKey) == 0 {+ logger.Fatal("Control plane public key not found in store and not provided. Cannot verify peers.")}priv := node.GetOrGenerateKey(store)meshNode, err = node.NewSamNode(node.Options{PrivKey: priv,- HubPubKey: hubPubKey,- HubAddrs: hubAddrs,+ ControlPlanePubKey: controlPlanePubKey,+ RouterAddrs: routerAddrs,Store: store,MeshID: meshFlag,DiscoveryInterval: discoveryIntervalFlag,@@ -218,7 +218,7 @@ func main() {AutoRelayMinInterval: autoRelayMinIntervalFlag,AutoRelayBootDelay: autoRelayBootDelayFlag,AutoRelayBackoff: autoRelayBackoffFlag,- HubConnectTimeout: hubConnectTimeoutFlag,+ RouterConnectTimeout: routerConnectTimeoutFlag,RequiredRole: api.RoleSamBox,})if err != nil {@@ -229,13 +229,13 @@ func main() {}} else {// We have a new JWT (from flag or interactive login), need to enroll- var initHubAddrs []multiaddr.Multiaddr- if !strings.HasPrefix(hubAddr, "http://") && !strings.HasPrefix(hubAddr, "https://") {- ma, err := multiaddr.NewMultiaddr(hubAddr)+ var initRouterAddrs []multiaddr.Multiaddr+ if !strings.HasPrefix(controlPlaneAddr, "http://") && !strings.HasPrefix(controlPlaneAddr, "https://") {+ ma, err := multiaddr.NewMultiaddr(controlPlaneAddr)if err == nil {- initHubAddrs = []multiaddr.Multiaddr{ma}+ initRouterAddrs = []multiaddr.Multiaddr{ma}} else {- host, port, err := net.SplitHostPort(hubAddr)+ host, port, err := net.SplitHostPort(controlPlaneAddr)if err == nil {ip := net.ParseIP(host)var maddr multiaddr.Multiaddr@@ -248,9 +248,9 @@ func main() {if parseErr != nil {logger.Fatalf("Failed to parse multiaddr: %v", parseErr)}- initHubAddrs = []multiaddr.Multiaddr{maddr}+ initRouterAddrs = []multiaddr.Multiaddr{maddr}} else {- logger.Fatalf("Invalid hub address: %v", err)+ logger.Fatalf("Invalid control plane address: %v", err)}}}@@ -258,7 +258,7 @@ func main() {priv := node.GetOrGenerateKey(store)meshNode, err = node.NewSamNode(node.Options{PrivKey: priv,- HubAddrs: initHubAddrs,+ RouterAddrs: initRouterAddrs,Store: store,MeshID: meshFlag,DiscoveryInterval: discoveryIntervalFlag,@@ -272,7 +272,7 @@ func main() {AutoRelayMinInterval: autoRelayMinIntervalFlag,AutoRelayBootDelay: autoRelayBootDelayFlag,AutoRelayBackoff: autoRelayBackoffFlag,- HubConnectTimeout: hubConnectTimeoutFlag,+ RouterConnectTimeout: routerConnectTimeoutFlag,RequiredRole: api.RoleSamBox,})if err != nil {@@ -283,21 +283,21 @@ func main() {}if bootstrapTokenFlag != "" {- err = meshNode.EnrollBootstrap(ctx, hubAddr, bootstrapTokenFlag)+ err = meshNode.EnrollBootstrap(ctx, controlPlaneAddr, bootstrapTokenFlag)} else {- err = meshNode.Enroll(ctx, hubAddr, jwtStr)+ err = meshNode.Enroll(ctx, controlPlaneAddr, jwtStr)}if err != nil {logger.Fatalf("Enrollment failed: %v", err)}- if err := store.SaveHubURL(hubAddr); err != nil {- logger.Warnf("Failed to save hub URL: %v", err)+ if err := store.SaveControlPlaneURL(controlPlaneAddr); err != nil {+ logger.Warnf("Failed to save control plane URL: %v", err)}- logger.Infoln("Successfully enrolled with hub!")+ logger.Infoln("Successfully enrolled with control plane!")- if len(hubPubKey) == 0 {- if syncPubKey, _, err := node.SyncHubConfig(ctx, store); err != nil || len(syncPubKey) == 0 {- logger.Fatal("Hub public key not found in store after enrollment.")+ if len(controlPlanePubKey) == 0 {+ if syncPubKey, _, err := node.SyncMeshConfig(ctx, store); err != nil || len(syncPubKey) == 0 {+ logger.Fatal("Control plane public key not found in store after enrollment.")}}}@@ -357,14 +357,14 @@ func main() {Short: "Join the mesh interactively",Run: func(cmd *cobra.Command, args []string) {ctx := cmd.Context()- targetHub := hubAddr- if targetHub == "" {- targetHub = "https://bananas.sam-mesh.dev"+ targetControlPlane := controlPlaneAddr+ if targetControlPlane == "" {+ targetControlPlane = "https://bananas.sam-mesh.dev"}- if !strings.HasPrefix(targetHub, "http://") && !strings.HasPrefix(targetHub, "https://") {- targetHub = "https://" + targetHub+ if !strings.HasPrefix(targetControlPlane, "http://") && !strings.HasPrefix(targetControlPlane, "https://") {+ targetControlPlane = "https://" + targetControlPlane}- targetHub = strings.TrimSuffix(targetHub, "/")+ targetControlPlane = strings.TrimSuffix(targetControlPlane, "/")store, err := node.NewStore(resolveDataDir())if err != nil {@@ -381,37 +381,37 @@ func main() {}()dummyNode := &node.SamNode{Store: store}- fmt.Printf("Discovering hub info from %s...\n", targetHub)- hubInfo, err := node.FetchHubInfo(ctx, targetHub)+ fmt.Printf("Discovering control plane info from %s...\n", targetControlPlane)+ controlPlaneInfo, err := node.FetchControlPlaneInfo(ctx, targetControlPlane)if err != nil {- logger.Fatalf("Failed to discover hub info: %v", err)+ logger.Fatalf("Failed to discover control plane info: %v", err)}var jwtStr stringif bootstrapTokenFlag == "" {- fmt.Printf("OIDC Issuer discovered: %s\n", hubInfo.OidcIssuer)- fmt.Printf("Client ID discovered: %s\n", hubInfo.ClientId)+ fmt.Printf("OIDC Issuer discovered: %s\n", controlPlaneInfo.OidcIssuer)+ fmt.Printf("Client ID discovered: %s\n", controlPlaneInfo.ClientId)logger.Info("Discovering OIDC endpoints...")- tokenURL, authURL, err := dummyNode.DiscoverEndpoints(ctx, hubInfo.OidcIssuer)+ tokenURL, authURL, err := dummyNode.DiscoverEndpoints(ctx, controlPlaneInfo.OidcIssuer)if err != nil {logger.Fatalf("Failed to discover OIDC endpoints: %v", err)}- jwtStr, err = dummyNode.InteractiveLogin(ctx, authURL, tokenURL, hubInfo.ClientId, hubInfo.Audience, offlineAccessFlag, headlessFlag)+ jwtStr, err = dummyNode.InteractiveLogin(ctx, authURL, tokenURL, controlPlaneInfo.ClientId, controlPlaneInfo.Audience, offlineAccessFlag, headlessFlag)if err != nil {logger.Fatalf("Failed to get token: %v", err)}}- hubAddr = targetHub- var initHubAddrs []multiaddr.Multiaddr- if !strings.HasPrefix(hubAddr, "http://") && !strings.HasPrefix(hubAddr, "https://") {- ma, err := multiaddr.NewMultiaddr(hubAddr)+ controlPlaneAddr = targetControlPlane+ var initRouterAddrs []multiaddr.Multiaddr+ if !strings.HasPrefix(controlPlaneAddr, "http://") && !strings.HasPrefix(controlPlaneAddr, "https://") {+ ma, err := multiaddr.NewMultiaddr(controlPlaneAddr)if err == nil {- initHubAddrs = []multiaddr.Multiaddr{ma}+ initRouterAddrs = []multiaddr.Multiaddr{ma}} else {- host, port, err := net.SplitHostPort(hubAddr)+ host, port, err := net.SplitHostPort(controlPlaneAddr)if err == nil {ip := net.ParseIP(host)var maddr multiaddr.Multiaddr@@ -424,9 +424,9 @@ func main() {if parseErr != nil {logger.Fatalf("Failed to parse multiaddr: %v", parseErr)}- initHubAddrs = []multiaddr.Multiaddr{maddr}+ initRouterAddrs = []multiaddr.Multiaddr{maddr}} else {- logger.Fatalf("Invalid hub address: %v", err)+ logger.Fatalf("Invalid control plane address: %v", err)}}}@@ -434,7 +434,7 @@ func main() {priv := node.GetOrGenerateKey(store)meshNode, err := node.NewSamNode(node.Options{PrivKey: priv,- HubAddrs: initHubAddrs,+ RouterAddrs: initRouterAddrs,Store: store,MeshID: meshFlag,DiscoveryInterval: discoveryIntervalFlag,@@ -448,7 +448,7 @@ func main() {AutoRelayMinInterval: 30 * time.Second,AutoRelayBootDelay: 0 * time.Second,AutoRelayBackoff: 3 * time.Second,- HubConnectTimeout: hubConnectTimeoutFlag,+ RouterConnectTimeout: routerConnectTimeoutFlag,RequiredRole: api.RoleSamBox,})if err != nil {@@ -459,18 +459,18 @@ func main() {}if bootstrapTokenFlag != "" {- err = meshNode.EnrollBootstrap(ctx, targetHub, bootstrapTokenFlag)+ err = meshNode.EnrollBootstrap(ctx, targetControlPlane, bootstrapTokenFlag)} else {- err = meshNode.Enroll(ctx, targetHub, jwtStr)+ err = meshNode.Enroll(ctx, targetControlPlane, jwtStr)}if err != nil {logger.Fatalf("Enrollment failed: %v", err)}- if err := store.SaveHubURL(targetHub); err != nil {- logger.Warnf("Failed to save hub URL: %v", err)+ if err := store.SaveControlPlaneURL(targetControlPlane); err != nil {+ logger.Warnf("Failed to save control plane URL: %v", err)}if bootstrapTokenFlag == "" {- if err := store.SaveOIDCConfig(hubInfo.OidcIssuer, hubInfo.ClientId, hubInfo.Audience); err != nil {+ if err := store.SaveOIDCConfig(controlPlaneInfo.OidcIssuer, controlPlaneInfo.ClientId, controlPlaneInfo.Audience); err != nil {logger.Warnf("Failed to save OIDC config: %v", err)}}@@ -486,15 +486,15 @@ func main() {runCmd.Flags().StringVar(&bootstrapTokenFlag, "bootstrap-token", "", "Pre-shared bootstrap token for enrollment")runCmd.Flags().StringVar(&clientIDFlag, "client-id", "", "OIDC Client ID for M2M")runCmd.Flags().StringVar(&clientSecretFlag, "client-secret", "", "OIDC Client Secret for M2M")- runCmd.Flags().StringVar(&hubPublicKeyFlag, "hub-public-key", "", "Hub Public Key (32-byte Hex)")+ runCmd.Flags().StringVar(&controlPlanePublicKeyFlag, "control-plane-public-key", "", "Control plane public key (32-byte Hex)")runCmd.Flags().StringVar(&meshFlag, "mesh", node.DefaultMeshName, "Mesh federation name")runCmd.Flags().StringVar(&discoveryIntervalFlag, "discovery-interval", node.DefaultDiscoveryInterval, "Polling interval for DHT discovery")- runCmd.Flags().DurationVar(&monitorBootstrapFlag, "monitor-bootstrap", 2*time.Minute, "Initial wait before monitoring hub connection")- runCmd.Flags().DurationVar(&monitorCheckIntervalFlag, "monitor-interval", 1*time.Minute, "Interval for checking hub connection")+ runCmd.Flags().DurationVar(&monitorBootstrapFlag, "monitor-bootstrap", 2*time.Minute, "Initial wait before monitoring router connection")+ runCmd.Flags().DurationVar(&monitorCheckIntervalFlag, "monitor-interval", 1*time.Minute, "Interval for checking router connection")runCmd.Flags().DurationVar(&autoRelayMinIntervalFlag, "autorelay-min-interval", 30*time.Second, "AutoRelay Min Interval")runCmd.Flags().DurationVar(&autoRelayBootDelayFlag, "autorelay-boot-delay", 0*time.Second, "AutoRelay Boot Delay")runCmd.Flags().DurationVar(&autoRelayBackoffFlag, "autorelay-backoff", 3*time.Second, "AutoRelay Backoff")- runCmd.Flags().DurationVar(&hubConnectTimeoutFlag, "hub-connect-timeout", node.DefaultHubConnectTimeout, "Timeout for dialing each hub address")+ runCmd.Flags().DurationVar(&routerConnectTimeoutFlag, "router-connect-timeout", node.DefaultRouterConnectTimeout, "Timeout for dialing each router address")runCmd.Flags().BoolVar(&enableRelayFlag, "enable-relay", false, "Allow this node to serve as a relay for others")runCmd.Flags().StringVar(&logLevelFlag, "log-level", "info", "Log level (debug, info, warn, error)")runCmd.Flags().DurationVar(&keyGracePeriodFlag, "key-grace-period", 24*time.Hour, "Key grace period for old keys (e.g. 24h)")@@ -506,11 +506,11 @@ func main() {runCmd.Flags().StringVar(&interceptorsDirFlag, "interceptors-dir", "", "Path to the directory containing precompiled libinterceptor.so binaries")joinCmd.Flags().BoolVar(&allowLoopbackFlag, "allow-loopback", false, "Allow publishing and connecting to loopback/link-local addresses")- joinCmd.Flags().DurationVar(&hubConnectTimeoutFlag, "hub-connect-timeout", node.DefaultHubConnectTimeout, "Timeout for dialing each hub address")+ joinCmd.Flags().DurationVar(&routerConnectTimeoutFlag, "router-connect-timeout", node.DefaultRouterConnectTimeout, "Timeout for dialing each router address")joinCmd.Flags().BoolVar(&offlineAccessFlag, "offline-access", false, "Request OIDC offline access/refresh token for automatic renewal")joinCmd.Flags().StringVar(&bootstrapTokenFlag, "bootstrap-token", "", "Pre-shared bootstrap token for enrollment")- rootCmd.PersistentFlags().StringVar(&hubAddr, "hub", "", "Hub URL")+ rootCmd.PersistentFlags().StringVar(&controlPlaneAddr, "control-plane", "", "Control plane URL")rootCmd.PersistentFlags().StringVar(&configFile, "config", node.DefaultConfigFile, "Path to sam-node.yaml configuration file")rootCmd.PersistentFlags().StringVar(&oidcIssuerFlag, "oidc-issuer", "", "OIDC Issuer URL")rootCmd.PersistentFlags().StringVar(&deviceAuthURLFlag, "device-auth-url", "", "OIDC Device Authorization URL")diff --git a/cmd/sam-console/main.go b/cmd/sam-console/main.goindex be3e77c0..c2350dd6 100644--- a/cmd/sam-console/main.go+++ b/cmd/sam-console/main.go@@ -15,11 +15,11 @@ import (func main() {var (- hubURL = flag.String("hub", "http://localhost:8080", "URL of the SAM control plane")- adminToken = flag.String("admin-token", "", "Admin token for control plane authentication")- bindAddr = flag.String("bind-addr", ":8081", "Address to bind the console server")- staticDir = flag.String("static-dir", "public", "Directory containing static frontend files")- basePath = flag.String("base-path", "", "Base path prefix for the console (e.g. /console)")+ controlPlaneURL = flag.String("control-plane", "http://localhost:8080", "URL of the SAM control plane")+ adminToken = flag.String("admin-token", "", "Admin token for control plane authentication")+ bindAddr = flag.String("bind-addr", ":8081", "Address to bind the console server")+ staticDir = flag.String("static-dir", "public", "Directory containing static frontend files")+ basePath = flag.String("base-path", "", "Base path prefix for the console (e.g. /console)"))flag.Parse()@@ -28,10 +28,10 @@ func main() {}srv, err := console.NewServer(console.Config{- HubURL: *hubURL,- AdminToken: *adminToken,- StaticDir: *staticDir,- BasePath: *basePath,+ ControlPlaneURL: *controlPlaneURL,+ AdminToken: *adminToken,+ StaticDir: *staticDir,+ BasePath: *basePath,})if err != nil {log.Fatalf("Failed to initialize console server: %v", err)diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.goindex d016d7f8..65f45903 100644--- a/cmd/sam-node/main.go+++ b/cmd/sam-node/main.go@@ -50,43 +50,43 @@ func init() {}var (- hubAddr string- jwtFlag string- jwtPathFlag string- bootstrapTokenFlag string- clientIDFlag string- clientSecretFlag string- hubPublicKeyFlag string- bindAddrFlag string- meshFlag string- discoveryIntervalFlag string- listenAddrs []string- enableRelayFlag bool- configFile string- oidcIssuerFlag string- deviceAuthURLFlag string- audienceFlag string- dataDirFlag string- headlessFlag bool- offlineAccessFlag bool- logLevelFlag string- keyGracePeriodFlag time.Duration- allowLoopbackFlag bool- monitorBootstrapFlag time.Duration- monitorCheckIntervalFlag time.Duration- autoRelayMinIntervalFlag time.Duration- autoRelayBootDelayFlag time.Duration- autoRelayBackoffFlag time.Duration- hubConnectTimeoutFlag time.Duration- apiTokenFlag string- tlsCertFlag string- tlsKeyFlag string- tlsCAFlag string- dhtProviderAddrTTLFlag time.Duration- dhtMaxRecordAgeFlag time.Duration- dhtLookupLimitFlag int- discoveryConcurrencyFlag int- policySyncIntervalFlag time.Duration+ controlPlaneAddr string+ jwtFlag string+ jwtPathFlag string+ bootstrapTokenFlag string+ clientIDFlag string+ clientSecretFlag string+ controlPlanePublicKeyFlag string+ bindAddrFlag string+ meshFlag string+ discoveryIntervalFlag string+ listenAddrs []string+ enableRelayFlag bool+ configFile string+ oidcIssuerFlag string+ deviceAuthURLFlag string+ audienceFlag string+ dataDirFlag string+ headlessFlag bool+ offlineAccessFlag bool+ logLevelFlag string+ keyGracePeriodFlag time.Duration+ allowLoopbackFlag bool+ monitorBootstrapFlag time.Duration+ monitorCheckIntervalFlag time.Duration+ autoRelayMinIntervalFlag time.Duration+ autoRelayBootDelayFlag time.Duration+ autoRelayBackoffFlag time.Duration+ routerConnectTimeoutFlag time.Duration+ apiTokenFlag string+ tlsCertFlag string+ tlsKeyFlag string+ tlsCAFlag string+ dhtProviderAddrTTLFlag time.Duration+ dhtMaxRecordAgeFlag time.Duration+ dhtLookupLimitFlag int+ discoveryConcurrencyFlag int+ policySyncIntervalFlag time.Duration)var logger = golog.Logger("sam-node-cli")@@ -136,24 +136,24 @@ func main() {}}()- var hubPubKey ed25519.PublicKey- var hubAddrs []multiaddr.Multiaddr+ var controlPlanePubKey ed25519.PublicKey+ var routerAddrs []multiaddr.Multiaddr- storedPubKey, syncedAddrs, err := node.SyncHubConfig(context.Background(), store)+ storedPubKey, syncedAddrs, err := node.SyncMeshConfig(context.Background(), store)if err != nil {- logger.Warnf("Failed to sync hub config: %v", err)+ logger.Warnf("Failed to sync mesh config: %v", err)}if len(storedPubKey) > 0 {- hubPubKey = storedPubKey- hubAddrs = syncedAddrs+ controlPlanePubKey = storedPubKey+ routerAddrs = syncedAddrs}- if hubPublicKeyFlag != "" {- pubBytes, err := hex.DecodeString(strings.TrimSpace(hubPublicKeyFlag))+ if controlPlanePublicKeyFlag != "" {+ pubBytes, err := hex.DecodeString(strings.TrimSpace(controlPlanePublicKeyFlag))if err != nil {- logger.Fatalf("Invalid hub public key: %v", err)+ logger.Fatalf("Invalid control plane public key: %v", err)}- hubPubKey = pubBytes+ controlPlanePubKey = pubBytes}var meshNode *node.SamNode@@ -185,16 +185,16 @@ func main() {if jwtStr == "" && bootstrapTokenFlag == "" {token, _ := store.LoadIdentity()if len(token) == 0 {- displayHub := hubAddr- if displayHub == "" {- if h, err := store.LoadHubURL(); err == nil && h != "" {- displayHub = h+ displayControlPlane := controlPlaneAddr+ if displayControlPlane == "" {+ if h, err := store.LoadControlPlaneURL(); err == nil && h != "" {+ displayControlPlane = h} else {- displayHub = "https://bananas.sam-mesh.dev"+ displayControlPlane = "https://bananas.sam-mesh.dev"}}logger.Infof("No identity found. Starting unauthenticated sidecar for enrollment over MCP...")- unauthSrv, err := node.StartUnauthSidecarServer(displayHub, bindAddrFlag, tlsCertFlag, tlsKeyFlag)+ unauthSrv, err := node.StartUnauthSidecarServer(displayControlPlane, bindAddrFlag, tlsCertFlag, tlsKeyFlag)if err != nil {logger.Fatalf("Failed to start unauthenticated sidecar: %v", err)}@@ -206,14 +206,14 @@ func main() {}logger.Infoln("Using stored identity.")- if len(hubPubKey) == 0 {- logger.Fatal("Hub public key not found in store and not provided. Cannot verify peers.")+ if len(controlPlanePubKey) == 0 {+ logger.Fatal("Control plane public key not found in store and not provided. Cannot verify peers.")}priv := node.GetOrGenerateKey(store)meshNode, err = node.NewSamNode(node.Options{PrivKey: priv,- HubPubKey: hubPubKey,- HubAddrs: hubAddrs,+ ControlPlanePubKey: controlPlanePubKey,+ RouterAddrs: routerAddrs,Store: store,MeshID: meshFlag,DiscoveryInterval: discoveryIntervalFlag,@@ -227,7 +227,7 @@ func main() {AutoRelayMinInterval: autoRelayMinIntervalFlag,AutoRelayBootDelay: autoRelayBootDelayFlag,AutoRelayBackoff: autoRelayBackoffFlag,- HubConnectTimeout: hubConnectTimeoutFlag,+ RouterConnectTimeout: routerConnectTimeoutFlag,RequiredRole: api.RoleNode,PolicySyncInterval: policySyncIntervalFlag,DHTProviderAddrTTL: dhtProviderAddrTTLFlag,@@ -243,14 +243,14 @@ func main() {}} else {// We have a new JWT (from flag or interactive login), need to enroll- var initHubAddrs []multiaddr.Multiaddr- if !strings.HasPrefix(hubAddr, "http://") && !strings.HasPrefix(hubAddr, "https://") {- ma, err := multiaddr.NewMultiaddr(hubAddr)+ var initRouterAddrs []multiaddr.Multiaddr+ if !strings.HasPrefix(controlPlaneAddr, "http://") && !strings.HasPrefix(controlPlaneAddr, "https://") {+ ma, err := multiaddr.NewMultiaddr(controlPlaneAddr)if err == nil {- initHubAddrs = []multiaddr.Multiaddr{ma}+ initRouterAddrs = []multiaddr.Multiaddr{ma}} else {// Try parsing as host:port- host, port, err := net.SplitHostPort(hubAddr)+ host, port, err := net.SplitHostPort(controlPlaneAddr)if err == nil {ip := net.ParseIP(host)var maddr multiaddr.Multiaddr@@ -263,12 +263,12 @@ func main() {if parseErr != nil {logger.Fatalf("Failed to parse multiaddr: %v", parseErr)}- initHubAddrs = []multiaddr.Multiaddr{maddr}+ initRouterAddrs = []multiaddr.Multiaddr{maddr}} else {- if len(hubAddrs) > 0 {- initHubAddrs = hubAddrs+ if len(routerAddrs) > 0 {+ initRouterAddrs = routerAddrs} else {- logger.Fatalf("Invalid hub address and no stored config: %v. You can use community maintained meshes like hub.sam-mesh.dev (Production) or bananas.sam-mesh.dev (Testnet)", err)+ logger.Fatalf("Invalid control plane address and no stored config: %v. You can use community maintained meshes like hub.sam-mesh.dev (Production) or bananas.sam-mesh.dev (Testnet)", err)}}}@@ -278,7 +278,7 @@ func main() {enrollCtx, enrollCancel := context.WithCancel(context.Background())meshNode, err = node.NewSamNode(node.Options{PrivKey: priv,- HubAddrs: initHubAddrs,+ RouterAddrs: initRouterAddrs,Store: store,MeshID: meshFlag,DiscoveryInterval: discoveryIntervalFlag,@@ -292,7 +292,7 @@ func main() {AutoRelayMinInterval: autoRelayMinIntervalFlag,AutoRelayBootDelay: autoRelayBootDelayFlag,AutoRelayBackoff: autoRelayBackoffFlag,- HubConnectTimeout: hubConnectTimeoutFlag,+ RouterConnectTimeout: routerConnectTimeoutFlag,RequiredRole: api.RoleNode,PolicySyncInterval: policySyncIntervalFlag,DHTProviderAddrTTL: dhtProviderAddrTTLFlag,@@ -310,9 +310,9 @@ func main() {}if bootstrapTokenFlag != "" {- err = meshNode.EnrollBootstrap(enrollCtx, hubAddr, bootstrapTokenFlag)+ err = meshNode.EnrollBootstrap(enrollCtx, controlPlaneAddr, bootstrapTokenFlag)} else {- err = meshNode.Enroll(enrollCtx, hubAddr, jwtStr)+ err = meshNode.Enroll(enrollCtx, controlPlaneAddr, jwtStr)}if err != nil {if teardownErr := meshNode.Teardown(); teardownErr != nil {@@ -321,8 +321,8 @@ func main() {enrollCancel()logger.Fatalf("Enrollment failed: %v", err)}- if err := store.SaveHubURL(hubAddr); err != nil {- logger.Warnf("Failed to save hub URL: %v", err)+ if err := store.SaveControlPlaneURL(controlPlaneAddr); err != nil {+ logger.Warnf("Failed to save control plane URL: %v", err)}if teardownErr := meshNode.Teardown(); teardownErr != nil {@@ -330,17 +330,17 @@ func main() {}enrollCancel()- storedPubKey, newHubAddrs, err := node.SyncHubConfig(context.Background(), store)+ storedPubKey, newRouterAddrs, err := node.SyncMeshConfig(context.Background(), store)if err != nil {- logger.Warnf("Failed to sync hub config post-enrollment: %v", err)+ logger.Warnf("Failed to sync mesh config post-enrollment: %v", err)}- hubPubKey = storedPubKey+ controlPlanePubKey = storedPubKeylogger.Debugf("listenAddrs: %v, allowLoopback: %v", listenAddrs, allowLoopbackFlag)meshNode, err = node.NewSamNode(node.Options{PrivKey: priv,- HubPubKey: hubPubKey,- HubAddrs: newHubAddrs,+ ControlPlanePubKey: controlPlanePubKey,+ RouterAddrs: newRouterAddrs,Store: store,MeshID: meshFlag,DiscoveryInterval: discoveryIntervalFlag,@@ -354,7 +354,7 @@ func main() {AutoRelayMinInterval: autoRelayMinIntervalFlag,AutoRelayBootDelay: autoRelayBootDelayFlag,AutoRelayBackoff: autoRelayBackoffFlag,- HubConnectTimeout: hubConnectTimeoutFlag,+ RouterConnectTimeout: routerConnectTimeoutFlag,RequiredRole: api.RoleNode,PolicySyncInterval: policySyncIntervalFlag,})@@ -396,18 +396,18 @@ func main() {}joinCmd := &cobra.Command{- Use: "join [hub_url]",- Short: "Join the Sovereign Agent Mesh hub",+ Use: "join [control_plane_url]",+ Short: "Join the Sovereign Agent Mesh",Args: cobra.MaximumNArgs(1),Run: func(cmd *cobra.Command, args []string) {ctx := cmd.Context()- targetHub := ""+ targetControlPlane := ""if len(args) > 0 {- targetHub = args[0]+ targetControlPlane = args[0]}- if targetHub == "" {- fmt.Print("No hub URL provided. Do you want to join the default community testing network (https://bananas.sam-mesh.dev)? [y/N]: ")+ if targetControlPlane == "" {+ fmt.Print("No control plane URL provided. Do you want to join the default community testing network (https://bananas.sam-mesh.dev)? [y/N]: ")reader := bufio.NewReader(os.Stdin)response, err := reader.ReadString('\n')if err != nil {@@ -419,13 +419,13 @@ func main() {fmt.Println("Aborting join operation.")return}- targetHub = "https://bananas.sam-mesh.dev"+ targetControlPlane = "https://bananas.sam-mesh.dev"}- if !strings.HasPrefix(targetHub, "http://") && !strings.HasPrefix(targetHub, "https://") {- targetHub = "https://" + targetHub+ if !strings.HasPrefix(targetControlPlane, "http://") && !strings.HasPrefix(targetControlPlane, "https://") {+ targetControlPlane = "https://" + targetControlPlane}- targetHub = strings.TrimSuffix(targetHub, "/")+ targetControlPlane = strings.TrimSuffix(targetControlPlane, "/")store, err := node.NewStore(resolveDataDir())if err != nil {@@ -444,40 +444,40 @@ func main() {dummyNode := &node.SamNode{Store: store}- fmt.Printf("Discovering hub info from %s...\n", targetHub)- hubInfo, err := node.FetchHubInfo(ctx, targetHub)+ fmt.Printf("Discovering control plane info from %s...\n", targetControlPlane)+ controlPlaneInfo, err := node.FetchControlPlaneInfo(ctx, targetControlPlane)if err != nil {- logger.Fatalf("Failed to discover hub info: %v", err)+ logger.Fatalf("Failed to discover control plane info: %v", err)}var jwtStr stringif bootstrapTokenFlag == "" {- fmt.Printf("OIDC Issuer discovered: %s\n", hubInfo.OidcIssuer)- fmt.Printf("Client ID discovered: %s\n", hubInfo.ClientId)+ fmt.Printf("OIDC Issuer discovered: %s\n", controlPlaneInfo.OidcIssuer)+ fmt.Printf("Client ID discovered: %s\n", controlPlaneInfo.ClientId)logger.Info("Discovering OIDC endpoints...")- tokenURL, authURL, err := dummyNode.DiscoverEndpoints(ctx, hubInfo.OidcIssuer)+ tokenURL, authURL, err := dummyNode.DiscoverEndpoints(ctx, controlPlaneInfo.OidcIssuer)if err != nil {logger.Fatalf("Failed to discover OIDC endpoints: %v", err)}- jwtStr, err = dummyNode.InteractiveLogin(ctx, authURL, tokenURL, hubInfo.ClientId, hubInfo.Audience, offlineAccessFlag, headlessFlag)+ jwtStr, err = dummyNode.InteractiveLogin(ctx, authURL, tokenURL, controlPlaneInfo.ClientId, controlPlaneInfo.Audience, offlineAccessFlag, headlessFlag)if err != nil {logger.Fatalf("Failed to get token: %v", err)}}- // Override global hubAddr with targetHub for enrollment- hubAddr = targetHub+ // Override global controlPlaneAddr with targetControlPlane for enrollment+ controlPlaneAddr = targetControlPlane- // Connect to Hub and Enroll- var initHubAddrs []multiaddr.Multiaddr- if !strings.HasPrefix(hubAddr, "http://") && !strings.HasPrefix(hubAddr, "https://") {- ma, err := multiaddr.NewMultiaddr(hubAddr)+ // Connect to control plane and enroll+ var initRouterAddrs []multiaddr.Multiaddr+ if !strings.HasPrefix(controlPlaneAddr, "http://") && !strings.HasPrefix(controlPlaneAddr, "https://") {+ ma, err := multiaddr.NewMultiaddr(controlPlaneAddr)if err == nil {- initHubAddrs = []multiaddr.Multiaddr{ma}+ initRouterAddrs = []multiaddr.Multiaddr{ma}} else {- host, port, err := net.SplitHostPort(hubAddr)+ host, port, err := net.SplitHostPort(controlPlaneAddr)if err == nil {ip := net.ParseIP(host)var maddr multiaddr.Multiaddr@@ -490,9 +490,9 @@ func main() {if parseErr != nil {logger.Fatalf("Failed to parse multiaddr: %v", parseErr)}- initHubAddrs = []multiaddr.Multiaddr{maddr}+ initRouterAddrs = []multiaddr.Multiaddr{maddr}} else {- logger.Fatalf("Invalid hub address: %v", err)+ logger.Fatalf("Invalid control plane address: %v", err)}}}@@ -500,7 +500,7 @@ func main() {priv := node.GetOrGenerateKey(store)meshNode, err := node.NewSamNode(node.Options{PrivKey: priv,- HubAddrs: initHubAddrs,+ RouterAddrs: initRouterAddrs,Store: store,MeshID: meshFlag,DiscoveryInterval: discoveryIntervalFlag,@@ -514,7 +514,7 @@ func main() {AutoRelayMinInterval: 30 * time.Second,AutoRelayBootDelay: 0 * time.Second,AutoRelayBackoff: 3 * time.Second,- HubConnectTimeout: hubConnectTimeoutFlag,+ RouterConnectTimeout: routerConnectTimeoutFlag,RequiredRole: api.RoleNode,PolicySyncInterval: policySyncIntervalFlag,})@@ -526,18 +526,18 @@ func main() {}if bootstrapTokenFlag != "" {- err = meshNode.EnrollBootstrap(ctx, targetHub, bootstrapTokenFlag)+ err = meshNode.EnrollBootstrap(ctx, targetControlPlane, bootstrapTokenFlag)} else {- err = meshNode.Enroll(ctx, targetHub, jwtStr)+ err = meshNode.Enroll(ctx, targetControlPlane, jwtStr)}if err != nil {logger.Fatalf("Enrollment failed: %v", err)}- if err := store.SaveHubURL(targetHub); err != nil {- logger.Warnf("Failed to save hub URL: %v", err)+ if err := store.SaveControlPlaneURL(targetControlPlane); err != nil {+ logger.Warnf("Failed to save control plane URL: %v", err)}if bootstrapTokenFlag == "" {- if err := store.SaveOIDCConfig(hubInfo.OidcIssuer, hubInfo.ClientId, hubInfo.Audience); err != nil {+ if err := store.SaveOIDCConfig(controlPlaneInfo.OidcIssuer, controlPlaneInfo.ClientId, controlPlaneInfo.Audience); err != nil {logger.Warnf("Failed to save OIDC config: %v", err)}}@@ -553,22 +553,22 @@ func main() {runCmd.Flags().StringVar(&bootstrapTokenFlag, "bootstrap-token", "", "Pre-shared bootstrap token for enrollment")runCmd.Flags().StringVar(&clientIDFlag, "client-id", "", "OIDC Client ID for M2M")runCmd.Flags().StringVar(&clientSecretFlag, "client-secret", "", "OIDC Client Secret for M2M")- runCmd.Flags().StringVar(&hubPublicKeyFlag, "hub-public-key", "", "Hub Public Key (32-byte Hex)")+ runCmd.Flags().StringVar(&controlPlanePublicKeyFlag, "control-plane-public-key", "", "Control plane public key (32-byte Hex)")runCmd.Flags().StringVar(&bindAddrFlag, "bind-addr", "127.0.0.1:8080", "Local TCP address for the HTTP server (MCP and Sidecar API)")runCmd.Flags().StringVar(&meshFlag, "mesh", node.DefaultMeshName, "Mesh federation name")runCmd.Flags().StringVar(&discoveryIntervalFlag, "discovery-interval", node.DefaultDiscoveryInterval, "Polling interval for DHT discovery")- runCmd.Flags().DurationVar(&monitorBootstrapFlag, "monitor-bootstrap", 2*time.Minute, "Initial wait before monitoring hub connection")- runCmd.Flags().DurationVar(&monitorCheckIntervalFlag, "monitor-interval", 1*time.Minute, "Interval for checking hub connection")+ runCmd.Flags().DurationVar(&monitorBootstrapFlag, "monitor-bootstrap", 2*time.Minute, "Initial wait before monitoring router connection")+ runCmd.Flags().DurationVar(&monitorCheckIntervalFlag, "monitor-interval", 1*time.Minute, "Interval for checking router connection")runCmd.Flags().DurationVar(&autoRelayMinIntervalFlag, "autorelay-min-interval", 30*time.Second, "AutoRelay Min Interval")runCmd.Flags().DurationVar(&autoRelayBootDelayFlag, "autorelay-boot-delay", 0*time.Second, "AutoRelay Boot Delay")runCmd.Flags().DurationVar(&autoRelayBackoffFlag, "autorelay-backoff", 3*time.Second, "AutoRelay Backoff")- runCmd.Flags().DurationVar(&hubConnectTimeoutFlag, "hub-connect-timeout", node.DefaultHubConnectTimeout, "Timeout for dialing each hub address")+ runCmd.Flags().DurationVar(&routerConnectTimeoutFlag, "router-connect-timeout", node.DefaultRouterConnectTimeout, "Timeout for dialing each router address")runCmd.Flags().BoolVar(&enableRelayFlag, "enable-relay", false, "Allow this node to serve as a relay for others")runCmd.Flags().StringVar(&logLevelFlag, "log-level", "info", "Log level (debug, info, warn, error)")runCmd.Flags().DurationVar(&keyGracePeriodFlag, "key-grace-period", 24*time.Hour, "Key grace period for old keys (e.g. 24h)")runCmd.Flags().BoolVar(&allowLoopbackFlag, "allow-loopback", false, "Allow publishing and connecting to loopback/link-local addresses")joinCmd.Flags().BoolVar(&allowLoopbackFlag, "allow-loopback", false, "Allow publishing and connecting to loopback/link-local addresses")- joinCmd.Flags().DurationVar(&hubConnectTimeoutFlag, "hub-connect-timeout", node.DefaultHubConnectTimeout, "Timeout for dialing each hub address")+ joinCmd.Flags().DurationVar(&routerConnectTimeoutFlag, "router-connect-timeout", node.DefaultRouterConnectTimeout, "Timeout for dialing each router address")joinCmd.Flags().BoolVar(&offlineAccessFlag, "offline-access", false, "Request OIDC offline access/refresh token for automatic renewal")joinCmd.Flags().StringVar(&bootstrapTokenFlag, "bootstrap-token", "", "Pre-shared bootstrap token for enrollment")runCmd.Flags().StringVar(&apiTokenFlag, "api-token", "", "Static Bearer token for API authorization")@@ -579,8 +579,8 @@ func main() {runCmd.Flags().DurationVar(&dhtMaxRecordAgeFlag, "dht-max-record-age", 0, "Maximum age for DHT records (0s uses library default)")runCmd.Flags().IntVar(&dhtLookupLimitFlag, "dht-lookup-limit", 0, "Maximum number of providers to query from the DHT (0 uses default 20)")runCmd.Flags().IntVar(&discoveryConcurrencyFlag, "discovery-concurrency", 0, "Max concurrent catalog fetches during discovery (0 uses default 10)")- runCmd.Flags().DurationVar(&policySyncIntervalFlag, "policy-sync-interval", 1*time.Hour, "Interval for syncing mesh policy from the Hub")- rootCmd.PersistentFlags().StringVar(&hubAddr, "hub", "", "Hub URL")+ runCmd.Flags().DurationVar(&policySyncIntervalFlag, "policy-sync-interval", 1*time.Hour, "Interval for syncing mesh policy from the control plane")+ rootCmd.PersistentFlags().StringVar(&controlPlaneAddr, "control-plane", "", "Control plane URL")rootCmd.PersistentFlags().StringVar(&configFile, "config", node.DefaultConfigFile, "Path to sam-node.yaml configuration file")rootCmd.PersistentFlags().StringVar(&oidcIssuerFlag, "oidc-issuer", "", "OIDC Issuer URL")rootCmd.PersistentFlags().StringVar(&deviceAuthURLFlag, "device-auth-url", "", "OIDC Device Authorization URL")diff --git a/development/examples/calc-mcp/sam-node-config.yaml b/development/examples/calc-mcp/sam-node-config.yamlindex a06e55de..fad29c57 100644--- a/development/examples/calc-mcp/sam-node-config.yaml+++ b/development/examples/calc-mcp/sam-node-config.yaml@@ -1,7 +1,7 @@version: "v1alpha1"attenuation:# Allow cross-node MCP only when the caller's biscuit carries a- # node($peer) fact — i.e. it was issued by our hub upon enrollment.+ # node($peer) fact — i.e. it was issued by our control plane upon enrollment.policies:services:- type: "mcp"diff --git a/development/kind/00-namespace-rbac.yaml b/development/kind/00-namespace-rbac.yamlindex 111312ea..c981b443 100644--- a/development/kind/00-namespace-rbac.yaml+++ b/development/kind/00-namespace-rbac.yaml@@ -3,7 +3,7 @@ kind: Namespacemetadata:name: ${NAMESPACE}----# Let the hub validate node SA tokens against the kube API OIDC discovery+# Let the control plane validate node SA tokens against the kube API OIDC discovery# endpoints without credentials.apiVersion: rbac.authorization.k8s.io/v1kind: ClusterRolediff --git a/development/kind/kind-config.yaml b/development/kind/kind-config.yamlindex 8296eea6..58f08211 100644--- a/development/kind/kind-config.yaml+++ b/development/kind/kind-config.yaml@@ -2,7 +2,7 @@ kind: ClusterapiVersion: kind.x-k8s.io/v1alpha4nodes:- role: control-plane- # Expose the hub to the host (via the sam-hub-nodeport NodePort) so a+ # Expose the control plane and router to the host (via the sam-control-plane-nodeport NodePort) so a# locally-built sam-node can enroll: host:9090->HTTP, host:4001->libp2p TCP.extraPortMappings:- containerPort: 30090@@ -19,7 +19,7 @@ nodes:protocol: TCP- role: workerlabels:- sam-role: hub+ sam-role: control-plane- role: workerlabels:sam-role: node-adiff --git a/development/kind/node.template.yaml b/development/kind/node.template.yamlindex 0d96f474..a8c34a3b 100644--- a/development/kind/node.template.yaml+++ b/development/kind/node.template.yaml@@ -28,7 +28,7 @@ spec:imagePullPolicy: IfNotPresentargs:- "run"- - "--hub=${HUB_URL}"+ - "--control-plane=${CONTROL_PLANE_URL}"- "--jwt-path=/var/run/secrets/tokens/sam-token"- "--api-token=devtoken"- "--bind-addr=0.0.0.0:8080"diff --git a/development/kind/run-local-node.sh b/development/kind/run-local-node.shindex d4514cfe..07dd68ae 100755--- a/development/kind/run-local-node.sh+++ b/development/kind/run-local-node.sh@@ -1,8 +1,8 @@#!/usr/bin/env bash-# Enroll a locally-built ./bin/sam-node into the kind mesh hub for local testing.-# The hub (exposed via sam-hub-nodeport + kind extraPortMappings) is reached at+# Enroll a locally-built ./bin/sam-node into the kind mesh for local testing.+# The control plane (exposed via sam-control-plane-nodeport + kind extraPortMappings) is reached at# 127.0.0.1:9090 (HTTP enroll) and 127.0.0.1:4001 (libp2p TCP); the node relays-# peer traffic through the hub. Extra args pass through, e.g. to host a service:+# peer traffic through the router. Extra args pass through, e.g. to host a service:# ARGS="--config development/examples/calc-mcp/sam-node-config.yaml"set -euo pipefail@@ -27,14 +27,14 @@ kubectl --context "${KCTX}" -n "${NAMESPACE}" create serviceaccount local-node-sJWT="$(kubectl --context "${KCTX}" -n "${NAMESPACE}" create token local-node-sa \--audience=sam-mesh-audience --duration=1h)"-echo "Enrolling local ./bin/sam-node into mesh hub at http://127.0.0.1:9090…"+echo "Enrolling local ./bin/sam-node into the mesh control plane at http://127.0.0.1:9090…"echo " MCP/sidecar API on 127.0.0.1:9099"exec ./bin/sam-node run \- --hub http://127.0.0.1:9090 \+ --control-plane http://127.0.0.1:9090 \--jwt "${JWT}" \--listen /ip4/0.0.0.0/tcp/0 \--bind-addr 127.0.0.1:9099 \--api-token devtoken \--discovery-interval 200ms \- --hub-connect-timeout 10s \+ --router-connect-timeout 10s \"$@"diff --git a/development/kind/run.sh b/development/kind/run.shindex d2b1243c..d1779141 100755--- a/development/kind/run.sh+++ b/development/kind/run.sh@@ -1,5 +1,5 @@#!/usr/bin/env bash-# Kind dev mesh: a hub plus the nodes declared in mesh-config.yaml, each pinned+# Kind dev mesh: a control plane and router plus the nodes declared in mesh-config.yaml, each pinned# to its own k8s node, with live per-pod logs in named tmux panes.set -euo pipefail@@ -8,7 +8,7 @@ NAMESPACE="sam-kind"SESSION="sam-kind"KCTX="kind-${CLUSTER}"IMAGE_TAG="local"-HUB_URL="http://sam-mesh-control-plane:8080"+CONTROL_PLANE_URL="http://sam-mesh-control-plane:8080"HELM="helm"@@ -58,8 +58,8 @@ render_and_apply() {SIDECAR=$' - name: '"${name}"$'\n image: '"${name}:${IMAGE_TAG}"$'\n imagePullPolicy: IfNotPresent'CONFIG_VOLUME=$' - name: config\n configMap:\n name: '"${node}-config"fi- NODE="$node" HUB_URL="$HUB_URL" CONFIG_ARG="$CONFIG_ARG" CONFIG_MOUNT="$CONFIG_MOUNT" SIDECAR="$SIDECAR" CONFIG_VOLUME="$CONFIG_VOLUME" \- envsubst '${NODE} ${NAMESPACE} ${HUB_URL} ${IMAGE_TAG} ${CONFIG_ARG} ${CONFIG_MOUNT} ${SIDECAR} ${CONFIG_VOLUME}' \+ NODE="$node" CONTROL_PLANE_URL="$CONTROL_PLANE_URL" CONFIG_ARG="$CONFIG_ARG" CONFIG_MOUNT="$CONFIG_MOUNT" SIDECAR="$SIDECAR" CONFIG_VOLUME="$CONFIG_VOLUME" \+ envsubst '${NODE} ${NAMESPACE} ${CONTROL_PLANE_URL} ${IMAGE_TAG} ${CONFIG_ARG} ${CONFIG_MOUNT} ${SIDECAR} ${CONFIG_VOLUME}' \< "${SCRIPT_DIR}/node.template.yaml" | kubectl --context "${KCTX}" apply -f -}diff --git a/development/kind/test-mesh-e2e.sh b/development/kind/test-mesh-e2e.shindex 7931d112..7bda43b3 100755--- a/development/kind/test-mesh-e2e.sh+++ b/development/kind/test-mesh-e2e.sh@@ -39,7 +39,7 @@ mcp() { ./bin/mcp-client -url "$URL" -token "devtoken" -timeout 20 "$@" 2>/dev/necho "== get_mesh_info =="info=$(mcp -tool get_mesh_info -args '{}')echo "$info"-echo "$info" | jq -e '.hub_peer_id != "" and (.dht_size > 0)' >/dev/null \+echo "$info" | jq -e '.router_peer_id != "" and (.dht_size > 0)' >/dev/null \|| { echo "get_mesh_info assertion failed"; exit 1; }echo "== discover services / find calculator (poll) =="diff --git a/internal/console/server.go b/internal/console/server.goindex 4e399144..0f9f93bb 100644--- a/internal/console/server.go+++ b/internal/console/server.go@@ -22,10 +22,10 @@ import ()type Config struct {- HubURL string- AdminToken string- StaticDir string- BasePath string+ ControlPlaneURL string+ AdminToken string+ StaticDir string+ BasePath string}type Server struct {@@ -36,20 +36,20 @@ type Server struct {}func NewServer(cfg Config) (*Server, error) {- if cfg.HubURL == "" {- return nil, fmt.Errorf("HubURL is required")+ if cfg.ControlPlaneURL == "" {+ return nil, fmt.Errorf("ControlPlaneURL is required")}- hubURL, err := url.Parse(cfg.HubURL)+ controlPlaneURL, err := url.Parse(cfg.ControlPlaneURL)if err != nil {- return nil, fmt.Errorf("invalid HubURL: %w", err)+ return nil, fmt.Errorf("invalid ControlPlaneURL: %w", err)}var provider *oidc.Providervar clientID stringclient := &http.Client{Timeout: 10 * time.Second}- resp, err := client.Get(cfg.HubURL + "/info")+ resp, err := client.Get(cfg.ControlPlaneURL + "/info")if err != nil {return nil, fmt.Errorf("failed to query control-plane info for OIDC discovery: %w", err)}@@ -60,9 +60,9 @@ func NewServer(cfg Config) (*Server, error) {if err != nil {return nil, fmt.Errorf("failed to read control-plane info body: %w", err)}- var info api.HubInfoResponse+ var info api.ControlPlaneInfoResponseif err := proto.Unmarshal(body, &info); err != nil {- return nil, fmt.Errorf("failed to unmarshal hub info: %w", err)+ return nil, fmt.Errorf("failed to unmarshal control plane info: %w", err)}if info.OidcIssuer != "" && info.ClientId != "" {@@ -88,7 +88,7 @@ func NewServer(cfg Config) (*Server, error) {// Create reverse proxy to the control planeproxy := &httputil.ReverseProxy{Rewrite: func(r *httputil.ProxyRequest) {- r.SetURL(hubURL)+ r.SetURL(controlPlaneURL)r.Out.Host = r.In.Host// If Authorization header is not set, inject from sam_session cookieif r.Out.Header.Get("Authorization") == "" {diff --git a/internal/console/server_test.go b/internal/console/server_test.goindex 6f9bdac5..d3da0092 100644--- a/internal/console/server_test.go+++ b/internal/console/server_test.go@@ -19,13 +19,13 @@ func TestNewServer_OIDCAutoDiscovery(t *testing.T) {t.Fatalf("failed to generate RSA key: %v", err)}- // 2. Start mock Hub + OIDC server+ // 2. Start mock control plane + OIDC servervar serverURL stringmux := http.NewServeMux()// Mock Control Plane /info endpointmux.HandleFunc("/info", func(w http.ResponseWriter, r *http.Request) {- resp := &api.HubInfoResponse{+ resp := &api.ControlPlaneInfoResponse{OidcIssuer: serverURL,ClientId: "mock-console-client",}@@ -75,9 +75,9 @@ func TestNewServer_OIDCAutoDiscovery(t *testing.T) {// 3. Instantiate console Server with auto-discovery flags (empty issuer and client ID)cfg := Config{- HubURL: serverURL,- AdminToken: "test-admin-token",- StaticDir: t.TempDir(),+ ControlPlaneURL: serverURL,+ AdminToken: "test-admin-token",+ StaticDir: t.TempDir(),}srv, err := NewServer(cfg)diff --git a/internal/controlplane/server.go b/internal/controlplane/server.goindex 13a0d6dd..802036a0 100644--- a/internal/controlplane/server.go+++ b/internal/controlplane/server.go@@ -319,11 +319,11 @@ func (s *Server) HandleInfo(w http.ResponseWriter, r *http.Request) {routerAddrs = append(routerAddrs, r.Addresses...)}- resp := &api.HubInfoResponse{- OidcIssuer: issuer,- ClientId: aud,- Audience: aud,- HubAddresses: routerAddrs, // Reused this field for back-compatibility with bootstrap routers list+ resp := &api.ControlPlaneInfoResponse{+ OidcIssuer: issuer,+ ClientId: aud,+ Audience: aud,+ RouterAddresses: routerAddrs, // Reused this field for back-compatibility with bootstrap routers list}respData, err := proto.Marshal(resp)@@ -483,10 +483,10 @@ func (s *Server) HandleRegister(w http.ResponseWriter, r *http.Request) {}resp := &api.EnrollResponse{- BiscuitToken: biscuitData,- HubPublicKey: pubKey,- HubAddresses: routerAddrs, // routers nodes multiaddresses- Expiration: token.Expiry.Unix(),+ BiscuitToken: biscuitData,+ ControlPlanePublicKey: pubKey,+ RouterAddresses: routerAddrs, // routers nodes multiaddresses+ Expiration: token.Expiry.Unix(),}respData, err := proto.Marshal(resp)@@ -1588,11 +1588,11 @@ func (s *Server) buildApprovedBootstrapEnrollResponse(ctx context.Context, biscu}return &api.BootstrapEnrollResponse{- Status: api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED,- BiscuitToken: biscuitToken,- HubPublicKey: pubKey,- HubAddresses: routerAddrs,- Expiration: expiration,+ Status: api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED,+ BiscuitToken: biscuitToken,+ ControlPlanePublicKey: pubKey,+ RouterAddresses: routerAddrs,+ Expiration: expiration,}, nil}diff --git a/internal/controlplane/server_test.go b/internal/controlplane/server_test.goindex fe1c3b2f..d628578d 100644--- a/internal/controlplane/server_test.go+++ b/internal/controlplane/server_test.go@@ -170,15 +170,15 @@ func TestControlPlaneBasic(t *testing.T) {t.Fatalf("failed to read /info body: %v", err)}- var info api.HubInfoResponse+ var info api.ControlPlaneInfoResponseif err := proto.Unmarshal(body, &info); err != nil {- t.Fatalf("failed to unmarshal HubInfoResponse: %v", err)+ t.Fatalf("failed to unmarshal ControlPlaneInfoResponse: %v", err)}if info.OidcIssuer != issuer || info.ClientId != "sam-mesh-audience" {t.Errorf("unexpected info response claims: %+v", &info)}- if len(info.HubAddresses) != 0 {- t.Errorf("expected 0 active routers, got %d", len(info.HubAddresses))+ if len(info.RouterAddresses) != 0 {+ t.Errorf("expected 0 active routers, got %d", len(info.RouterAddresses))}// 2. Test /keys@@ -358,11 +358,11 @@ func TestNodeAndRouterRegistrationFlow(t *testing.T) {body, _ = io.ReadAll(resp.Body)_ = resp.Body.Close()- var info api.HubInfoResponse+ var info api.ControlPlaneInfoResponse_ = proto.Unmarshal(body, &info)- if !reflect.DeepEqual(info.HubAddresses, routerAddresses) {- t.Errorf("expected active routers address list %v, got %v", routerAddresses, info.HubAddresses)+ if !reflect.DeepEqual(info.RouterAddresses, routerAddresses) {+ t.Errorf("expected active routers address list %v, got %v", routerAddresses, info.RouterAddresses)}// 6. Rogue Node tries to lease as a router (lacks 'router' role)@@ -620,8 +620,8 @@ func TestEnrollmentWorkflow(t *testing.T) {if len(statusResp.BiscuitToken) == 0 {t.Fatalf("biscuit token is empty")}- if len(statusResp.HubPublicKey) == 0 {- t.Fatalf("hub public key is empty")+ if len(statusResp.ControlPlanePublicKey) == 0 {+ t.Fatalf("control plane public key is empty")}// Verify Biscuit router rights@@ -901,8 +901,8 @@ func TestNodeProactiveTokenRefresh(t *testing.T) {if err := nStore.SaveKey(privKeyBytes); err != nil {t.Fatalf("failed to save private key: %v", err)}- if err := nStore.SaveHubURL(cpURL); err != nil {- t.Fatalf("failed to save hub URL: %v", err)+ if err := nStore.SaveControlPlaneURL(cpURL); err != nil {+ t.Fatalf("failed to save control plane URL: %v", err)}if err := nStore.SaveIdentity(biscuitToken); err != nil {t.Fatalf("failed to save initial identity: %v", err)diff --git a/internal/identity/biscuit.go b/internal/identity/biscuit.goindex d7496c05..22b7fc93 100644--- a/internal/identity/biscuit.go+++ b/internal/identity/biscuit.go@@ -238,7 +238,7 @@ func VerifyBiscuitAndGetKey(biscuitData []byte, expectedPeer peer.ID, trustedPub},})- authorizer.AddCheck(api.HubStaticTimeCheck)+ authorizer.AddCheck(api.ControlPlaneStaticTimeCheck)authorizer.AddPolicy(api.AllowIfTruePolicy)if err := authorizer.Authorize(); err == nil {@@ -408,15 +408,15 @@ func VerifyAndExtractPeerID(trustedPublicKeys []ed25519.PublicKey, biscuitData [return pID, nil}-// VerifyBiscuitRole checks that the biscuit is signed by the hub's public key+// VerifyBiscuitRole checks that the biscuit is signed by the control plane's public key// and contains the specified role fact.-func VerifyBiscuitRole(biscuitData []byte, hubPubKey ed25519.PublicKey, expectedRole string) error {+func VerifyBiscuitRole(biscuitData []byte, controlPlanePubKey ed25519.PublicKey, expectedRole string) error {b, err := biscuit.Unmarshal(biscuitData)if err != nil {return fmt.Errorf("malformed biscuit: %w", err)}- authorizer, err := b.Authorizer(hubPubKey)+ authorizer, err := b.Authorizer(controlPlanePubKey)if err != nil {return fmt.Errorf("failed to create authorizer: %w", err)}diff --git a/internal/node/config_test.go b/internal/node/config_test.goindex e88825b3..f60ed1dc 100644--- a/internal/node/config_test.go+++ b/internal/node/config_test.go@@ -42,13 +42,13 @@ attenuation:# 1. Enforce strict TLS certificate expiry limit- 'check if time($time), $time < 2026-12-31T23:59:59Z;'- # local policies can contain deny rules (to restrict Hub grants) or allow rules (to override implicit denies)+ # local policies can contain deny rules (to restrict control plane grants) or allow rules (to override implicit denies)policies:# 2. Block db-writer calls during off-hours (9 PM to 6 AM)- 'deny if service("mcp", "db-writer"), current_hour($hour), $hour >= 21;'- 'deny if service("mcp", "db-writer"), current_hour($hour), $hour < 6;'- # 3. Restrict contractors from accessing db-writer even if Hub granted it+ # 3. Restrict contractors from accessing db-writer even if the control plane granted it- 'deny if service("mcp", "db-writer"), role("contractor");'# 4. Explicitly allow local admin bypassdiff --git a/internal/node/connection_monitor.go b/internal/node/connection_monitor.goindex 33989ace..8baf4e12 100644--- a/internal/node/connection_monitor.go+++ b/internal/node/connection_monitor.go@@ -6,17 +6,17 @@ import ("github.com/multiformats/go-multiaddr")-type hubConnectionManager interface {+type routerConnectionManager interface {IsConnected() bool- LoadHubConfig() ([]byte, []string, error)- ConnectAndAuthWithHub(ctx context.Context, addr multiaddr.Multiaddr) error- LoadHubURL() (string, error)+ LoadMeshConfig() ([]byte, []string, error)+ ConnectAndAuthWithRouter(ctx context.Context, addr multiaddr.Multiaddr) error+ LoadControlPlaneURL() (string, error)- SaveHubConfig(pubKey []byte, addrs []string) error+ SaveMeshConfig(pubKey []byte, addrs []string) errorUpdateRelays(addrs []multiaddr.Multiaddr)}-// checkHubConnection monitors the connection to the hub and attempts to recover it if disconnected.+// checkRouterConnection monitors the connection to the routers and attempts to recover it if disconnected.// It returns two booleans indicating the current state of the connection:// - stable: true if the connection was already established and is healthy.// - reconnected: true if the connection was lost but successfully recovered during this check.@@ -24,18 +24,18 @@ type hubConnectionManager interface {// The recovery process follows these steps:// 1. Connection Check: If already connected, return (stable=true, reconnected=false).// 2. P2P Retry: If disconnected, attempt to reconnect using the known P2P multiaddresses stored locally.-// 3. HTTP Fallback: If P2P retries fail, fall back to HTTP discovery using the stored Hub URL to fetch-// the new Hub addresses and Peer IDs, update the local config, and attempt to reconnect.+// 3. HTTP Fallback: If P2P retries fail, fall back to HTTP discovery using the stored Control plane URL to fetch+// the new router addresses and Peer IDs, update the local config, and attempt to reconnect.// 4. Total Failure: If all reconnection attempts fail, return (stable=false, reconnected=false).-func checkHubConnection(ctx context.Context, mgr hubConnectionManager) (stable bool, reconnected bool) {+func checkRouterConnection(ctx context.Context, mgr routerConnectionManager) (stable bool, reconnected bool) {if mgr.IsConnected() {return true, false}- logger.Warn("[Monitor] Disconnected from Hub. Attempting to reconnect...")+ logger.Warn("[Monitor] Disconnected from router. Attempting to reconnect...")var p2pAddrs []multiaddr.Multiaddr- if _, storedAddrs, err := mgr.LoadHubConfig(); err == nil {+ if _, storedAddrs, err := mgr.LoadMeshConfig(); err == nil {for _, addrStr := range storedAddrs {if ma, err := multiaddr.NewMultiaddr(addrStr); err == nil {p2pAddrs = append(p2pAddrs, ma)@@ -45,8 +45,8 @@ func checkHubConnection(ctx context.Context, mgr hubConnectionManager) (stable bvar connectedAddrs []multiaddr.Multiaddrfor _, addr := range p2pAddrs {- if err := mgr.ConnectAndAuthWithHub(ctx, addr); err == nil {- logger.Infof("[Monitor] Successfully reconnected to Hub via P2P: %s", addr)+ if err := mgr.ConnectAndAuthWithRouter(ctx, addr); err == nil {+ logger.Infof("[Monitor] Successfully reconnected to router via P2P: %s", addr)connectedAddrs = append(connectedAddrs, addr)}}@@ -55,38 +55,38 @@ func checkHubConnection(ctx context.Context, mgr hubConnectionManager) (stable breturn false, true}- hubURL, err := mgr.LoadHubURL()- if err != nil || hubURL == "" {+ controlPlaneURL, err := mgr.LoadControlPlaneURL()+ if err != nil || controlPlaneURL == "" {return false, false}- logger.Infof("[Monitor] Reconnect P2P failed. Discovering hub info from %s...", hubURL)- info, err := FetchHubInfo(ctx, hubURL)- if err != nil || len(info.HubAddresses) == 0 {+ logger.Infof("[Monitor] Reconnect P2P failed. Discovering control plane info from %s...", controlPlaneURL)+ info, err := FetchControlPlaneInfo(ctx, controlPlaneURL)+ if err != nil || len(info.RouterAddresses) == 0 {return false, false}- var newHubAddrs []multiaddr.Multiaddr- for _, addrStr := range info.HubAddresses {+ var newRouterAddrs []multiaddr.Multiaddr+ for _, addrStr := range info.RouterAddresses {if ma, err := multiaddr.NewMultiaddr(addrStr); err == nil {- newHubAddrs = append(newHubAddrs, ma)+ newRouterAddrs = append(newRouterAddrs, ma)}}- if len(newHubAddrs) == 0 {+ if len(newRouterAddrs) == 0 {return false, false}- if pubKeyBytes, _, err := mgr.LoadHubConfig(); err == nil {- if saveErr := mgr.SaveHubConfig(pubKeyBytes, info.HubAddresses); saveErr != nil {- logger.Errorf("[Monitor] Failed to save updated hub config: %v", saveErr)+ if pubKeyBytes, _, err := mgr.LoadMeshConfig(); err == nil {+ if saveErr := mgr.SaveMeshConfig(pubKeyBytes, info.RouterAddresses); saveErr != nil {+ logger.Errorf("[Monitor] Failed to save updated mesh config: %v", saveErr)}}var connectedAddrsFallback []multiaddr.Multiaddr- for _, addr := range newHubAddrs {- if err := mgr.ConnectAndAuthWithHub(ctx, addr); err == nil {- logger.Infof("[Monitor] Successfully reconnected to Hub via HTTP fallback: %s", addr)+ for _, addr := range newRouterAddrs {+ if err := mgr.ConnectAndAuthWithRouter(ctx, addr); err == nil {+ logger.Infof("[Monitor] Successfully reconnected to router via HTTP fallback: %s", addr)connectedAddrsFallback = append(connectedAddrsFallback, addr)}}diff --git a/internal/node/connection_monitor_test.go b/internal/node/connection_monitor_test.goindex aac250d3..b650da69 100644--- a/internal/node/connection_monitor_test.go+++ b/internal/node/connection_monitor_test.go@@ -9,59 +9,59 @@ import ("github.com/multiformats/go-multiaddr")-type mockHubConnectionManager struct {- connected bool- hubConfigErr error- storedAddrs []string- hubURLErr error- hubURL string- discoverErr error- discoverResp *api.HubInfoResponse- connectP2PErr error- connectHTTPReq bool- connectHTTPErr error- saveConfigErr error+type mockRouterConnectionManager struct {+ connected bool+ meshConfigErr error+ storedAddrs []string+ controlPlaneURLErr error+ controlPlaneURL string+ discoverErr error+ discoverResp *api.ControlPlaneInfoResponse+ connectP2PErr error+ connectHTTPReq bool+ connectHTTPErr error+ saveConfigErr error}-func (m *mockHubConnectionManager) IsConnected() bool {+func (m *mockRouterConnectionManager) IsConnected() bool {return m.connected}-func (m *mockHubConnectionManager) LoadHubConfig() ([]byte, []string, error) {- return nil, m.storedAddrs, m.hubConfigErr+func (m *mockRouterConnectionManager) LoadMeshConfig() ([]byte, []string, error) {+ return nil, m.storedAddrs, m.meshConfigErr}-func (m *mockHubConnectionManager) ConnectAndAuthWithHub(ctx context.Context, addr multiaddr.Multiaddr) error {+func (m *mockRouterConnectionManager) ConnectAndAuthWithRouter(ctx context.Context, addr multiaddr.Multiaddr) error {if m.connectHTTPReq {return m.connectHTTPErr}return m.connectP2PErr}-func (m *mockHubConnectionManager) LoadHubURL() (string, error) {- return m.hubURL, m.hubURLErr+func (m *mockRouterConnectionManager) LoadControlPlaneURL() (string, error) {+ return m.controlPlaneURL, m.controlPlaneURLErr}-func (m *mockHubConnectionManager) DiscoverHubInfo(ctx context.Context, url string) (*api.HubInfoResponse, error) {+func (m *mockRouterConnectionManager) DiscoverControlPlaneInfo(ctx context.Context, url string) (*api.ControlPlaneInfoResponse, error) {return m.discoverResp, m.discoverErr}-func (m *mockHubConnectionManager) SaveHubConfig(pubKey []byte, addrs []string) error {+func (m *mockRouterConnectionManager) SaveMeshConfig(pubKey []byte, addrs []string) error {return m.saveConfigErr}-func (m *mockHubConnectionManager) UpdateRelays(addrs []multiaddr.Multiaddr) {}+func (m *mockRouterConnectionManager) UpdateRelays(addrs []multiaddr.Multiaddr) {}-func TestCheckHubConnection(t *testing.T) {+func TestCheckRouterConnection(t *testing.T) {cases := []struct {name string- mgr *mockHubConnectionManager+ mgr *mockRouterConnectionManagerwantStable boolwantReconn bool}{{name: "already connected",- mgr: &mockHubConnectionManager{+ mgr: &mockRouterConnectionManager{connected: true,},wantStable: true,@@ -69,7 +69,7 @@ func TestCheckHubConnection(t *testing.T) {},{name: "disconnected, reconnects via P2P",- mgr: &mockHubConnectionManager{+ mgr: &mockRouterConnectionManager{connected: false,storedAddrs: []string{"/ip4/127.0.0.1/tcp/4001"},connectP2PErr: nil,@@ -79,13 +79,13 @@ func TestCheckHubConnection(t *testing.T) {},{name: "disconnected, P2P fails, reconnects via HTTP",- mgr: &mockHubConnectionManager{- connected: false,- storedAddrs: []string{"/ip4/127.0.0.1/tcp/4001"},- connectP2PErr: errors.New("p2p failed"),- hubURL: "https://hub.example.com",- discoverResp: &api.HubInfoResponse{- HubAddresses: []string{"/ip4/127.0.0.1/tcp/4002"},+ mgr: &mockRouterConnectionManager{+ connected: false,+ storedAddrs: []string{"/ip4/127.0.0.1/tcp/4001"},+ connectP2PErr: errors.New("p2p failed"),+ controlPlaneURL: "https://cp.example.com",+ discoverResp: &api.ControlPlaneInfoResponse{+ RouterAddresses: []string{"/ip4/127.0.0.1/tcp/4002"},},connectHTTPReq: true,connectHTTPErr: nil,@@ -95,13 +95,13 @@ func TestCheckHubConnection(t *testing.T) {},{name: "disconnected, all fail",- mgr: &mockHubConnectionManager{- connected: false,- storedAddrs: []string{"/ip4/127.0.0.1/tcp/4001"},- connectP2PErr: errors.New("p2p failed"),- hubURL: "https://hub.example.com",- discoverResp: &api.HubInfoResponse{- HubAddresses: []string{"/ip4/127.0.0.1/tcp/4002"},+ mgr: &mockRouterConnectionManager{+ connected: false,+ storedAddrs: []string{"/ip4/127.0.0.1/tcp/4001"},+ connectP2PErr: errors.New("p2p failed"),+ controlPlaneURL: "https://cp.example.com",+ discoverResp: &api.ControlPlaneInfoResponse{+ RouterAddresses: []string{"/ip4/127.0.0.1/tcp/4002"},},connectHTTPReq: true,connectHTTPErr: errors.New("http fallback connect failed"),@@ -111,12 +111,12 @@ func TestCheckHubConnection(t *testing.T) {},{name: "disconnected, HTTP discovery fails",- mgr: &mockHubConnectionManager{- connected: false,- storedAddrs: []string{"/ip4/127.0.0.1/tcp/4001"},- connectP2PErr: errors.New("p2p failed"),- hubURL: "https://hub.example.com",- discoverErr: errors.New("discovery failed"),+ mgr: &mockRouterConnectionManager{+ connected: false,+ storedAddrs: []string{"/ip4/127.0.0.1/tcp/4001"},+ connectP2PErr: errors.New("p2p failed"),+ controlPlaneURL: "https://cp.example.com",+ discoverErr: errors.New("discovery failed"),},wantStable: false,wantReconn: false,@@ -125,7 +125,7 @@ func TestCheckHubConnection(t *testing.T) {for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {- stable, reconnected := checkHubConnection(context.Background(), tc.mgr)+ stable, reconnected := checkRouterConnection(context.Background(), tc.mgr)if stable != tc.wantStable {t.Errorf("expected stable %v, got %v", tc.wantStable, stable)}diff --git a/internal/node/hub_config.go b/internal/node/controlplane.gosimilarity index 50%rename from internal/node/hub_config.gorename to internal/node/controlplane.goindex 145cbb1f..823d0cb7 100644--- a/internal/node/hub_config.go+++ b/internal/node/controlplane.go@@ -28,14 +28,14 @@ import ("google.golang.org/protobuf/proto")-// FetchHubInfo retrieves the latest configuration from the Hub's /info endpoint.-func FetchHubInfo(ctx context.Context, hubURL string) (*api.HubInfoResponse, error) {- if !strings.HasPrefix(hubURL, "http://") && !strings.HasPrefix(hubURL, "https://") {- hubURL = "https://" + hubURL+// FetchControlPlaneInfo retrieves the latest configuration from the control plane's /info endpoint.+func FetchControlPlaneInfo(ctx context.Context, controlPlaneURL string) (*api.ControlPlaneInfoResponse, error) {+ if !strings.HasPrefix(controlPlaneURL, "http://") && !strings.HasPrefix(controlPlaneURL, "https://") {+ controlPlaneURL = "https://" + controlPlaneURL}- hubURL = strings.TrimSuffix(hubURL, "/")+ controlPlaneURL = strings.TrimSuffix(controlPlaneURL, "/")- urlStr := hubURL + "/info"+ urlStr := controlPlaneURL + "/info"req, err := http.NewRequestWithContext(ctx, "GET", urlStr, nil)if err != nil {return nil, fmt.Errorf("failed to create HTTP request: %w", err)@@ -56,10 +56,10 @@ func FetchHubInfo(ctx context.Context, hubURL string) (*api.HubInfoResponse, err}if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("hub returned status %s: %s", resp.Status, string(body))+ return nil, fmt.Errorf("control plane returned status %s: %s", resp.Status, string(body))}- var info api.HubInfoResponse+ var info api.ControlPlaneInfoResponseif err := proto.Unmarshal(body, &info); err != nil {return nil, fmt.Errorf("failed to decode /info response: %w", err)}@@ -67,87 +67,87 @@ func FetchHubInfo(ctx context.Context, hubURL string) (*api.HubInfoResponse, errreturn &info, nil}-// SyncHubConfig loads the hub configuration from the store, attempts to refresh it-// via HTTP from the hub, and updates the store if successful.-// It returns the hub public key and the latest multiaddresses.-func SyncHubConfig(ctx context.Context, s *Store) ([]byte, []multiaddr.Multiaddr, error) {- pubKey, storedAddrsStr, err := s.LoadHubConfig()+// SyncMeshConfig loads the mesh configuration from the store, attempts to refresh it+// via HTTP from the control plane, and updates the store if successful.+// It returns the control plane public key and the latest multiaddresses.+func SyncMeshConfig(ctx context.Context, s *Store) ([]byte, []multiaddr.Multiaddr, error) {+ pubKey, storedAddrsStr, err := s.LoadMeshConfig()if err != nil {- return nil, nil, fmt.Errorf("failed to load hub config from store: %w", err)+ return nil, nil, fmt.Errorf("failed to load mesh config from store: %w", err)}- hubURL, err := s.LoadHubURL()+ controlPlaneURL, err := s.LoadControlPlaneURL()if err != nil {- return nil, nil, fmt.Errorf("failed to load hub URL from store: %w", err)+ return nil, nil, fmt.Errorf("failed to load control plane URL from store: %w", err)}- var hubAddrs []multiaddr.Multiaddr+ var routerAddrs []multiaddr.Multiaddr// Parse stored addressesfor _, addrStr := range storedAddrsStr {ma, err := multiaddr.NewMultiaddr(addrStr)if err != nil {- logger.Warnf("Failed to parse stored hub address %q: %v", addrStr, err)+ logger.Warnf("Failed to parse stored router address %q: %v", addrStr, err)continue}- hubAddrs = append(hubAddrs, ma)+ routerAddrs = append(routerAddrs, ma)}// Fallback for legacy databases: extract URL from multiaddr- if hubURL == "" && len(hubAddrs) > 0 {- for _, addr := range hubAddrs {+ if controlPlaneURL == "" && len(routerAddrs) > 0 {+ for _, addr := range routerAddrs {if val, err := addr.ValueForProtocol(multiaddr.P_DNS4); err == nil {- hubURL = "https://" + val+ controlPlaneURL = "https://" + valbreak}if val, err := addr.ValueForProtocol(multiaddr.P_DNSADDR); err == nil {- hubURL = "https://" + val+ controlPlaneURL = "https://" + valbreak}}- if hubURL != "" {- logger.Infof("Extracted legacy hub URL from multiaddrs: %s", hubURL)+ if controlPlaneURL != "" {+ logger.Infof("Extracted legacy control plane URL from multiaddrs: %s", controlPlaneURL)}}// If we have a URL, fetch the latest info- if hubURL != "" {- logger.Infof("Fetching latest hub addresses via HTTP from %s...", hubURL)- info, err := FetchHubInfo(ctx, hubURL)+ if controlPlaneURL != "" {+ logger.Infof("Fetching latest router addresses via HTTP from %s...", controlPlaneURL)+ info, err := FetchControlPlaneInfo(ctx, controlPlaneURL)if err != nil {logger.Warnf("Failed to fetch updated addresses via HTTP (using cached): %v", err)- } else if len(info.HubAddresses) > 0 {- logger.Infof("Discovered latest hub addresses: %v", info.HubAddresses)- var newHubAddrs []multiaddr.Multiaddr- for _, addrStr := range info.HubAddresses {+ } else if len(info.RouterAddresses) > 0 {+ logger.Infof("Discovered latest router addresses: %v", info.RouterAddresses)+ var newRouterAddrs []multiaddr.Multiaddr+ for _, addrStr := range info.RouterAddresses {ma, parseErr := multiaddr.NewMultiaddr(addrStr)if parseErr != nil {- logger.Warnf("Failed to parse discovered hub address %q: %v", addrStr, parseErr)+ logger.Warnf("Failed to parse discovered router address %q: %v", addrStr, parseErr)continue}- newHubAddrs = append(newHubAddrs, ma)+ newRouterAddrs = append(newRouterAddrs, ma)}- if len(newHubAddrs) > 0 {- hubAddrs = newHubAddrs+ if len(newRouterAddrs) > 0 {+ routerAddrs = newRouterAddrsif len(pubKey) > 0 {- if saveErr := s.SaveHubConfig(pubKey, info.HubAddresses); saveErr != nil {- logger.Errorf("Failed to save updated hub config to store: %v", saveErr)+ if saveErr := s.SaveMeshConfig(pubKey, info.RouterAddresses); saveErr != nil {+ logger.Errorf("Failed to save updated mesh config to store: %v", saveErr)}}}}}- return pubKey, hubAddrs, nil+ return pubKey, routerAddrs, nil}-// FetchMeshPolicy retrieves the latest mesh policy from the Hub's /policies endpoint using a biscuit token.-func FetchMeshPolicy(ctx context.Context, hubURL string, biscuitToken []byte) (*api.PolicyConfigGetResponse, error) {- if !strings.HasPrefix(hubURL, "http://") && !strings.HasPrefix(hubURL, "https://") {- hubURL = "https://" + hubURL+// FetchMeshPolicy retrieves the latest mesh policy from the control plane's /policies endpoint using a biscuit token.+func FetchMeshPolicy(ctx context.Context, controlPlaneURL string, biscuitToken []byte) (*api.PolicyConfigGetResponse, error) {+ if !strings.HasPrefix(controlPlaneURL, "http://") && !strings.HasPrefix(controlPlaneURL, "https://") {+ controlPlaneURL = "https://" + controlPlaneURL}- hubURL = strings.TrimSuffix(hubURL, "/")+ controlPlaneURL = strings.TrimSuffix(controlPlaneURL, "/")- urlStr := hubURL + "/policies"+ urlStr := controlPlaneURL + "/policies"req, err := http.NewRequestWithContext(ctx, "GET", urlStr, nil)if err != nil {return nil, fmt.Errorf("failed to create HTTP request: %w", err)@@ -170,7 +170,7 @@ func FetchMeshPolicy(ctx context.Context, hubURL string, biscuitToken []byte) (*}if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("hub returned status %s: %s", resp.Status, string(body))+ return nil, fmt.Errorf("control plane returned status %s: %s", resp.Status, string(body))}var policyResp api.PolicyConfigGetResponsediff --git a/internal/node/hub_config_test.go b/internal/node/controlplane_test.gosimilarity index 59%rename from internal/node/hub_config_test.gorename to internal/node/controlplane_test.goindex d4a38cb9..1ef342ad 100644--- a/internal/node/hub_config_test.go+++ b/internal/node/controlplane_test.go@@ -26,11 +26,11 @@ import ("google.golang.org/protobuf/proto")-func TestFetchHubInfo(t *testing.T) {- expectedInfo := &api.HubInfoResponse{- HubAddresses: []string{"/ip4/127.0.0.1/tcp/4001"},- OidcIssuer: "https://issuer.example.com",- ClientId: "client-id",+func TestFetchControlPlaneInfo(t *testing.T) {+ expectedInfo := &api.ControlPlaneInfoResponse{+ RouterAddresses: []string{"/ip4/127.0.0.1/tcp/4001"},+ OidcIssuer: "https://issuer.example.com",+ ClientId: "client-id",}body, err := proto.Marshal(expectedInfo)@@ -47,13 +47,13 @@ func TestFetchHubInfo(t *testing.T) {}))defer server.Close()- info, err := FetchHubInfo(context.Background(), server.URL)+ info, err := FetchControlPlaneInfo(context.Background(), server.URL)if err != nil {- t.Fatalf("FetchHubInfo failed: %v", err)+ t.Fatalf("FetchControlPlaneInfo failed: %v", err)}- if !reflect.DeepEqual(info.HubAddresses, expectedInfo.HubAddresses) {- t.Errorf("Expected HubAddresses %v, got %v", expectedInfo.HubAddresses, info.HubAddresses)+ if !reflect.DeepEqual(info.RouterAddresses, expectedInfo.RouterAddresses) {+ t.Errorf("Expected RouterAddresses %v, got %v", expectedInfo.RouterAddresses, info.RouterAddresses)}if info.OidcIssuer != expectedInfo.OidcIssuer {t.Errorf("Expected OidcIssuer %s, got %s", expectedInfo.OidcIssuer, info.OidcIssuer)@@ -63,29 +63,29 @@ func TestFetchHubInfo(t *testing.T) {}}-func TestFetchHubInfo_HTTPError(t *testing.T) {+func TestFetchControlPlaneInfo_HTTPError(t *testing.T) {server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusInternalServerError)}))defer server.Close()- _, err := FetchHubInfo(context.Background(), server.URL)+ _, err := FetchControlPlaneInfo(context.Background(), server.URL)if err == nil {t.Fatal("Expected error, got nil")}- if !strings.Contains(err.Error(), "hub returned status 500 Internal Server Error") {+ if !strings.Contains(err.Error(), "control plane returned status 500 Internal Server Error") {t.Errorf("Expected error to contain '500 Internal Server Error', got %v", err)}}-func TestFetchHubInfo_InvalidProto(t *testing.T) {+func TestFetchControlPlaneInfo_InvalidProto(t *testing.T) {server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusOK)_, _ = w.Write([]byte("invalid data"))}))defer server.Close()- _, err := FetchHubInfo(context.Background(), server.URL)+ _, err := FetchControlPlaneInfo(context.Background(), server.URL)if err == nil {t.Fatal("Expected error, got nil")}@@ -94,11 +94,11 @@ func TestFetchHubInfo_InvalidProto(t *testing.T) {}}-func TestSyncHubConfig(t *testing.T) {- expectedInfo := &api.HubInfoResponse{- HubAddresses: []string{"/ip4/127.0.0.1/tcp/4001"},- OidcIssuer: "https://issuer.example.com",- ClientId: "client-id",+func TestSyncMeshConfig(t *testing.T) {+ expectedInfo := &api.ControlPlaneInfoResponse{+ RouterAddresses: []string{"/ip4/127.0.0.1/tcp/4001"},+ OidcIssuer: "https://issuer.example.com",+ ClientId: "client-id",}body, err := proto.Marshal(expectedInfo)@@ -119,47 +119,47 @@ func TestSyncHubConfig(t *testing.T) {}defer store.Close() //nolint:errcheck- // Initial store is empty, so SyncHubConfig should just return empty- pubKey, addrs, err := SyncHubConfig(context.Background(), store)+ // Initial store is empty, so SyncMeshConfig should just return empty+ pubKey, addrs, err := SyncMeshConfig(context.Background(), store)if err != nil {- t.Fatalf("SyncHubConfig failed: %v", err)+ t.Fatalf("SyncMeshConfig failed: %v", err)}if len(pubKey) != 0 || len(addrs) != 0 {t.Errorf("Expected empty result for empty store, got pubKey=%v, addrs=%v", pubKey, addrs)}- // Save initial config with explicit hub URL+ // Save initial config with explicit control plane URLtestPubKey := []byte("test-pub-key")- if err := store.SaveHubConfig(testPubKey, []string{"/ip4/1.2.3.4/tcp/1234"}); err != nil {- t.Fatalf("Failed to save hub config: %v", err)+ if err := store.SaveMeshConfig(testPubKey, []string{"/ip4/1.2.3.4/tcp/1234"}); err != nil {+ t.Fatalf("Failed to save mesh config: %v", err)}- if err := store.SaveHubURL(server.URL); err != nil {- t.Fatalf("Failed to save hub url: %v", err)+ if err := store.SaveControlPlaneURL(server.URL); err != nil {+ t.Fatalf("Failed to save control plane URL: %v", err)}- // Call SyncHubConfig, it should fetch new addrs from server- pubKey, addrs, err = SyncHubConfig(context.Background(), store)+ // Call SyncMeshConfig, it should fetch new addrs from server+ pubKey, addrs, err = SyncMeshConfig(context.Background(), store)if err != nil {- t.Fatalf("SyncHubConfig failed: %v", err)+ t.Fatalf("SyncMeshConfig failed: %v", err)}if string(pubKey) != string(testPubKey) {t.Errorf("Expected pubKey %s, got %s", testPubKey, pubKey)}- if len(addrs) != 1 || addrs[0].String() != expectedInfo.HubAddresses[0] {- t.Errorf("Expected addrs %v, got %v", expectedInfo.HubAddresses, addrs)+ if len(addrs) != 1 || addrs[0].String() != expectedInfo.RouterAddresses[0] {+ t.Errorf("Expected addrs %v, got %v", expectedInfo.RouterAddresses, addrs)}// Verify the new addrs were saved to the store- savedPubKey, savedAddrsStr, err := store.LoadHubConfig()+ savedPubKey, savedAddrsStr, err := store.LoadMeshConfig()if err != nil {- t.Fatalf("Failed to load hub config: %v", err)+ t.Fatalf("Failed to load mesh config: %v", err)}if string(savedPubKey) != string(testPubKey) {t.Errorf("Expected saved pubKey %s, got %s", testPubKey, savedPubKey)}- if len(savedAddrsStr) != 1 || savedAddrsStr[0] != expectedInfo.HubAddresses[0] {- t.Errorf("Expected saved addrs %v, got %v", expectedInfo.HubAddresses, savedAddrsStr)+ if len(savedAddrsStr) != 1 || savedAddrsStr[0] != expectedInfo.RouterAddresses[0] {+ t.Errorf("Expected saved addrs %v, got %v", expectedInfo.RouterAddresses, savedAddrsStr)}}diff --git a/internal/node/enroll.go b/internal/node/enroll.goindex e7f8a387..d3b484bd 100644--- a/internal/node/enroll.go+++ b/internal/node/enroll.go@@ -59,7 +59,7 @@ func GetOrGenerateKey(s *Store) crypto.PrivKey {return priv}-func (n *SamNode) Enroll(ctx context.Context, hubURL string, jwt string) error {+func (n *SamNode) Enroll(ctx context.Context, controlPlaneURL string, jwt string) error {pubKey := n.Host.Peerstore().PubKey(n.Host.ID())pubBytes, err := crypto.MarshalPublicKey(pubKey)if err != nil {@@ -77,10 +77,10 @@ func (n *SamNode) Enroll(ctx context.Context, hubURL string, jwt string) error {return fmt.Errorf("failed to marshal enroll request: %v", err)}- if !strings.HasPrefix(hubURL, "http://") && !strings.HasPrefix(hubURL, "https://") {- return fmt.Errorf("hub address must be an HTTP or HTTPS URL for enrollment: %s", hubURL)+ if !strings.HasPrefix(controlPlaneURL, "http://") && !strings.HasPrefix(controlPlaneURL, "https://") {+ return fmt.Errorf("control plane address must be an HTTP or HTTPS URL for enrollment: %s", controlPlaneURL)}- url := hubURL + "/register"+ url := controlPlaneURL + "/register"logger.Infof("Enrolling via HTTP at %s", url)httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(data))@@ -105,7 +105,7 @@ func (n *SamNode) Enroll(ctx context.Context, hubURL string, jwt string) error {return err}- return n.connectToHubAddresses(ctx, enrollResp.HubAddresses)+ return n.connectToRouters(ctx, enrollResp.RouterAddresses)}func (n *SamNode) processEnrollResponse(resp *http.Response) (*api.EnrollResponse, error) {@@ -130,12 +130,12 @@ func (n *SamNode) processEnrollResponse(resp *http.Response) (*api.EnrollResponsif len(enrollResp.BiscuitToken) == 0 {return nil, fmt.Errorf("received empty biscuit token")}- if len(enrollResp.HubPublicKey) != ed25519.PublicKeySize {- return nil, fmt.Errorf("received invalid hub public key size: %d bytes (expected %d)", len(enrollResp.HubPublicKey), ed25519.PublicKeySize)+ if len(enrollResp.ControlPlanePublicKey) != ed25519.PublicKeySize {+ return nil, fmt.Errorf("received invalid control plane public key size: %d bytes (expected %d)", len(enrollResp.ControlPlanePublicKey), ed25519.PublicKeySize)}if n.config.RequiredRole != "" {- if err := identity.VerifyBiscuitRole(enrollResp.BiscuitToken, ed25519.PublicKey(enrollResp.HubPublicKey), n.config.RequiredRole); err != nil {+ if err := identity.VerifyBiscuitRole(enrollResp.BiscuitToken, ed25519.PublicKey(enrollResp.ControlPlanePublicKey), n.config.RequiredRole); err != nil {return nil, fmt.Errorf("enrolled biscuit token lacks required role %q: %w", n.config.RequiredRole, err)}}@@ -148,44 +148,44 @@ func (n *SamNode) processEnrollResponse(resp *http.Response) (*api.EnrollResponsif err := n.Store.SaveIdentityExpiration(enrollResp.Expiration); err != nil {return nil, fmt.Errorf("failed to save identity expiration: %v", err)}- if err := n.Store.SaveHubConfig(enrollResp.HubPublicKey, enrollResp.HubAddresses); err != nil {- return nil, fmt.Errorf("failed to save hub config: %v", err)+ if err := n.Store.SaveMeshConfig(enrollResp.ControlPlanePublicKey, enrollResp.RouterAddresses); err != nil {+ return nil, fmt.Errorf("failed to save mesh config: %v", err)}n.keysMu.Lock()- n.trustedKeys = append(n.trustedKeys, TrustedKey{Key: ed25519.PublicKey(enrollResp.HubPublicKey), ReceivedAt: time.Now()})+ n.trustedKeys = append(n.trustedKeys, TrustedKey{Key: ed25519.PublicKey(enrollResp.ControlPlanePublicKey), ReceivedAt: time.Now()})n.keysMu.Unlock()return &enrollResp, nil}-func (n *SamNode) connectToHubAddresses(ctx context.Context, addrs []string) error {+func (n *SamNode) connectToRouters(ctx context.Context, addrs []string) error {if len(addrs) == 0 {- return fmt.Errorf("failed to connect and authenticate after HTTP enrollment: control plane returned no hub addresses")+ return fmt.Errorf("failed to connect and authenticate after HTTP enrollment: control plane returned no router addresses")}var lastAuthErr errorfor _, addrStr := range addrs {addr, err := multiaddr.NewMultiaddr(addrStr)if err != nil {- logger.Warnf("Failed to parse hub address from response: %v", err)+ logger.Warnf("Failed to parse router address from response: %v", err)continue}- if err := n.ConnectAndAuthWithHub(ctx, addr); err != nil {- logger.Warnf("Failed to connect and auth with hub after enrollment: %v", err)+ if err := n.ConnectAndAuthWithRouter(ctx, addr); err != nil {+ logger.Warnf("Failed to connect and auth with router after enrollment: %v", err)lastAuthErr = err} else {- logger.Info("Successfully enrolled via HTTP and stored identity and hub config.")+ logger.Info("Successfully enrolled via HTTP and stored identity and mesh config.")return nil}}- return fmt.Errorf("failed to connect and authenticate with any hub after HTTP enrollment (last error: %v)", lastAuthErr)+ return fmt.Errorf("failed to connect and authenticate with any router after HTTP enrollment (last error: %v)", lastAuthErr)}// EnrollBootstrap enrolls the node with the control plane using a pre-shared bootstrap token.// If the enrollment status is PENDING, it polls the status endpoint until approved or rejected.-func (n *SamNode) EnrollBootstrap(ctx context.Context, hubURL string, bootstrapToken string) error {+func (n *SamNode) EnrollBootstrap(ctx context.Context, controlPlaneURL string, bootstrapToken string) error {pubKey := n.Host.Peerstore().PubKey(n.Host.ID())pubBytes, err := crypto.MarshalPublicKey(pubKey)if err != nil {@@ -203,10 +203,10 @@ func (n *SamNode) EnrollBootstrap(ctx context.Context, hubURL string, bootstrapTreturn fmt.Errorf("failed to marshal bootstrap enroll request: %w", err)}- if !strings.HasPrefix(hubURL, "http://") && !strings.HasPrefix(hubURL, "https://") {- return fmt.Errorf("hub address must be an HTTP or HTTPS URL for enrollment: %s", hubURL)+ if !strings.HasPrefix(controlPlaneURL, "http://") && !strings.HasPrefix(controlPlaneURL, "https://") {+ return fmt.Errorf("control plane address must be an HTTP or HTTPS URL for enrollment: %s", controlPlaneURL)}- url := hubURL + "/enroll"+ url := controlPlaneURL + "/enroll"logger.Infof("Enrolling via Bootstrap token at %s", url)client := &http.Client{Timeout: 30 * time.Second}@@ -260,7 +260,7 @@ func (n *SamNode) EnrollBootstrap(ctx context.Context, hubURL string, bootstrapTcase <-ctx.Done():return ctx.Err()case <-ticker.C:- statusURL := hubURL + "/enroll/status"+ statusURL := controlPlaneURL + "/enroll/status"hReq, err := http.NewRequestWithContext(ctx, "POST", statusURL, bytes.NewReader(statusData))if err != nil {return fmt.Errorf("failed to create status request: %w", err)@@ -311,11 +311,11 @@ func (n *SamNode) EnrollBootstrap(ctx context.Context, hubURL string, bootstrapTreturn fmt.Errorf("received empty biscuit token from enrollment response")}- if len(enrollResp.HubPublicKey) != ed25519.PublicKeySize {- return fmt.Errorf("received invalid hub public key size: %d bytes", len(enrollResp.HubPublicKey))+ if len(enrollResp.ControlPlanePublicKey) != ed25519.PublicKeySize {+ return fmt.Errorf("received invalid control plane public key size: %d bytes", len(enrollResp.ControlPlanePublicKey))}- if err := identity.VerifyBiscuitRole(enrollResp.BiscuitToken, ed25519.PublicKey(enrollResp.HubPublicKey), n.config.RequiredRole); err != nil {+ if err := identity.VerifyBiscuitRole(enrollResp.BiscuitToken, ed25519.PublicKey(enrollResp.ControlPlanePublicKey), n.config.RequiredRole); err != nil {return fmt.Errorf("enrolled biscuit token lacks required role %q: %w", n.config.RequiredRole, err)}@@ -328,29 +328,29 @@ func (n *SamNode) EnrollBootstrap(ctx context.Context, hubURL string, bootstrapTreturn fmt.Errorf("failed to save identity expiration: %v", err)}- if err := n.Store.SaveHubConfig(enrollResp.HubPublicKey, enrollResp.HubAddresses); err != nil {- return fmt.Errorf("failed to save hub config: %v", err)+ if err := n.Store.SaveMeshConfig(enrollResp.ControlPlanePublicKey, enrollResp.RouterAddresses); err != nil {+ return fmt.Errorf("failed to save mesh config: %v", err)}n.keysMu.Lock()- n.trustedKeys = append(n.trustedKeys, TrustedKey{Key: ed25519.PublicKey(enrollResp.HubPublicKey), ReceivedAt: time.Now()})+ n.trustedKeys = append(n.trustedKeys, TrustedKey{Key: ed25519.PublicKey(enrollResp.ControlPlanePublicKey), ReceivedAt: time.Now()})n.keysMu.Unlock()- // Connect and Auth to hub after enrollment to join the mesh- if len(enrollResp.HubAddresses) == 0 {- return fmt.Errorf("failed to connect and authenticate after bootstrap enrollment: control plane returned no hub addresses")+ // Connect and Auth to router after enrollment to join the mesh+ if len(enrollResp.RouterAddresses) == 0 {+ return fmt.Errorf("failed to connect and authenticate after bootstrap enrollment: control plane returned no router addresses")}var lastAuthErr errorvar authed bool- for _, addrStr := range enrollResp.HubAddresses {+ for _, addrStr := range enrollResp.RouterAddresses {addr, err := multiaddr.NewMultiaddr(addrStr)if err != nil {- logger.Warnf("Failed to parse hub address: %v", err)+ logger.Warnf("Failed to parse router address: %v", err)continue}- if err := n.ConnectAndAuthWithHub(ctx, addr); err != nil {- logger.Warnf("Failed to connect and auth with hub: %v", err)+ if err := n.ConnectAndAuthWithRouter(ctx, addr); err != nil {+ logger.Warnf("Failed to connect and auth with router: %v", err)lastAuthErr = err} else {authed = true@@ -359,7 +359,7 @@ func (n *SamNode) EnrollBootstrap(ctx context.Context, hubURL string, bootstrapT}if !authed {- return fmt.Errorf("failed to connect/auth with hub after bootstrap enrollment (last error: %v)", lastAuthErr)+ return fmt.Errorf("failed to connect/auth with router after bootstrap enrollment (last error: %v)", lastAuthErr)}logger.Info("Successfully enrolled via Bootstrap token and joined mesh.")diff --git a/internal/node/enroll_test.go b/internal/node/enroll_test.goindex f04bcbc6..7c1276ee 100644--- a/internal/node/enroll_test.go+++ b/internal/node/enroll_test.go@@ -57,8 +57,8 @@ func TestGetOrGenerateKey(t *testing.T) {}}-func TestEnroll_InvalidHubPublicKeySize(t *testing.T) {- // 1. Start a fake hub enrollment server+func TestEnroll_InvalidControlPlanePublicKeySize(t *testing.T) {+ // 1. Start a fake control plane enrollment serverinvalidKey := []byte("too-short") // Not ed25519.PublicKeySize (32 bytes)srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if r.URL.Path != "/register" {@@ -66,10 +66,10 @@ func TestEnroll_InvalidHubPublicKeySize(t *testing.T) {return}resp := &api.EnrollResponse{- BiscuitToken: []byte("mock-token"),- Expiration: time.Now().Add(1 * time.Hour).Unix(),- HubPublicKey: invalidKey,- HubAddresses: []string{"/ip4/127.0.0.1/tcp/4001"},+ BiscuitToken: []byte("mock-token"),+ Expiration: time.Now().Add(1 * time.Hour).Unix(),+ ControlPlanePublicKey: invalidKey,+ RouterAddresses: []string{"/ip4/127.0.0.1/tcp/4001"},}data, _ := proto.Marshal(resp)w.Header().Set("Content-Type", "application/x-protobuf")@@ -105,7 +105,7 @@ func TestEnroll_InvalidHubPublicKeySize(t *testing.T) {if err == nil {t.Fatal("Expected Enroll to fail with invalid public key size, but it succeeded")}- if !strings.Contains(err.Error(), "received invalid hub public key size") {+ if !strings.Contains(err.Error(), "received invalid control plane public key size") {t.Fatalf("Expected invalid public key size error, got: %v", err)}}@@ -155,8 +155,8 @@ func TestProcessEnrollResponse_Errors(t *testing.T) {t.Run("EmptyBiscuitToken", func(t *testing.T) {enrollResp := &api.EnrollResponse{- BiscuitToken: nil,- HubPublicKey: make([]byte, 32),+ BiscuitToken: nil,+ ControlPlanePublicKey: make([]byte, 32),}data, _ := proto.Marshal(enrollResp)resp := &http.Response{@@ -170,7 +170,7 @@ func TestProcessEnrollResponse_Errors(t *testing.T) {})}-func TestConnectToHubAddresses_EmptyAddrs(t *testing.T) {+func TestConnectToRouters_EmptyAddrs(t *testing.T) {dir := t.TempDir()store, err := NewStore(dir)if err != nil {@@ -188,8 +188,8 @@ func TestConnectToHubAddresses_EmptyAddrs(t *testing.T) {t.Fatal(err)}- err = node.connectToHubAddresses(context.Background(), nil)- if err == nil || !strings.Contains(err.Error(), "returned no hub addresses") {- t.Fatalf("Expected no hub addresses error, got: %v", err)+ err = node.connectToRouters(context.Background(), nil)+ if err == nil || !strings.Contains(err.Error(), "returned no router addresses") {+ t.Fatalf("Expected no router addresses error, got: %v", err)}}diff --git a/internal/node/gate_test.go b/internal/node/gate_test.goindex 39b3c5cd..604bc403 100644--- a/internal/node/gate_test.go+++ b/internal/node/gate_test.go@@ -99,7 +99,7 @@ func TestConnectionGater(t *testing.T) {}}-// startBareNode brings up a SamNode without hub/enrollment.+// startBareNode brings up a SamNode without control plane/enrollment.func startBareNode(t *testing.T, ctx context.Context) (*SamNode, func()) {t.Helper()dir := t.TempDir()@@ -114,7 +114,7 @@ func startBareNode(t *testing.T, ctx context.Context) (*SamNode, func()) {}node, err := NewSamNode(Options{PrivKey: priv,- HubAddrs: nil,+ RouterAddrs: nil,Store: store,MeshID: "test-mesh",DiscoveryInterval: "1s",diff --git a/internal/node/mcp.go b/internal/node/mcp.goindex 1787ff44..7fd50a18 100644--- a/internal/node/mcp.go+++ b/internal/node/mcp.go@@ -125,7 +125,7 @@ func NewMCPServer(node *SamNode) *mcp.Server {// Add the check_connectivity tool.mcp.AddTool(mcpServer, &mcp.Tool{Name: "check_connectivity",- Description: "Diagnose the node's ability to communicate with the SAM hub and the broader mesh network.",+ Description: "Diagnose the node's ability to communicate with the SAM routers and the broader mesh network.",}, node.handleCheckConnectivity)// Add the get_token_info tool.@@ -150,7 +150,7 @@ func NewMCPServer(node *SamNode) *mcp.Server {}// NewUnauthenticatedMCPServer creates a minimal MCP server that instructs the client on how to authenticate.-func NewUnauthenticatedMCPServer(hubURL string) *mcp.Server {+func NewUnauthenticatedMCPServer(controlPlaneURL string) *mcp.Server {mcpServer := mcp.NewServer(&mcp.Implementation{Name: "sam-node-mcp-unauth",Version: "0.1.0",@@ -160,7 +160,7 @@ func NewUnauthenticatedMCPServer(hubURL string) *mcp.Server {Name: "get_login_instructions",Description: "Get instructions on how to authenticate this node so it can join the SAM mesh.",}, func(ctx context.Context, req *mcp.CallToolRequest, params map[string]any) (*mcp.CallToolResult, any, error) {- msg := fmt.Sprintf("The node is unauthenticated. Please open a regular terminal and run:\n\n sam-node join %s\n\nOnce complete, restart this MCP client.", hubURL)+ msg := fmt.Sprintf("The node is unauthenticated. Please open a regular terminal and run:\n\n sam-node join %s\n\nOnce complete, restart this MCP client.", controlPlaneURL)return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: msg},@@ -178,7 +178,7 @@ func NewUnauthenticatedMCPServer(hubURL string) *mcp.Server {{Role: "user",Content: &mcp.TextContent{- Text: fmt.Sprintf("Please open a terminal and run:\n\n`sam-node join %s`\n\nAfter you finish, please restart this MCP connection.", hubURL),+ Text: fmt.Sprintf("Please open a terminal and run:\n\n`sam-node join %s`\n\nAfter you finish, please restart this MCP connection.", controlPlaneURL),},},},@@ -189,8 +189,8 @@ func NewUnauthenticatedMCPServer(hubURL string) *mcp.Server {}// NewUnauthenticatedMCPHandler creates an HTTP handler for the unauthenticated MCP server.-func NewUnauthenticatedMCPHandler(hubURL string) http.Handler {- mcpServer := NewUnauthenticatedMCPServer(hubURL)+func NewUnauthenticatedMCPHandler(controlPlaneURL string) http.Handler {+ mcpServer := NewUnauthenticatedMCPServer(controlPlaneURL)streamableHandler := mcp.NewStreamableHTTPHandler(func(request *http.Request) *mcp.Server {return mcpServerdiff --git a/internal/node/mcp_handlers.go b/internal/node/mcp_handlers.goindex bb19b3f5..9d669941 100644--- a/internal/node/mcp_handlers.go+++ b/internal/node/mcp_handlers.go@@ -204,7 +204,7 @@ func (n *SamNode) handleGetMeshInfo(ctx context.Context, req *mcp.CallToolRequesresData := map[string]any{"connected_peers": connectedPeers,"dht_size": dhtSize,- "hub_peer_id": n.HubPeerID.String(),+ "router_peer_id": n.RouterPeerID.String(),}responseBytes, err := json.Marshal(resData)if err != nil {@@ -588,13 +588,13 @@ func (n *SamNode) handleCheckConnectivity(ctx context.Context, req *mcp.CallToolstats["ping_error"] = truestats["ping_error_msg"] = "invalid peer id"}- } else if n.HubPeerID != "" {+ } else if n.RouterPeerID != "" {start := time.Now()- err := n.Host.Connect(ctx, peer.AddrInfo{ID: n.HubPeerID})- stats["hub_latency_ms"] = time.Since(start).Milliseconds()- stats["hub_error"] = err != nil+ err := n.Host.Connect(ctx, peer.AddrInfo{ID: n.RouterPeerID})+ stats["router_latency_ms"] = time.Since(start).Milliseconds()+ stats["router_error"] = err != nilif err != nil {- stats["hub_error_msg"] = err.Error()+ stats["router_error_msg"] = err.Error()}}diff --git a/internal/node/mcp_test.go b/internal/node/mcp_test.goindex 679ec940..b09878d0 100644--- a/internal/node/mcp_test.go+++ b/internal/node/mcp_test.go@@ -131,7 +131,7 @@ func TestResolveRelayAddresses(t *testing.T) {targetID := targetHost.ID()// Add a dns-based circuit address for the target node to the local host's peerstore- circuitAddrStr := fmt.Sprintf("/dns4/hub.com/tcp/4501/p2p/%s/p2p-circuit", relayID.String())+ circuitAddrStr := fmt.Sprintf("/dns4/router.com/tcp/4501/p2p/%s/p2p-circuit", relayID.String())circuitAddr, _ := multiaddr.NewMultiaddr(circuitAddrStr)localHost.Peerstore().AddAddr(targetID, circuitAddr, peerstore.PermanentAddrTTL)diff --git a/internal/node/node.go b/internal/node/node.goindex ca62c90b..7227187c 100644--- a/internal/node/node.go+++ b/internal/node/node.go@@ -121,28 +121,28 @@ func (a *nodeRelayACL) AllowConnect(src peer.ID, srcAddr multiaddr.Multiaddr, de}type SamNode struct {- config Options- Host host.Host- DHT *dht.IpfsDHT- PubSub *pubsub.PubSub- Store *Store- HubPeerID peer.ID- authenticatedHubs map[peer.ID]bool- peerLastEventTime map[string]int64- receivedMsgs map[string][]string- topics map[string]*pubsub.Topic- mu sync.Mutex- LocalPolicy *NodeConfigComplete- revokedPeers *lru.Cache[string, int64]- authPeers sync.Map- trustedKeys []TrustedKey- keysMu sync.RWMutex- MeshPolicyRules []biscuit.Rule- MeshPolicyMu sync.RWMutex- rateLimiter *PeerRateLimiter- services *ServiceRegistry- BoundHTTPAddr string- AllowLoopback bool+ config Options+ Host host.Host+ DHT *dht.IpfsDHT+ PubSub *pubsub.PubSub+ Store *Store+ RouterPeerID peer.ID+ authenticatedRouters map[peer.ID]bool+ peerLastEventTime map[string]int64+ receivedMsgs map[string][]string+ topics map[string]*pubsub.Topic+ mu sync.Mutex+ LocalPolicy *NodeConfigComplete+ revokedPeers *lru.Cache[string, int64]+ authPeers sync.Map+ trustedKeys []TrustedKey+ keysMu sync.RWMutex+ MeshPolicyRules []biscuit.Rule+ MeshPolicyMu sync.RWMutex+ rateLimiter *PeerRateLimiter+ services *ServiceRegistry+ BoundHTTPAddr string+ AllowLoopback boolauthSuccess chan struct{}authOnce sync.Once@@ -233,23 +233,23 @@ func NewSamNode(cfg Options) (*SamNode, error) {}var trustedKeys []TrustedKey- if len(cfg.HubPubKey) > 0 {- trustedKeys = []TrustedKey{{Key: cfg.HubPubKey, ReceivedAt: time.Now()}}+ if len(cfg.ControlPlanePubKey) > 0 {+ trustedKeys = []TrustedKey{{Key: cfg.ControlPlanePubKey, ReceivedAt: time.Now()}}}node := &SamNode{- config: cfg,- Store: cfg.Store,- trustedKeys: trustedKeys,- peerLastEventTime: make(map[string]int64),- receivedMsgs: make(map[string][]string),- topics: make(map[string]*pubsub.Topic),- authenticatedHubs: make(map[peer.ID]bool),- LocalPolicy: cfg.NodeConfig,- AllowLoopback: cfg.AllowLoopback,- authSuccess: make(chan struct{}),- reprovideTrigger: make(chan struct{}, 1),- logger: golog.Logger("sam-node"),+ config: cfg,+ Store: cfg.Store,+ trustedKeys: trustedKeys,+ peerLastEventTime: make(map[string]int64),+ receivedMsgs: make(map[string][]string),+ topics: make(map[string]*pubsub.Topic),+ authenticatedRouters: make(map[peer.ID]bool),+ LocalPolicy: cfg.NodeConfig,+ AllowLoopback: cfg.AllowLoopback,+ authSuccess: make(chan struct{}),+ reprovideTrigger: make(chan struct{}, 1),+ logger: golog.Logger("sam-node"),}var err error@@ -265,12 +265,12 @@ func NewSamNode(cfg Options) (*SamNode, error) {return node, nil}-// Start initializes the libp2p host, DHT, connects to the hub, and starts runtime components.+// Start initializes the libp2p host, DHT, connects to the routers, and starts runtime components.func (n *SamNode) Start(ctx context.Context) error {if biscuitBytes := n.GetIdentity(); len(biscuitBytes) > 0 {- hubPubKeyBytes, _, err := n.Store.LoadHubConfig()- if err == nil && len(hubPubKeyBytes) > 0 {- if err := identity.VerifyBiscuitRole(biscuitBytes, ed25519.PublicKey(hubPubKeyBytes), n.config.RequiredRole); err != nil {+ controlPlanePubKeyBytes, _, err := n.Store.LoadMeshConfig()+ if err == nil && len(controlPlanePubKeyBytes) > 0 {+ if err := identity.VerifyBiscuitRole(biscuitBytes, ed25519.PublicKey(controlPlanePubKeyBytes), n.config.RequiredRole); err != nil {return fmt.Errorf("loaded identity fails role requirement %q: %w", n.config.RequiredRole, err)}}@@ -279,9 +279,9 @@ func (n *SamNode) Start(ctx context.Context) error {// Layer 2: Attach the Bouncer (Gater)gater := &nodeConnGate{node: n}- // Convert Hub multiaddrs to peer.AddrInfo to use as static relays+ // Convert router multiaddrs to peer.AddrInfo to use as static relaysvar staticRelays []peer.AddrInfo- for _, addr := range n.config.HubAddrs {+ for _, addr := range n.config.RouterAddrs {resolvedAddrs, err := resolveAddrIfNeeded(ctx, addr)if err != nil {resolvedAddrs = []multiaddr.Multiaddr{addr}@@ -289,8 +289,8 @@ func (n *SamNode) Start(ctx context.Context) error {for _, resolved := range resolvedAddrs {if addrInfo, err := peer.AddrInfoFromP2pAddr(resolved); err == nil && addrInfo.ID != "" {staticRelays = append(staticRelays, *addrInfo)- if n.HubPeerID == "" {- n.HubPeerID = addrInfo.ID+ if n.RouterPeerID == "" {+ n.RouterPeerID = addrInfo.ID}} else {logger.Warnf("Failed to parse static relay addr %s: %v", resolved, err)@@ -332,7 +332,7 @@ func (n *SamNode) Start(ctx context.Context) error {}),}- // If we have a Hub, configure it as our static fallback relay for NAT hole-punching+ // If we have routers, configure them as our static fallback relays for NAT hole-punchingif len(staticRelays) > 0 {n.currentRelays = staticRelaysopts = append(opts, libp2p.EnableAutoRelayWithPeerSource(@@ -350,7 +350,7 @@ func (n *SamNode) Start(ctx context.Context) error {logger.Infof("[Relay] PeerSource context done")case <-n.authSuccess:logger.Infof("[Relay] Yielding static relays to AutoRelay")- // Shuffle the relays to distribute load evenly across Hubs+ // Shuffle the relays to distribute load evenly across routersshuffled := make([]peer.AddrInfo, len(currentRelays))copy(shuffled, currentRelays)rand.Shuffle(len(shuffled), func(i, j int) {@@ -433,9 +433,9 @@ func (n *SamNode) Start(ctx context.Context) error {var authenticated boolvar fatalAuthErr error- for _, addr := range n.config.HubAddrs {- if err := n.ConnectAndAuthWithHub(ctx, addr); err != nil {- logger.Warnf("[AuthN] Failed to bootstrap and auth with hub %s: %v", addr, err)+ for _, addr := range n.config.RouterAddrs {+ if err := n.ConnectAndAuthWithRouter(ctx, addr); err != nil {+ logger.Warnf("[AuthN] Failed to bootstrap and auth with router %s: %v", addr, err)if errors.Is(err, ErrFatalAuth) {fatalAuthErr = err}@@ -444,21 +444,21 @@ func (n *SamNode) Start(ctx context.Context) error {}}- if len(n.config.HubAddrs) > 0 && !authenticated {+ if len(n.config.RouterAddrs) > 0 && !authenticated {if fatalAuthErr != nil {return fmt.Errorf("fatal auth failure: %w", fatalAuthErr)}- return fmt.Errorf("failed to authenticate with any hub: all connection attempts failed")+ return fmt.Errorf("failed to authenticate with any router: all connection attempts failed")}if authenticated {- logger.Infof("[DHT] Bootstrapping DHT with connected hub...")+ logger.Infof("[DHT] Bootstrapping DHT with connected router...")if err := n.DHT.Bootstrap(ctx); err != nil {logger.Warnf("[DHT] Failed to trigger DHT bootstrap: %v", err)}}- // Initialize Gossipsub for Hub Events+ // Initialize Gossipsub for control plane eventsps, err := pubsub.NewGossipSub(ctx, h)if err != nil {return err@@ -503,8 +503,8 @@ func (n *SamNode) Start(ctx context.Context) error {}()}- // Listen for Network Evictions/Revocations from the Hub- go n.listenForHubEvents(ctx)+ // Listen for Network Evictions/Revocations from the control plane+ go n.listenForControlPlaneEvents(ctx)interval, err := time.ParseDuration(n.config.DiscoveryInterval)if err != nil {@@ -570,10 +570,10 @@ func (n *SamNode) startReprovideLoop(ctx context.Context, interval time.Durationfunc (n *SamNode) IsConnected() bool {n.mu.Lock()defer n.mu.Unlock()- if len(n.authenticatedHubs) == 0 {+ if len(n.authenticatedRouters) == 0 {return false}- for pid := range n.authenticatedHubs {+ for pid := range n.authenticatedRouters {if n.Host.Network().Connectedness(pid) == network.Connected {return true}@@ -581,16 +581,16 @@ func (n *SamNode) IsConnected() bool {return false}-func (n *SamNode) LoadHubConfig() ([]byte, []string, error) {- return n.Store.LoadHubConfig()+func (n *SamNode) LoadMeshConfig() ([]byte, []string, error) {+ return n.Store.LoadMeshConfig()}-func (n *SamNode) LoadHubURL() (string, error) {- return n.Store.LoadHubURL()+func (n *SamNode) LoadControlPlaneURL() (string, error) {+ return n.Store.LoadControlPlaneURL()}-func (n *SamNode) SaveHubConfig(pubKey []byte, addrs []string) error {- return n.Store.SaveHubConfig(pubKey, addrs)+func (n *SamNode) SaveMeshConfig(pubKey []byte, addrs []string) error {+ return n.Store.SaveMeshConfig(pubKey, addrs)}func (n *SamNode) startConnectionMonitor(ctx context.Context, bootstrapDuration, checkInterval time.Duration, maxFailures int) {@@ -611,11 +611,11 @@ func (n *SamNode) startConnectionMonitor(ctx context.Context, bootstrapDuration,case <-ctx.Done():returncase <-ticker.C:- stable, reconnected := checkHubConnection(ctx, n)+ stable, reconnected := checkRouterConnection(ctx, n)if stable {if consecutiveFailures > 0 {- logger.Infof("[Monitor] Connection to hub is stable. Resetting failure count.")+ logger.Infof("[Monitor] Connection to router is stable. Resetting failure count.")consecutiveFailures = 0}continue@@ -633,9 +633,9 @@ func (n *SamNode) startConnectionMonitor(ctx context.Context, bootstrapDuration,}consecutiveFailures++- logger.Errorf("[Monitor] Failed to reconnect to the hub. Consecutive failures: %d/%d", consecutiveFailures, maxFailures)+ logger.Errorf("[Monitor] Failed to reconnect to a router. Consecutive failures: %d/%d", consecutiveFailures, maxFailures)if consecutiveFailures >= maxFailures {- logger.Fatalf("[Monitor] Failed to reconnect to the hub for %d consecutive checks. Exiting to avoid network partition.", maxFailures)+ logger.Fatalf("[Monitor] Failed to reconnect to a router for %d consecutive checks. Exiting to avoid network partition.", maxFailures)}}}@@ -643,7 +643,7 @@ func (n *SamNode) startConnectionMonitor(ctx context.Context, bootstrapDuration,}func (n *SamNode) RegisterStaticServices(ctx context.Context, services []api.ServiceConfig) error {- // Wait for node to be connected to a hub or DHT to be ready+ // Wait for node to be connected to a router or DHT to be ready// This avoids failure if we try to register immediately after enrollment// before the connection is established.ticker := time.NewTicker(100 * time.Millisecond)@@ -685,7 +685,7 @@ dhtLoop:return nil}-func (n *SamNode) ConnectAndAuthWithHub(ctx context.Context, addr multiaddr.Multiaddr) error {+func (n *SamNode) ConnectAndAuthWithRouter(ctx context.Context, addr multiaddr.Multiaddr) error {resolvedAddrs, err := resolveAddrIfNeeded(ctx, addr)if err != nil {resolvedAddrs = []multiaddr.Multiaddr{addr}@@ -712,14 +712,14 @@ func (n *SamNode) ConnectAndAuthWithHub(ctx context.Context, addr multiaddr.Mult}// Create a per-replica timeout context to prevent blocking on offline replicas- replicaCtx, cancel := context.WithTimeout(ctx, n.config.HubConnectTimeout)+ replicaCtx, cancel := context.WithTimeout(ctx, n.config.RouterConnectTimeout)if err := n.Host.Connect(replicaCtx, *addrInfo); err != nil {cancel()if strings.Contains(err.Error(), "peer id mismatch") {lastFatalErr = fmt.Errorf("%w: %w", ErrFatalAuth, err)}- errs = append(errs, fmt.Errorf("failed to connect to hub %s: %w", resolved, err))+ errs = append(errs, fmt.Errorf("failed to connect to router %s: %w", resolved, err))continue}@@ -727,16 +727,16 @@ func (n *SamNode) ConnectAndAuthWithHub(ctx context.Context, addr multiaddr.Mults, err := n.Host.NewStream(replicaCtx, addrInfo.ID, api.AuthProtocolID)if err != nil {cancel()- errs = append(errs, fmt.Errorf("failed to open auth stream to hub %s: %w", resolved, err))+ errs = append(errs, fmt.Errorf("failed to open auth stream to router %s: %w", resolved, err))continue}_ = s.SetDeadline(time.Now().Add(5 * time.Second))- success, err := n.performHubAuthHandshake(s, biscuitBytes, addrInfo.ID)+ success, err := n.performRouterAuthHandshake(s, biscuitBytes, addrInfo.ID)if err != nil {_ = s.Reset()cancel()- errs = append(errs, fmt.Errorf("handshake failed with hub %s: %w", resolved, err))+ errs = append(errs, fmt.Errorf("handshake failed with router %s: %w", resolved, err))if errors.Is(err, ErrFatalAuth) {lastFatalErr = err}@@ -747,10 +747,10 @@ func (n *SamNode) ConnectAndAuthWithHub(ctx context.Context, addr multiaddr.Multif success {n.mu.Lock()- n.authenticatedHubs[addrInfo.ID] = true- n.HubPeerID = addrInfo.ID+ n.authenticatedRouters[addrInfo.ID] = true+ n.RouterPeerID = addrInfo.IDn.mu.Unlock()- logger.Infof("[AuthN] Successfully authenticated with hub via libp2p: %s", addrInfo.ID)+ logger.Infof("[AuthN] Successfully authenticated with router via libp2p: %s", addrInfo.ID)connected = true}}@@ -765,10 +765,10 @@ func (n *SamNode) ConnectAndAuthWithHub(ctx context.Context, addr multiaddr.Multif lastFatalErr != nil {return lastFatalErr}- return fmt.Errorf("failed to authenticate with any hub addresses: %w", errors.Join(errs...))+ return fmt.Errorf("failed to authenticate with any router addresses: %w", errors.Join(errs...))}-func (n *SamNode) performHubAuthHandshake(s network.Stream, biscuitBytes []byte, expectedRouter peer.ID) (bool, error) {+func (n *SamNode) performRouterAuthHandshake(s network.Stream, biscuitBytes []byte, expectedRouter peer.ID) (bool, error) {writer := msgio.NewVarintWriter(s)authFrame := &api.AuthFrame{Biscuit: biscuitBytes}data, err := proto.Marshal(authFrame)@@ -904,11 +904,11 @@ func (n *SamNode) StartRenewalLoop(ctx context.Context, issuerURL, clientID, cli}if fetchErr == nil {- hubURL, loadErr := n.Store.LoadHubURL()+ controlPlaneURL, loadErr := n.Store.LoadControlPlaneURL()if loadErr != nil {- fetchErr = fmt.Errorf("failed to load hub URL for renewal: %w", loadErr)+ fetchErr = fmt.Errorf("failed to load control plane URL for renewal: %w", loadErr)} else {- fetchErr = n.Enroll(ctx, hubURL, newJWT)+ fetchErr = n.Enroll(ctx, controlPlaneURL, newJWT)}}@@ -975,16 +975,16 @@ func (n *SamNode) RefreshEnrollment(ctx context.Context) error {return fmt.Errorf("failed to marshal request: %w", err)}- hubURL, err := n.Store.LoadHubURL()+ controlPlaneURL, err := n.Store.LoadControlPlaneURL()if err != nil {- return fmt.Errorf("failed to load hub URL: %w", err)+ return fmt.Errorf("failed to load control plane URL: %w", err)}- if !strings.HasPrefix(hubURL, "http://") && !strings.HasPrefix(hubURL, "https://") {- return fmt.Errorf("hub address must be an HTTP or HTTPS URL for renewal: %s", hubURL)+ if !strings.HasPrefix(controlPlaneURL, "http://") && !strings.HasPrefix(controlPlaneURL, "https://") {+ return fmt.Errorf("control plane address must be an HTTP or HTTPS URL for renewal: %s", controlPlaneURL)}- url := hubURL + "/refresh"+ url := controlPlaneURL + "/refresh"httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(reqData))if err != nil {return fmt.Errorf("failed to create http request: %w", err)@@ -1079,8 +1079,8 @@ func (n *SamNode) renewWithRefreshToken(ctx context.Context, clientSecret stringreturn newJWT, nil}-// listenForHubEvents listens to the topic established by the Hub-func (n *SamNode) listenForHubEvents(ctx context.Context) {+// listenForControlPlaneEvents listens to the topic established by the control plane+func (n *SamNode) listenForControlPlaneEvents(ctx context.Context) {topic, err := n.PubSub.Join(api.GossipEvents)if err != nil {return@@ -1107,10 +1107,10 @@ func (n *SamNode) listenForHubEvents(ctx context.Context) {continue}- // Since the signature is verified against our list of trusted hub public keys+ // Since the signature is verified against our list of trusted control plane public keys// in verifyEvent below, any message with a valid signature is cryptographically- // proven to have been authored by one of the hubs. We do not restrict msg.GetFrom()- // to a single HubPeerID because there can be multiple hub replicas in a cluster,+ // proven to have been authored by one of the control planes. We do not restrict msg.GetFrom()+ // to a single RouterPeerID because there can be multiple control plane replicas in a cluster,// each with its own PeerID.if !n.verifyEvent(&event) {@@ -1496,11 +1496,11 @@ func (n *SamNode) findProvidersByCID(ctx context.Context, c cid.Cid) ([]peer.Add}providers := make([]peer.AddrInfo, 0, len(providersMap))for _, p := range providersMap {- hubAddrsCount := 0- if n.HubPeerID != "" {- hubAddrsCount = len(n.Host.Peerstore().Addrs(n.HubPeerID))+ routerAddrsCount := 0+ if n.RouterPeerID != "" {+ routerAddrsCount = len(n.Host.Peerstore().Addrs(n.RouterPeerID))}- logger.Infof("[Discovery] Evaluating relay for %s: HubPeerID=%s, HubAddrsCount=%d", p.ID, n.HubPeerID, hubAddrsCount)+ logger.Infof("[Discovery] Evaluating relay for %s: RouterPeerID=%s, RouterAddrsCount=%d", p.ID, n.RouterPeerID, routerAddrsCount)for _, addr := range p.Addrs {logger.Infof("[Discovery] Provider %s advertised address: %s", p.ID, addr)@@ -1953,9 +1953,9 @@ func hasCircuit(addr multiaddr.Multiaddr) bool {}func (n *SamNode) syncMeshPolicy(ctx context.Context) error {- hubURL, err := n.Store.LoadHubURL()- if err != nil || hubURL == "" {- return fmt.Errorf("hub URL not found in store")+ controlPlaneURL, err := n.Store.LoadControlPlaneURL()+ if err != nil || controlPlaneURL == "" {+ return fmt.Errorf("control plane URL not found in store")}token := n.GetIdentity()@@ -1963,7 +1963,7 @@ func (n *SamNode) syncMeshPolicy(ctx context.Context) error {return fmt.Errorf("node has no identity token to fetch mesh policy")}- policyResp, err := FetchMeshPolicy(ctx, hubURL, token)+ policyResp, err := FetchMeshPolicy(ctx, controlPlaneURL, token)if err != nil {return fmt.Errorf("failed to fetch mesh policy: %w", err)}diff --git a/internal/node/node_test.go b/internal/node/node_test.goindex 4f3414d5..00be2bb4 100644--- a/internal/node/node_test.go+++ b/internal/node/node_test.go@@ -102,7 +102,7 @@ func TestConnectionMonitor_CrashesAfterFailures(t *testing.T) {store, _ := NewStore(t.TempDir())node, err := NewSamNode(Options{PrivKey: priv,- HubAddrs: nil,+ RouterAddrs: nil,Store: store,MeshID: "test",DiscoveryInterval: "10s",diff --git a/internal/node/options.go b/internal/node/options.goindex fff8ef8a..3f408e55 100644--- a/internal/node/options.go+++ b/internal/node/options.go@@ -25,17 +25,17 @@ import ()const (- DefaultMeshName = "public-mesh"- DefaultDiscoveryInterval = "30s"- DefaultConfigFile = "sam-node.yaml"- DefaultHubConnectTimeout = 5 * time.Second+ DefaultMeshName = "public-mesh"+ DefaultDiscoveryInterval = "30s"+ DefaultConfigFile = "sam-node.yaml"+ DefaultRouterConnectTimeout = 5 * time.Second)// Options holds all configuration options for a SamNode.type Options struct {PrivKey crypto.PrivKey- HubPubKey ed25519.PublicKey- HubAddrs []multiaddr.Multiaddr+ ControlPlanePubKey ed25519.PublicKey+ RouterAddrs []multiaddr.MultiaddrStore *StoreMeshID stringDiscoveryInterval string@@ -49,8 +49,8 @@ type Options struct {AutoRelayMinInterval time.DurationAutoRelayBootDelay time.DurationAutoRelayBackoff time.Duration- // HubConnectTimeout bounds each hub address's dial (connect + stream open).- HubConnectTimeout time.Duration+ // RouterConnectTimeout bounds each router address's dial (connect + stream open).+ RouterConnectTimeout time.Duration// DHT OptionsDHTProviderAddrTTL time.DurationDHTMaxRecordAge time.Duration@@ -58,7 +58,7 @@ type Options struct {DiscoveryConcurrency int// RequiredRole restricts enrollment and startup to only accept tokens containing this role.RequiredRole string- // PolicySyncInterval specifies how often the node syncs the mesh policy from the Hub.+ // PolicySyncInterval specifies how often the node syncs the mesh policy from the control plane.PolicySyncInterval time.Duration}@@ -85,8 +85,8 @@ func (o *Options) Default() {if o.KeyGracePeriod == 0 {o.KeyGracePeriod = 24 * time.Hour}- if o.HubConnectTimeout == 0 {- o.HubConnectTimeout = DefaultHubConnectTimeout+ if o.RouterConnectTimeout == 0 {+ o.RouterConnectTimeout = DefaultRouterConnectTimeout}if o.DHTLookupLimit <= 0 {o.DHTLookupLimit = 20diff --git a/internal/node/proxy_test.go b/internal/node/proxy_test.goindex a18dcdf9..febb2c7b 100644--- a/internal/node/proxy_test.go+++ b/internal/node/proxy_test.go@@ -57,7 +57,7 @@ func TestDatapathIntegration(t *testing.T) {nodeA, err := NewSamNode(Options{PrivKey: privA,- HubAddrs: nil,+ RouterAddrs: nil,Store: storeA,MeshID: "test-mesh",DiscoveryInterval: "1s",@@ -84,7 +84,7 @@ func TestDatapathIntegration(t *testing.T) {nodeB, err := NewSamNode(Options{PrivKey: privB,- HubAddrs: nil,+ RouterAddrs: nil,Store: storeB,MeshID: "test-mesh",DiscoveryInterval: "1s",@@ -261,7 +261,7 @@ func TestDatapathIntegration_Unauthenticated(t *testing.T) {nodeA, err := NewSamNode(Options{PrivKey: privA,- HubAddrs: nil,+ RouterAddrs: nil,Store: storeA,MeshID: "test-mesh",DiscoveryInterval: "1s",@@ -288,7 +288,7 @@ func TestDatapathIntegration_Unauthenticated(t *testing.T) {nodeB, err := NewSamNode(Options{PrivKey: privB,- HubAddrs: nil,+ RouterAddrs: nil,Store: storeB,MeshID: "test-mesh",DiscoveryInterval: "1s",@@ -410,7 +410,7 @@ func TestStdioDatapathIntegration(t *testing.T) {nodeA, err := NewSamNode(Options{PrivKey: privA,- HubAddrs: nil,+ RouterAddrs: nil,Store: storeA,MeshID: "test-mesh",DiscoveryInterval: "1s",@@ -433,7 +433,7 @@ func TestStdioDatapathIntegration(t *testing.T) {nodeB, err := NewSamNode(Options{PrivKey: privB,- HubAddrs: nil,+ RouterAddrs: nil,Store: storeB,MeshID: "test-mesh",DiscoveryInterval: "1s",@@ -600,7 +600,7 @@ func TestDatapathHeadersAndRoutingTable(t *testing.T) {nodeA, err := NewSamNode(Options{PrivKey: privA,- HubAddrs: nil,+ RouterAddrs: nil,Store: storeA,MeshID: "test-mesh",DiscoveryInterval: "1s",@@ -627,7 +627,7 @@ func TestDatapathHeadersAndRoutingTable(t *testing.T) {nodeB, err := NewSamNode(Options{PrivKey: privB,- HubAddrs: nil,+ RouterAddrs: nil,Store: storeB,MeshID: "test-mesh",DiscoveryInterval: "1s",diff --git a/internal/node/sidecar.go b/internal/node/sidecar.goindex 738b16c2..ab7fef4b 100644--- a/internal/node/sidecar.go+++ b/internal/node/sidecar.go@@ -125,7 +125,7 @@ func StartSidecarServer(node *SamNode, addr, token, certFile, keyFile, caFile streturn server, nil}-func StartUnauthSidecarServer(hubURL, addr, certFile, keyFile string) (*http.Server, error) {+func StartUnauthSidecarServer(controlPlaneURL, addr, certFile, keyFile string) (*http.Server, error) {mux := http.NewServeMux()// Public endpoints@@ -133,7 +133,7 @@ func StartUnauthSidecarServer(hubURL, addr, certFile, keyFile string) (*http.Sermux.HandleFunc("/readyz", handleReadyz)// Mount Unauthenticated MCP handler- mcpHandler := NewUnauthenticatedMCPHandler(hubURL)+ mcpHandler := NewUnauthenticatedMCPHandler(controlPlaneURL)mux.Handle("/", mcpHandler)server := &http.Server{diff --git a/internal/node/static_service_test.go b/internal/node/static_service_test.goindex f74fc55d..0c932bce 100644--- a/internal/node/static_service_test.go+++ b/internal/node/static_service_test.go@@ -25,7 +25,7 @@ import ("google.golang.org/protobuf/proto")-func startMockLibp2pHub(t *testing.T) (peer.ID, string) {+func startMockRouter(t *testing.T) (peer.ID, string) {t.Helper()h, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"))if err != nil {@@ -34,7 +34,7 @@ func startMockLibp2pHub(t *testing.T) (peer.ID, string) {kdht, err := dht.New(h, dht.Mode(dht.ModeServer), dht.ProtocolPrefix("/sam"))if err != nil {- t.Fatalf("failed to create DHT on mock hub: %v", err)+ t.Fatalf("failed to create DHT on mock router: %v", err)}// Generate mock control plane keys@@ -125,9 +125,9 @@ func startMockLibp2pHub(t *testing.T) (peer.ID, string) {}resp := &api.EnrollResponse{- BiscuitToken: biscuitBytes,- HubPublicKey: cpPub,- HubAddresses: []string{h.Addrs()[0].String() + "/p2p/" + h.ID().String()},+ BiscuitToken: biscuitBytes,+ ControlPlanePublicKey: cpPub,+ RouterAddresses: []string{h.Addrs()[0].String() + "/p2p/" + h.ID().String()},}data, err := proto.Marshal(resp)if err != nil {@@ -151,8 +151,8 @@ func startMockLibp2pHub(t *testing.T) (peer.ID, string) {}func TestStaticServiceRegistrationRequiresConnection(t *testing.T) {- // 1. Setup mock hub- _, hubURL := startMockLibp2pHub(t)+ // 1. Setup mock router+ _, routerAddr := startMockRouter(t)// 2. Create temp storetmpDir := t.TempDir()@@ -167,10 +167,10 @@ func TestStaticServiceRegistrationRequiresConnection(t *testing.T) {t.Fatalf("failed to generate libp2p key: %v", err)}- // 4. Create Node with empty hub addrs initially+ // 4. Create Node with empty router addrs initiallynode, err := NewSamNode(Options{PrivKey: priv,- HubAddrs: []multiaddr.Multiaddr{},+ RouterAddrs: []multiaddr.Multiaddr{},Store: store,MeshID: "test-mesh",DiscoveryInterval: "100ms",@@ -199,7 +199,7 @@ func TestStaticServiceRegistrationRequiresConnection(t *testing.T) {upstream := httptest.NewServer(newFakeMCPHandler(t, []*mcp.Tool{}))defer upstream.Close()- // 5. Try to register static services BEFORE connecting to hub+ // 5. Try to register static services BEFORE connecting to routerservices := []api.ServiceConfig{{Type: "mcp",@@ -213,14 +213,14 @@ func TestStaticServiceRegistrationRequiresConnection(t *testing.T) {defer cancel()err = node.RegisterStaticServices(ctxTimeout, services)if err == nil {- t.Fatal("Expected RegisterStaticServices to fail before connecting to hub, but it succeeded")+ t.Fatal("Expected RegisterStaticServices to fail before connecting to router, but it succeeded")}if !strings.Contains(err.Error(), "timeout waiting for DHT to be ready") && !errors.Is(err, context.DeadlineExceeded) {t.Fatalf("Expected error to indicate timeout or deadline exceeded, got: %v", err)}- // 6. Now enroll and connect to hub (which sets up DHT and hub connection)- err = node.Enroll(ctx, hubURL, "dummy-jwt")+ // 6. Now enroll and connect to router (which sets up DHT and router connection)+ err = node.Enroll(ctx, routerAddr, "dummy-jwt")if err != nil {t.Fatalf("failed to enroll: %v", err)}@@ -238,8 +238,8 @@ func TestStaticServiceRegistrationRequiresConnection(t *testing.T) {}func TestStaticServiceRegistrationCommandFailure(t *testing.T) {- // 1. Setup mock hub- _, hubURL := startMockLibp2pHub(t)+ // 1. Setup mock router+ _, routerAddr := startMockRouter(t)// 2. Create temp storetmpDir := t.TempDir()@@ -254,10 +254,10 @@ func TestStaticServiceRegistrationCommandFailure(t *testing.T) {t.Fatalf("failed to generate libp2p key: %v", err)}- // 4. Create Node with empty hub addrs initially+ // 4. Create Node with empty router addrs initiallynode, err := NewSamNode(Options{PrivKey: priv,- HubAddrs: []multiaddr.Multiaddr{},+ RouterAddrs: []multiaddr.Multiaddr{},Store: store,MeshID: "test-mesh",DiscoveryInterval: "100ms",@@ -282,8 +282,8 @@ func TestStaticServiceRegistrationCommandFailure(t *testing.T) {}}()- // 5. Enroll and connect to hub (which sets up DHT and hub connection)- err = node.Enroll(ctx, hubURL, "dummy-jwt")+ // 5. Enroll and connect to router (which sets up DHT and router connection)+ err = node.Enroll(ctx, routerAddr, "dummy-jwt")if err != nil {t.Fatalf("failed to enroll: %v", err)}diff --git a/internal/node/store.go b/internal/node/store.goindex e6e2cec9..7bc4427e 100644--- a/internal/node/store.go+++ b/internal/node/store.go@@ -195,28 +195,28 @@ func (s *Store) LoadKey() ([]byte, error) {return val, nil}-func (s *Store) SaveHubConfig(pubKey []byte, addrs []string) error {+func (s *Store) SaveMeshConfig(pubKey []byte, addrs []string) error {return s.db.Update(func(tx *bbolt.Tx) error {b := tx.Bucket([]byte(bucketIdentity))- if err := b.Put([]byte("hub_public_key"), pubKey); err != nil {+ if err := b.Put([]byte("control_plane_public_key"), pubKey); err != nil {return err}data, _ := json.Marshal(addrs)- return b.Put([]byte("hub_addresses"), data)+ return b.Put([]byte("router_addresses"), data)})}-func (s *Store) LoadHubConfig() ([]byte, []string, error) {+func (s *Store) LoadMeshConfig() ([]byte, []string, error) {var pubKey []bytevar addrs []stringerr := s.db.View(func(tx *bbolt.Tx) error {b := tx.Bucket([]byte(bucketIdentity))- dbVal := b.Get([]byte("hub_public_key"))+ dbVal := b.Get([]byte("control_plane_public_key"))if len(dbVal) > 0 {pubKey = make([]byte, len(dbVal))copy(pubKey, dbVal)}- addrsBytes := b.Get([]byte("hub_addresses"))+ addrsBytes := b.Get([]byte("router_addresses"))if len(addrsBytes) > 0 {return json.Unmarshal(addrsBytes, &addrs)}@@ -225,18 +225,18 @@ func (s *Store) LoadHubConfig() ([]byte, []string, error) {return pubKey, addrs, err}-func (s *Store) SaveHubURL(url string) error {+func (s *Store) SaveControlPlaneURL(url string) error {return s.db.Update(func(tx *bbolt.Tx) error {b := tx.Bucket([]byte(bucketIdentity))- return b.Put([]byte("hub_url"), []byte(url))+ return b.Put([]byte("control_plane_url"), []byte(url))})}-func (s *Store) LoadHubURL() (string, error) {+func (s *Store) LoadControlPlaneURL() (string, error) {var val []byteerr := s.db.View(func(tx *bbolt.Tx) error {b := tx.Bucket([]byte(bucketIdentity))- val = b.Get([]byte("hub_url"))+ val = b.Get([]byte("control_plane_url"))return nil})return string(val), errdiff --git a/internal/node/store_test.go b/internal/node/store_test.goindex 1c2ae213..98a24ecb 100644--- a/internal/node/store_test.go+++ b/internal/node/store_test.go@@ -213,7 +213,7 @@ func TestStore_Key(t *testing.T) {}}-func TestStore_HubConfig(t *testing.T) {+func TestStore_MeshConfig(t *testing.T) {store, err := NewStore(t.TempDir())if err != nil {t.Fatalf("Failed to create store: %v", err)@@ -225,35 +225,35 @@ func TestStore_HubConfig(t *testing.T) {}()// Loading when not set- pubKey, addrs, err := store.LoadHubConfig()+ pubKey, addrs, err := store.LoadMeshConfig()if err != nil {- t.Fatalf("LoadHubConfig failed: %v", err)+ t.Fatalf("LoadMeshConfig failed: %v", err)}if len(pubKey) > 0 || len(addrs) > 0 {- t.Errorf("Expected empty hub config, got pubKey=%v, addrs=%v", pubKey, addrs)+ t.Errorf("Expected empty mesh config, got pubKey=%v, addrs=%v", pubKey, addrs)}- hubPubKey := []byte("hub-public-key-bytes")- hubAddrs := []string{"/ip4/127.0.0.1/tcp/5001", "/dns4/hub.example.com/tcp/5001"}+ controlPlanePubKey := []byte("control-plane-public-key-bytes")+ routerAddrs := []string{"/ip4/127.0.0.1/tcp/5001", "/dns4/cp.example.com/tcp/5001"}- if err := store.SaveHubConfig(hubPubKey, hubAddrs); err != nil {- t.Fatalf("SaveHubConfig failed: %v", err)+ if err := store.SaveMeshConfig(controlPlanePubKey, routerAddrs); err != nil {+ t.Fatalf("SaveMeshConfig failed: %v", err)}- loadedPubKey, loadedAddrs, err := store.LoadHubConfig()+ loadedPubKey, loadedAddrs, err := store.LoadMeshConfig()if err != nil {- t.Fatalf("LoadHubConfig failed: %v", err)+ t.Fatalf("LoadMeshConfig failed: %v", err)}- if !bytes.Equal(loadedPubKey, hubPubKey) {- t.Errorf("Expected loaded hub pubkey %v, got %v", hubPubKey, loadedPubKey)+ if !bytes.Equal(loadedPubKey, controlPlanePubKey) {+ t.Errorf("Expected loaded control plane pubkey %v, got %v", controlPlanePubKey, loadedPubKey)}- if !reflect.DeepEqual(loadedAddrs, hubAddrs) {- t.Errorf("Expected loaded hub addrs %v, got %v", hubAddrs, loadedAddrs)+ if !reflect.DeepEqual(loadedAddrs, routerAddrs) {+ t.Errorf("Expected loaded router addrs %v, got %v", routerAddrs, loadedAddrs)}}-func TestStore_HubURL(t *testing.T) {+func TestStore_ControlPlaneURL(t *testing.T) {store, err := NewStore(t.TempDir())if err != nil {t.Fatalf("Failed to create store: %v", err)@@ -265,26 +265,26 @@ func TestStore_HubURL(t *testing.T) {}()// Loading when not set- url, err := store.LoadHubURL()+ url, err := store.LoadControlPlaneURL()if err != nil {- t.Fatalf("LoadHubURL failed: %v", err)+ t.Fatalf("LoadControlPlaneURL failed: %v", err)}if url != "" {- t.Errorf("Expected empty Hub URL, got %q", url)+ t.Errorf("Expected empty Control plane URL, got %q", url)}- hubURL := "https://hub.example.com"- if err := store.SaveHubURL(hubURL); err != nil {- t.Fatalf("SaveHubURL failed: %v", err)+ controlPlaneURL := "https://cp.example.com"+ if err := store.SaveControlPlaneURL(controlPlaneURL); err != nil {+ t.Fatalf("SaveControlPlaneURL failed: %v", err)}- loaded, err := store.LoadHubURL()+ loaded, err := store.LoadControlPlaneURL()if err != nil {- t.Fatalf("LoadHubURL failed: %v", err)+ t.Fatalf("LoadControlPlaneURL failed: %v", err)}- if loaded != hubURL {- t.Errorf("Expected loaded hub URL %q, got %q", hubURL, loaded)+ if loaded != controlPlaneURL {+ t.Errorf("Expected loaded control plane URL %q, got %q", controlPlaneURL, loaded)}}diff --git a/internal/router/router.go b/internal/router/router.goindex d1fff235..542b36f4 100644--- a/internal/router/router.go+++ b/internal/router/router.go@@ -264,7 +264,7 @@ func (r *Router) Start() error {go r.runKeysSyncLoop()go r.runFederationLoop()go r.runBiscuitRenewalLoop()- go r.listenForHubEvents(r.ctx)+ go r.listenForControlPlaneEvents(r.ctx)r.isReady.Store(true)logger.Infof("Router Online. PeerID: %s, ListenAddrs: %v", r.Host.ID(), r.Host.Addrs())@@ -314,10 +314,10 @@ func (r *Router) enroll(peerID peer.ID) error {r.keysMu.Lock()r.biscuitToken = enrollResp.BiscuitTokenr.biscuitExpiration = time.Unix(enrollResp.Expiration, 0)- r.trustedPublicKeys = []ed25519.PublicKey{enrollResp.HubPublicKey}+ r.trustedPublicKeys = []ed25519.PublicKey{enrollResp.ControlPlanePublicKey}r.keysMu.Unlock()- if err := identity.VerifyBiscuitRole(enrollResp.BiscuitToken, enrollResp.HubPublicKey, r.config.RequiredRole); err != nil {+ if err := identity.VerifyBiscuitRole(enrollResp.BiscuitToken, enrollResp.ControlPlanePublicKey, r.config.RequiredRole); err != nil {return fmt.Errorf("enrolled biscuit token lacks required role %q: %w", r.config.RequiredRole, err)}@@ -436,10 +436,10 @@ func (r *Router) enrollBootstrap(peerID peer.ID) error {r.keysMu.Lock()r.biscuitToken = enrollResp.BiscuitTokenr.biscuitExpiration = time.Unix(enrollResp.Expiration, 0)- r.trustedPublicKeys = []ed25519.PublicKey{enrollResp.HubPublicKey}+ r.trustedPublicKeys = []ed25519.PublicKey{enrollResp.ControlPlanePublicKey}r.keysMu.Unlock()- if err := identity.VerifyBiscuitRole(enrollResp.BiscuitToken, enrollResp.HubPublicKey, r.config.RequiredRole); err != nil {+ if err := identity.VerifyBiscuitRole(enrollResp.BiscuitToken, enrollResp.ControlPlanePublicKey, r.config.RequiredRole); err != nil {return fmt.Errorf("enrolled biscuit token lacks required role %q: %w", r.config.RequiredRole, err)}@@ -557,7 +557,7 @@ func (r *Router) verifyEvent(event *api.MeshEvent) bool {return false}-func (r *Router) listenForHubEvents(ctx context.Context) {+func (r *Router) listenForControlPlaneEvents(ctx context.Context) {defer r.wg.Done()if r.EventTopic == nil {return@@ -765,12 +765,12 @@ func (r *Router) connectBootstrapRouters() {return}- var info api.HubInfoResponse+ var info api.ControlPlaneInfoResponseif err := proto.Unmarshal(body, &info); err != nil {return}- for _, addrStr := range info.HubAddresses {+ for _, addrStr := range info.RouterAddresses {ma, err := multiaddr.NewMultiaddr(addrStr)if err != nil {continuediff --git a/mobile/mobile_e2e.sh b/mobile/mobile_e2e.shindex c6df4281..89bb0aee 100755--- a/mobile/mobile_e2e.sh+++ b/mobile/mobile_e2e.sh@@ -143,7 +143,7 @@ docker run --name host-node \sam-node:local \run \--data-dir /data \- --hub http://sam-control-plane:37001 \+ --control-plane http://sam-control-plane:37001 \--jwt "$HOST_JWT" \--bind-addr 0.0.0.0:8081 \--api-token host-token \diff --git a/mobile/sam-node-app/README.md b/mobile/sam-node-app/README.mdindex 3ad6d771..3af03812 100644--- a/mobile/sam-node-app/README.md+++ b/mobile/sam-node-app/README.md@@ -60,10 +60,10 @@ flutter runOnce launched, the app displays a control interface:-1. **Hub URL / Address**: The address of the SAM Hub (e.g., `https://bananas.sam-mesh.dev`).+1. **Control plane URL**: The address of the SAM control plane (e.g., `https://bananas.sam-mesh.dev`).2. **Enrollment JWT**: A valid JWT token retrieved from your OIDC provider to authenticate the node registration.3. **Local API Token**: The secret bearer token used to secure the local sidecar REST APIs (defaults to `secret-token`).-4. **Enroll Node**: Click this button first to generate the local Peer Identity and register the node with the Hub.+4. **Enroll Node**: Click this button first to generate the local Peer Identity and register the node with the control plane.5. **Start Node**: Launches the Go node runtime in the background. It will bind its local MCP sidecar to `127.0.0.1:5005`.6. **Stop Node**: Gracefully shuts down the background Go mesh client.diff --git a/mobile/sam-node-app/integration_test/e2e_test.dart b/mobile/sam-node-app/integration_test/e2e_test.dartindex 448853c5..14b2dfb0 100644--- a/mobile/sam-node-app/integration_test/e2e_test.dart+++ b/mobile/sam-node-app/integration_test/e2e_test.dart@@ -42,15 +42,15 @@ void main() {final jwt = tokenData['access_token'] as String;expect(jwt, isNotEmpty);- // 3. Enroll Node against host Hub- const hubURL = 'http://127.0.0.1:37001';- final enrollErr = samLib.enroll(dataDir, hubURL, jwt, true);+ // 3. Enroll Node against the host control plane+ const controlPlaneURL = 'http://127.0.0.1:37001';+ final enrollErr = samLib.enroll(dataDir, controlPlaneURL, jwt, true);expect(enrollErr, isNull);// 4. Start Nodefinal startErr = samLib.start({'dataDir': dataDir,- 'hubURL': hubURL,+ 'controlPlaneURL': controlPlaneURL,'meshID': 'public-mesh','bindAddr': '0.0.0.0:8080', // sidecar HTTP server inside phone'apiToken': 'test-token',diff --git a/mobile/sam-node-app/lib/main.dart b/mobile/sam-node-app/lib/main.dartindex 670ce907..35cb9755 100644--- a/mobile/sam-node-app/lib/main.dart+++ b/mobile/sam-node-app/lib/main.dart@@ -17,17 +17,17 @@ import 'package:url_launcher/url_launcher.dart';import 'sam_ffi.dart';import 'mcp_server.dart';-String? _isolatedFetchHubInfo(String url) {+String? _isolatedFetchControlPlaneInfo(String url) {try {- return SamNodeLib().fetchHubInfoJSON(url);+ return SamNodeLib().fetchControlPlaneInfoJSON(url);} catch (e) {return jsonEncode({'error': 'FFI_ERROR: ${e.toString()}'});}}-String? _isolatedEnroll(String dataDir, String hubText, String jwtText, bool allowLoopback) {+String? _isolatedEnroll(String dataDir, String controlPlaneText, String jwtText, bool allowLoopback) {try {- return SamNodeLib().enroll(dataDir, hubText, jwtText, allowLoopback);+ return SamNodeLib().enroll(dataDir, controlPlaneText, jwtText, allowLoopback);} catch (e) {return e.toString();}@@ -67,7 +67,7 @@ class NodeControlPage extends StatefulWidget {}class _NodeControlPageState extends State<NodeControlPage> {- final _hubController =+ final _controlPlaneController =TextEditingController(text: 'https://bananas.sam-mesh.dev');final _jwtController = TextEditingController();final _tokenController = TextEditingController(text: 'secret-token');@@ -113,7 +113,7 @@ class _NodeControlPageState extends State<NodeControlPage> {@overridevoid dispose() {_pollingTimer?.cancel();- _hubController.dispose();+ _controlPlaneController.dispose();_jwtController.dispose();_tokenController.dispose();_externalMcpUrlController.dispose();@@ -152,23 +152,23 @@ class _NodeControlPageState extends State<NodeControlPage> {debugPrint('DEBUG: _loginAndEnroll started');setState(() {_loggingIn = true;- _status = 'Fetching hub info...';+ _status = 'Fetching control plane info...';});HttpServer? server;try {- final hubUrl = _hubController.text.trim();- debugPrint('DEBUG: Fetching hub info from $hubUrl');- final infoJson = await Isolate.run(() => _isolatedFetchHubInfo(hubUrl));- debugPrint('DEBUG: Hub info JSON: $infoJson');+ final controlPlaneUrl = _controlPlaneController.text.trim();+ debugPrint('DEBUG: Fetching control plane info from $controlPlaneUrl');+ final infoJson = await Isolate.run(() => _isolatedFetchControlPlaneInfo(controlPlaneUrl));+ debugPrint('DEBUG: Control plane info JSON: $infoJson');if (infoJson == null) {- throw Exception('Failed to fetch hub info');+ throw Exception('Failed to fetch control plane info');}final info = jsonDecode(infoJson);if (info['error'] != null) {- throw Exception('Hub info error: ${info['error']}');+ throw Exception('Control plane info error: ${info['error']}');}final issuer = info['oidcIssuer'];@@ -178,7 +178,7 @@ class _NodeControlPageState extends State<NodeControlPage> {debugPrint('DEBUG: Issuer: $issuer, ClientId: $clientId, Audience: $audience');if (issuer == null || clientId == null) {- throw Exception('Incomplete hub info received');+ throw Exception('Incomplete control plane info received');}setState(() {@@ -357,18 +357,18 @@ class _NodeControlPageState extends State<NodeControlPage> {Future<void> _startDeviceLogin() async {setState(() {_loggingIn = true;- _status = 'Fetching hub info for device login...';+ _status = 'Fetching control plane info for device login...';});try {- final hubUrl = _hubController.text.trim();- debugPrint('DEBUG: Device Login: Fetching hub info from $hubUrl');- final infoJson = await Isolate.run(() => _isolatedFetchHubInfo(hubUrl));- if (infoJson == null) throw Exception('Failed to fetch hub info');+ final controlPlaneUrl = _controlPlaneController.text.trim();+ debugPrint('DEBUG: Device Login: Fetching control plane info from $controlPlaneUrl');+ final infoJson = await Isolate.run(() => _isolatedFetchControlPlaneInfo(controlPlaneUrl));+ if (infoJson == null) throw Exception('Failed to fetch control plane info');final info = jsonDecode(infoJson);if (info['error'] != null) {- throw Exception('Hub info error: ${info['error']}');+ throw Exception('Control plane info error: ${info['error']}');}final issuer = info['oidcIssuer'];@@ -376,7 +376,7 @@ class _NodeControlPageState extends State<NodeControlPage> {final audience = info['audience'];if (issuer == null || clientId == null) {- throw Exception('Incomplete hub info received');+ throw Exception('Incomplete control plane info received');}// OIDC discovery@@ -572,10 +572,10 @@ class _NodeControlPageState extends State<NodeControlPage> {Future<void> _enroll() async {final appDir = await getApplicationDocumentsDirectory();final dataDir = '${appDir.path}/sam_data';- final hubText = _hubController.text;+ final controlPlaneText = _controlPlaneController.text;final jwtText = _jwtController.text;final err = await Isolate.run(() {- return _isolatedEnroll(dataDir, hubText, jwtText, true);+ return _isolatedEnroll(dataDir, controlPlaneText, jwtText, true);});setState(() {@@ -627,7 +627,7 @@ class _NodeControlPageState extends State<NodeControlPage> {final err = _samLib.start({'dataDir': dataDir,- 'hubURL': _hubController.text,+ 'controlPlaneURL': _controlPlaneController.text,'meshID': 'public-mesh','bindAddr': '127.0.0.1:5005', // sidecar port inside phone'apiToken': _tokenController.text,@@ -930,9 +930,9 @@ class _NodeControlPageState extends State<NodeControlPage> {textAlign: TextAlign.center),const SizedBox(height: 30),TextField(- controller: _hubController,+ controller: _controlPlaneController,decoration: const InputDecoration(- labelText: 'Hub URL',+ labelText: 'Control plane URL',border: OutlineInputBorder(),hintText: 'https://bananas.sam-mesh.dev',),diff --git a/mobile/sam-node-app/lib/sam_ffi.dart b/mobile/sam-node-app/lib/sam_ffi.dartindex ced40c8d..7b7aca10 100644--- a/mobile/sam-node-app/lib/sam_ffi.dart+++ b/mobile/sam-node-app/lib/sam_ffi.dart@@ -15,17 +15,17 @@ typedef GetNodeIDDart = ffi.Pointer<Utf8> Function();typedef EnrollNodeC = ffi.Pointer<Utf8> Function(ffi.Pointer<Utf8> dataDir,- ffi.Pointer<Utf8> hubURL,+ ffi.Pointer<Utf8> controlPlaneURL,ffi.Pointer<Utf8> jwt,ffi.Int8 allowLoopback);typedef EnrollNodeDart = ffi.Pointer<Utf8> Function(ffi.Pointer<Utf8> dataDir,- ffi.Pointer<Utf8> hubURL,+ ffi.Pointer<Utf8> controlPlaneURL,ffi.Pointer<Utf8> jwt,int allowLoopback);-typedef FetchHubInfoJSONC = ffi.Pointer<Utf8> Function(ffi.Pointer<Utf8> hubURL);-typedef FetchHubInfoJSONDart = ffi.Pointer<Utf8> Function(ffi.Pointer<Utf8> hubURL);+typedef FetchControlPlaneInfoJSONC = ffi.Pointer<Utf8> Function(ffi.Pointer<Utf8> controlPlaneURL);+typedef FetchControlPlaneInfoJSONDart = ffi.Pointer<Utf8> Function(ffi.Pointer<Utf8> controlPlaneURL);typedef IsEnrolledC = ffi.Int8 Function(ffi.Pointer<Utf8> dataDir);typedef IsEnrolledDart = int Function(ffi.Pointer<Utf8> dataDir);@@ -42,7 +42,7 @@ class SamNodeLib {late StopNodeDart _stopNode;late GetNodeIDDart _getNodeID;late EnrollNodeDart _enrollNode;- late FetchHubInfoJSONDart _fetchHubInfoJSON;+ late FetchControlPlaneInfoJSONDart _fetchControlPlaneInfoJSON;late IsEnrolledDart _isEnrolled;late GetMeshInfoDart _getMeshInfo;late FreeStringDart _freeString;@@ -60,7 +60,7 @@ class SamNodeLib {_stopNode = _dylib.lookupFunction<StopNodeC, StopNodeDart>('StopNode');_getNodeID = _dylib.lookupFunction<GetNodeIDC, GetNodeIDDart>('GetNodeID');_enrollNode = _dylib.lookupFunction<EnrollNodeC, EnrollNodeDart>('EnrollNode');- _fetchHubInfoJSON = _dylib.lookupFunction<FetchHubInfoJSONC, FetchHubInfoJSONDart>('FetchHubInfoJSON');+ _fetchControlPlaneInfoJSON = _dylib.lookupFunction<FetchControlPlaneInfoJSONC, FetchControlPlaneInfoJSONDart>('FetchControlPlaneInfoJSON');_isEnrolled = _dylib.lookupFunction<IsEnrolledC, IsEnrolledDart>('IsEnrolled');_getMeshInfo = _dylib.lookupFunction<GetMeshInfoC, GetMeshInfoDart>('GetMeshInfo');_freeString = _dylib.lookupFunction<FreeStringC, FreeStringDart>('FreeString');@@ -94,16 +94,16 @@ class SamNodeLib {return goID;}- String? enroll(String dataDir, String hubURL, String jwt, bool allowLoopback) {+ String? enroll(String dataDir, String controlPlaneURL, String jwt, bool allowLoopback) {final cDataDir = dataDir.toNativeUtf8();- final cHubURL = hubURL.toNativeUtf8();+ final cControlPlaneURL = controlPlaneURL.toNativeUtf8();final cJWT = jwt.toNativeUtf8();final cAllowLoopback = allowLoopback ? 1 : 0;- final cErr = _enrollNode(cDataDir, cHubURL, cJWT, cAllowLoopback);+ final cErr = _enrollNode(cDataDir, cControlPlaneURL, cJWT, cAllowLoopback);calloc.free(cDataDir);- calloc.free(cHubURL);+ calloc.free(cControlPlaneURL);calloc.free(cJWT);if (cErr.address == 0) return null;@@ -112,10 +112,10 @@ class SamNodeLib {return goErr;}- String? fetchHubInfoJSON(String hubURL) {- final cHubURL = hubURL.toNativeUtf8();- final cResult = _fetchHubInfoJSON(cHubURL);- calloc.free(cHubURL);+ String? fetchControlPlaneInfoJSON(String controlPlaneURL) {+ final cControlPlaneURL = controlPlaneURL.toNativeUtf8();+ final cResult = _fetchControlPlaneInfoJSON(cControlPlaneURL);+ calloc.free(cControlPlaneURL);if (cResult.address == 0) return null;final goResult = cResult.toDartString();diff --git a/mobile/sam-node-ffi/ffi/ffi.go b/mobile/sam-node-ffi/ffi/ffi.goindex 6266dc70..f1c6bfef 100644--- a/mobile/sam-node-ffi/ffi/ffi.go+++ b/mobile/sam-node-ffi/ffi/ffi.go@@ -46,7 +46,7 @@ var (// MobileConfig holds simple configuration options for the mobile agent.type MobileConfig struct {DataDir string `json:"dataDir"`- HubURL string `json:"hubURL"`+ ControlPlaneURL string `json:"controlPlaneURL"`MeshID string `json:"meshID"`BindAddr string `json:"bindAddr"`ApiToken string `json:"apiToken"`@@ -102,19 +102,19 @@ func StartNode(configJSON string) error {token, _ := store.LoadIdentity()if len(token) == 0 {- displayHub := config.HubURL- if displayHub == "" {- if h, err := store.LoadHubURL(); err == nil && h != "" {- displayHub = h+ displayControlPlane := config.ControlPlaneURL+ if displayControlPlane == "" {+ if h, err := store.LoadControlPlaneURL(); err == nil && h != "" {+ displayControlPlane = h} else {- displayHub = "https://bananas.sam-mesh.dev"+ displayControlPlane = "https://bananas.sam-mesh.dev"}}bindAddr := config.BindAddrif bindAddr == "" {bindAddr = "127.0.0.1:8080"}- srv, err := node.StartUnauthSidecarServer(displayHub, bindAddr, "", "")+ srv, err := node.StartUnauthSidecarServer(displayControlPlane, bindAddr, "", "")if err != nil {_ = store.Close()activeStore = nil@@ -124,14 +124,14 @@ func StartNode(configJSON string) error {return nil}- var hubPubKey ed25519.PublicKey- var hubAddrs []multiaddr.Multiaddr+ var controlPlanePubKey ed25519.PublicKey+ var routerAddrs []multiaddr.Multiaddr// Sync config from stored/synced configuration- storedPubKey, syncedAddrs, err := node.SyncHubConfig(context.Background(), store)+ storedPubKey, syncedAddrs, err := node.SyncMeshConfig(context.Background(), store)if err == nil && len(storedPubKey) > 0 {- hubPubKey = storedPubKey- hubAddrs = syncedAddrs+ controlPlanePubKey = storedPubKey+ routerAddrs = syncedAddrs}priv := node.GetOrGenerateKey(store)@@ -157,8 +157,8 @@ func StartNode(configJSON string) error {// Create and initialize the nodesamNode, err := node.NewSamNode(node.Options{PrivKey: priv,- HubPubKey: hubPubKey,- HubAddrs: hubAddrs,+ ControlPlanePubKey: controlPlanePubKey,+ RouterAddrs: routerAddrs,Store: store,MeshID: meshID,DiscoveryInterval: discoveryInterval,@@ -258,7 +258,7 @@ func GetNodeID() string {}// EnrollNode enrolls a node.-func EnrollNode(dataDir string, hubURL string, jwt string, allowLoopback bool) error {+func EnrollNode(dataDir string, controlPlaneURL string, jwt string, allowLoopback bool) error {_ = os.MkdirAll(dataDir, 0700)logFilePath := filepath.Join(dataDir, "node.log")golog.SetupLogging(golog.Config{@@ -276,11 +276,11 @@ func EnrollNode(dataDir string, hubURL string, jwt string, allowLoopback bool) epriv := node.GetOrGenerateKey(store)- var initHubAddrs []multiaddr.Multiaddr- if !strings.HasPrefix(hubURL, "http://") && !strings.HasPrefix(hubURL, "https://") {- ma, err := multiaddr.NewMultiaddr(hubURL)+ var initRouterAddrs []multiaddr.Multiaddr+ if !strings.HasPrefix(controlPlaneURL, "http://") && !strings.HasPrefix(controlPlaneURL, "https://") {+ ma, err := multiaddr.NewMultiaddr(controlPlaneURL)if err == nil {- initHubAddrs = []multiaddr.Multiaddr{ma}+ initRouterAddrs = []multiaddr.Multiaddr{ma}}}@@ -296,7 +296,7 @@ func EnrollNode(dataDir string, hubURL string, jwt string, allowLoopback bool) emeshNode, err := node.NewSamNode(node.Options{PrivKey: priv,- HubAddrs: initHubAddrs,+ RouterAddrs: initRouterAddrs,Store: store,AllowLoopback: allowLoopback,ListenAddrs: listenAddrs,@@ -312,27 +312,27 @@ func EnrollNode(dataDir string, hubURL string, jwt string, allowLoopback bool) e_ = meshNode.Teardown()}()- err = meshNode.Enroll(enrollCtx, hubURL, jwt)+ err = meshNode.Enroll(enrollCtx, controlPlaneURL, jwt)if err != nil {return fmt.Errorf("enrollment failed: %w", err)}- if err := store.SaveHubURL(hubURL); err != nil {- return fmt.Errorf("failed to save hub URL: %w", err)+ if err := store.SaveControlPlaneURL(controlPlaneURL); err != nil {+ return fmt.Errorf("failed to save control plane URL: %w", err)}- _, _, err = node.SyncHubConfig(enrollCtx, store)+ _, _, err = node.SyncMeshConfig(enrollCtx, store)if err != nil {- return fmt.Errorf("failed to sync hub config post-enrollment: %w", err)+ return fmt.Errorf("failed to sync mesh config post-enrollment: %w", err)}return nil}-// FetchHubInfoJSON fetches hub info and returns it as a JSON string.+// FetchControlPlaneInfoJSON fetches control plane info and returns it as a JSON string.// If an error occurs, it returns a JSON object with an "error" field.-func FetchHubInfoJSON(hubURL string) string {- info, err := node.FetchHubInfo(context.Background(), hubURL)+func FetchControlPlaneInfoJSON(controlPlaneURL string) string {+ info, err := node.FetchControlPlaneInfo(context.Background(), controlPlaneURL)if err != nil {return fmt.Sprintf(`{"error": %q}`, err.Error())}diff --git a/mobile/sam-node-ffi/ffi/ffi_test.go b/mobile/sam-node-ffi/ffi/ffi_test.goindex 4c178dd6..559db114 100644--- a/mobile/sam-node-ffi/ffi/ffi_test.go+++ b/mobile/sam-node-ffi/ffi/ffi_test.go@@ -34,18 +34,18 @@ import ()func TestMobileFFILifecycle(t *testing.T) {- // 1. Setup Mock Hub- hubHost, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"))+ // 1. Setup Mock Router+ routerHost, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"))if err != nil {t.Fatal(err)}- defer func() { _ = hubHost.Close() }()+ defer func() { _ = routerHost.Close() }()- hubDHT, err := dht.New(hubHost, dht.Mode(dht.ModeServer), dht.ProtocolPrefix("/sam"))+ routerDHT, err := dht.New(routerHost, dht.Mode(dht.ModeServer), dht.ProtocolPrefix("/sam"))if err != nil {t.Fatal(err)}- defer func() { _ = hubDHT.Close() }()+ defer func() { _ = routerDHT.Close() }()// Generate key-pair for Mock Control Plane signingcpPubKey, cpPrivKey, err := ed25519.GenerateKey(rand.Reader)@@ -53,11 +53,11 @@ func TestMobileFFILifecycle(t *testing.T) {t.Fatal(err)}- hubHost.SetStreamHandler(api.AuthProtocolID, func(s network.Stream) {- println("--- MOCK HUB: received auth stream connection")+ routerHost.SetStreamHandler(api.AuthProtocolID, func(s network.Stream) {+ println("--- MOCK ROUTER: received auth stream connection")defer func() { _ = s.Close() }()- biscuitBytes := mintMockBiscuit(t, hubHost.ID().String(), cpPrivKey, api.RoleRouter)+ biscuitBytes := mintMockBiscuit(t, routerHost.ID().String(), cpPrivKey, api.RoleRouter)resp := &api.AuthResponse{Success: true,@@ -66,10 +66,10 @@ func TestMobileFFILifecycle(t *testing.T) {data, _ := proto.Marshal(resp)writer := msgio.NewVarintWriter(s)if err := writer.WriteMsg(data); err != nil {- println("--- MOCK HUB: failed to write AuthResponse:", err.Error())+ println("--- MOCK ROUTER: failed to write AuthResponse:", err.Error())return}- println("--- MOCK HUB: wrote AuthResponse success with valid biscuit")+ println("--- MOCK ROUTER: wrote AuthResponse success with valid biscuit")})mux := http.NewServeMux()@@ -80,16 +80,16 @@ func TestMobileFFILifecycle(t *testing.T) {biscuitBytes := mintMockBiscuit(t, req.PeerId, cpPrivKey, api.RoleNode)resp := &api.EnrollResponse{- BiscuitToken: biscuitBytes,- HubPublicKey: cpPubKey,- HubAddresses: []string{hubHost.Addrs()[0].String() + "/p2p/" + hubHost.ID().String()},+ BiscuitToken: biscuitBytes,+ ControlPlanePublicKey: cpPubKey,+ RouterAddresses: []string{routerHost.Addrs()[0].String() + "/p2p/" + routerHost.ID().String()},}data, _ := proto.Marshal(resp)w.Header().Set("Content-Type", "application/x-protobuf")_, _ = w.Write(data)})mux.HandleFunc("/info", func(w http.ResponseWriter, r *http.Request) {- resp := &api.HubInfoResponse{+ resp := &api.ControlPlaneInfoResponse{OidcIssuer: "http://mock-issuer",ClientId: "mock-client",Audience: "mock-audience",@@ -111,12 +111,12 @@ func TestMobileFFILifecycle(t *testing.T) {// 3. Mobile Node Startcfg := MobileConfig{- DataDir: tmpDir,- HubURL: httpServer.URL,- MeshID: "test-mesh",- BindAddr: "127.0.0.1:0", // random free port- ApiToken: "test-token",- AllowLoopback: true,+ DataDir: tmpDir,+ ControlPlaneURL: httpServer.URL,+ MeshID: "test-mesh",+ BindAddr: "127.0.0.1:0", // random free port+ ApiToken: "test-token",+ AllowLoopback: true,}cfgBytes, _ := json.Marshal(cfg)diff --git a/mobile/sam-node-ffi/main.go b/mobile/sam-node-ffi/main.goindex 4fbadcb4..a99d4718 100644--- a/mobile/sam-node-ffi/main.go+++ b/mobile/sam-node-ffi/main.go@@ -55,23 +55,23 @@ func GetNodeID() *C.char {}//export EnrollNode-func EnrollNode(dataDir *C.char, hubURL *C.char, jwt *C.char, allowLoopback C.char) *C.char {+func EnrollNode(dataDir *C.char, controlPlaneURL *C.char, jwt *C.char, allowLoopback C.char) *C.char {goDataDir := C.GoString(dataDir)- goHubURL := C.GoString(hubURL)+ goControlPlaneURL := C.GoString(controlPlaneURL)goJWT := C.GoString(jwt)goAllowLoopback := allowLoopback != 0- err := ffi.EnrollNode(goDataDir, goHubURL, goJWT, goAllowLoopback)+ err := ffi.EnrollNode(goDataDir, goControlPlaneURL, goJWT, goAllowLoopback)if err != nil {return C.CString(err.Error())}return nil}-//export FetchHubInfoJSON-func FetchHubInfoJSON(hubURL *C.char) *C.char {- goHubURL := C.GoString(hubURL)- jsonStr := ffi.FetchHubInfoJSON(goHubURL)+//export FetchControlPlaneInfoJSON+func FetchControlPlaneInfoJSON(controlPlaneURL *C.char) *C.char {+ goControlPlaneURL := C.GoString(controlPlaneURL)+ jsonStr := ffi.FetchControlPlaneInfoJSON(goControlPlaneURL)return C.CString(jsonStr)}diff --git a/site/assets/scss/_styles_project.scss b/site/assets/scss/_styles_project.scssindex bea189b0..65d7b8aa 100644--- a/site/assets/scss/_styles_project.scss+++ b/site/assets/scss/_styles_project.scss@@ -51,7 +51,7 @@z-index: 1;}- // Soft glowing orbs in background to represent network nodes or hubs+ // Soft glowing orbs in background to represent network nodes or routers.mesh-glow-cyan {position: absolute;width: 600px;diff --git a/site/content/_index.md b/site/content/_index.mdindex 7ae41a7c..97f6275d 100644--- a/site/content/_index.md+++ b/site/content/_index.md@@ -6,4 +6,4 @@ SAM (Sovereign Agent Mesh) provides a secure, zero-trust P2P network specificallThink of it as a private, zero-trust overlay network tailored for agent-to-agent communication.-**Secure by Default**: You do not join a mesh automatically, and your tools are never exposed by default. SAM relies on a Zero-Trust architecture, meaning you are 100% isolated until you explicitly join a hub and allow access. You can use our public testnet for "Easy Mode" testing, or run completely in "DIY Mode" by hosting your own control plane.+**Secure by Default**: You do not join a mesh automatically, and your tools are never exposed by default. SAM relies on a Zero-Trust architecture, meaning you are 100% isolated until you explicitly join a mesh and allow access. You can use our public testnet for "Easy Mode" testing, or run completely in "DIY Mode" by hosting your own control plane.diff --git a/site/content/docs/_index.md b/site/content/docs/_index.mdindex 56b2a8ea..e10974c4 100644--- a/site/content/docs/_index.md+++ b/site/content/docs/_index.md@@ -9,7 +9,7 @@ SAM (Sovereign Agent Mesh) is a smart, zero-config, zero-trust P2P network builtInstead of exposing your agent's tools (like local scripts, LLM endpoints, or internal APIs) to the public internet, SAM allows you to create secure, private mesh networks. This is especially critical because modern AI agents operate across highly heterogeneous environments—spanning cloud servers, on-premises datacenters, personal laptops, Raspberry Pis, and Android devices. SAM seamlessly connects them all, regardless of complex network topologies or NATs.**Security & Trust Boundaries (Read This First!)**-* **Isolated by Default:** You do NOT join any mesh by default. You must explicitly configure the control plane (Hub) you want to join.+* **Isolated by Default:** You do NOT join any mesh by default. You must explicitly configure the control plane you want to join.* **Closed by Default:** Joining a mesh does not expose your tools. By default, your node does not allow any services to be reached by others. You must explicitly configure policies to share tools.* **Bring Your Own Control Plane (DIY):** While we offer public testnets, the core design allows you to host your own SAM control plane. You retain 100% control over your data, identities, and authorization policies.@@ -26,7 +26,7 @@ For the fastest way to get started and experiment, you can join our public beta### "DIY Mode" (Self-Hosted for Developers & Operators)Compile from source, run local clusters, host your own control plane, or execute tests:-- 🛠️ **[Developer Guide](development/)**: Prereqs, compilation, local hub setup, and Kubernetes Kind deployment.+- 🛠️ **[Developer Guide](development/)**: Prereqs, compilation, local control plane setup, and Kubernetes Kind deployment.- 🧪 **[Testing Guide](development/testing/)**: Go tests, E2E BATS, and containerized mesh execution.---diff --git a/site/content/docs/development/kubernetes-deployment.md b/site/content/docs/development/kubernetes-deployment.mdindex ef6c0054..912d27f6 100644--- a/site/content/docs/development/kubernetes-deployment.md+++ b/site/content/docs/development/kubernetes-deployment.md@@ -11,7 +11,7 @@ This guide explains how to deploy the SAM control plane and router in a Kubernet## 1. Local Testing with Kind-The repository ships a one-command local mesh under `development/kind/`, driven by `make` targets. This is the fastest way to get a running hub and a few nodes on your machine.+The repository ships a one-command local mesh under `development/kind/`, driven by `make` targets. This is the fastest way to get a running control plane, router and a few nodes on your machine.### Automated Mesh (Recommended)@@ -24,9 +24,9 @@ This creates a `sam-kind` cluster (one control-plane plus workers for the contro- The **control plane**, configured to trust the cluster's own OIDC issuer.- Five **nodes** declared in `development/kind/mesh-config.yaml` (`node-a` through `node-e`), all **bare** by default — assign services to suit what you're testing.-Nodes authenticate to the hub via **Workload Identity Federation** (projected ServiceAccount tokens), so no static secrets or mock OIDC provider are needed. The hub is exposed to the host on `127.0.0.1:9090` (HTTP enroll) and `127.0.0.1:4001` (libp2p) via a NodePort and the cluster's `extraPortMappings` — `cloud-provider-kind` is not required.+Nodes authenticate to the control plane via **Workload Identity Federation** (projected ServiceAccount tokens), so no static secrets or mock OIDC provider are needed. The control plane is exposed to the host on `127.0.0.1:9090` (HTTP enroll) and `127.0.0.1:4001` (libp2p) via a NodePort and the cluster's `extraPortMappings` — `cloud-provider-kind` is not required.-Once everything is up, `make kind-up` opens a tmux session with live per-pod logs (hub and each node in its own pane). Manage the mesh with:+Once everything is up, `make kind-up` opens a tmux session with live per-pod logs (control plane, router and each node in its own pane). Manage the mesh with:```bashmake kind-up ARGS=-s # bring the mesh up without attaching the log view@@ -50,7 +50,7 @@ node-d:node-e:```-- The key is the node's name. The cluster currently ships with a hub plus these **five** agent nodes, all bare by default; each is pinned to a matching worker via the `sam-role` labels in `kind-config.yaml`.+- The key is the node's name. The cluster currently ships with a control plane and router plus these **five** agent nodes, all bare by default; each is pinned to a matching worker via the `sam-role` labels in `kind-config.yaml`.- A **blank** value is a bare node — a `sam-node` with no local service, useful as a caller/consumer.- A **non-blank** value is a folder name under `development/examples/`. That service is built and deployed as a **sidecar** next to the node, and the node is configured to advertise it to the mesh.@@ -104,7 +104,7 @@ make build # produce ./bin/sam-nodemake kind-local-node```-This mints a ServiceAccount token and runs `./bin/sam-node` against the hub at `127.0.0.1:9090`, exposing its MCP API on `127.0.0.1:9099` with the API token `devtoken`. Extra flags pass through via `ARGS`, e.g. to host an example service:+This mints a ServiceAccount token and runs `./bin/sam-node` against the control plane at `127.0.0.1:9090`, exposing its MCP API on `127.0.0.1:9099` with the API token `devtoken`. Extra flags pass through via `ARGS`, e.g. to host an example service:```bashmake kind-local-node ARGS="--config development/examples/calc-mcp/sam-node-config.yaml"@@ -204,18 +204,18 @@ kubectl apply -f sam-router.yamlYou can use the following command to extract the allocated IP into an environment variable:```bash-HUB_IP=$(kubectl get svc sam-control-plane -o jsonpath='{.status.loadBalancer.ingress[0].ip}')+CONTROL_PLANE_IP=$(kubectl get svc sam-control-plane -o jsonpath='{.status.loadBalancer.ingress[0].ip}')```---## 3. Connecting an Agent-To connect a `sam-node` to the hub, you just need the hub's external IP and port.+To connect a `sam-node` to the control plane, you just need its external IP and port.### Enrolling the Agent-To connect a `sam-node` to the hub for the first time, you need to enroll it. The node needs to authenticate with the hub using a JWT token.+To connect a `sam-node` to the control plane for the first time, you need to enroll it. The node needs to authenticate with the control plane using a JWT token.If you are using the **Mock OIDC Provider**, the node can fetch the token using OIDC Client Credentials flow:@@ -227,7 +227,7 @@ If you are using the **Mock OIDC Provider**, the node can fetch the token using2. **Run the Node to enroll:**```bashsam-node run \- --hub "http://$HUB_IP:9090" \+ --control-plane "http://$CONTROL_PLANE_IP:9090" \--oidc-issuer "http://$MOCK_IP:18080" \--client-id "sam-mesh-audience" \--client-secret "sam-e2e-secret"@@ -236,7 +236,7 @@ If you are using the **Mock OIDC Provider**, the node can fetch the token usingIf you are using **Google OIDC**, you must obtain a valid Google ID token for your user and pass it via the `--jwt` flag:```bashsam-node run \- --hub "http://$HUB_IP:9090" \+ --control-plane "http://$CONTROL_PLANE_IP:9090" \--jwt "<your-google-id-token>"```@@ -275,7 +275,7 @@ spec:image: sam-node:localcommand: ["sam-node", "run"]args:- - "--hub"+ - "--control-plane"- "http://sam-control-plane:8080"- "--oidc-issuer"- "http://mock-oidc:18080"@@ -305,7 +305,7 @@ The SAM project supports three primary flows for acquiring a JWT token to enroll* **Example:**```bashsam-node run \- --hub "http://hub.example.com:9090" \+ --control-plane "http://control-plane.example.com:9090" \--oidc-issuer "https://accounts.google.com" \--client-id "$SAM_OIDC_ID" \--client-secret "$SAM_OIDC_SECRET"@@ -314,11 +314,11 @@ sam-node run \#### 2. Native App Authorization Code Flow (Human Intervention)* **Description:** For devices operated by humans, this uses the standard Authorization Code Flow with PKCE for native apps (RFC 8252). The human operator runs `sam-node join` to open a web browser (or get a verification code via `--headless`), completes the login, and obtains a Biscuit token which is stored in the local database (`agent.db`).* **Use Case:** When a human operator is enrolling a node manually via their local terminal.-* **How to use:** Run `sam-node join <hub-url>` before running the node daemon. Alternatively, you can obtain a token yourself and pass it via the `--jwt` flag to `sam-node run`.+* **How to use:** Run `sam-node join <control-plane-url>` before running the node daemon. Alternatively, you can obtain a token yourself and pass it via the `--jwt` flag to `sam-node run`.* **Example:**```bash# First, join interactively:-sam-node join https://hub.example.com+sam-node join https://control-plane.example.com# Then start the node daemon:sam-node run@@ -332,7 +332,7 @@ sam-node run* **Example:**```bashsam-node run \- --hub "http://hub.example.com:9090" \+ --control-plane "http://control-plane.example.com:9090" \--jwt-path "/var/run/secrets/kubernetes.io/serviceaccount/token"```> [!NOTE]@@ -379,7 +379,7 @@ metadata:```### Step 4: Deploy the Node with a Projected Volume-Deploy the `sam-node` and configure it to use the ServiceAccount. We use a **Projected Volume** to request a token with the specific audience expected by the hub (e.g., the mesh name or a specific client ID).+Deploy the `sam-node` and configure it to use the ServiceAccount. We use a **Projected Volume** to request a token with the specific audience expected by the control plane (e.g., the mesh name or a specific client ID).```yamlapiVersion: apps/v1@@ -402,7 +402,7 @@ spec:image: sam-node:localcommand: ["sam-node", "run"]args:- - "--hub"+ - "--control-plane"- "http://sam-control-plane:8080"- "--jwt-path"- "/var/run/secrets/tokens/sam-token"diff --git a/site/content/docs/development/policy.md b/site/content/docs/development/policy.mdindex 00ebe63d..dfb3ad6e 100644--- a/site/content/docs/development/policy.md+++ b/site/content/docs/development/policy.md@@ -8,12 +8,12 @@ The `sam-control-plane` authenticates users via OIDC and injects **Facts** into> [!IMPORTANT]> **Default-Deny Security Posture**> SAM enforces a strict **default-deny** model. By default, when a node joins the mesh, **all of its services (MCP tools, LLM inference endpoints) are completely locked down and inaccessible to other peers**.-> Access is only permitted if the caller presents a Biscuit token containing capability facts (e.g., `granted_service_exact(...)`) explicitly issued by the Hub based on matched user roles.+> Access is only permitted if the caller presents a Biscuit token containing capability facts (e.g., `granted_service_exact(...)`) explicitly issued by the control plane based on matched user roles.> There are no built-in exceptions; even the catalog service (system://sam.catalog) must be explicitly permitted (e.g., via a role mapping) to facilitate peer-to-peer discovery.## 1. OIDC to Biscuit Translation-The Hub automatically translates OIDC claims into undeniable cryptographic facts:+The control plane automatically translates OIDC claims into undeniable cryptographic facts:| OIDC Claim / Data | Biscuit Fact | Description || :--- | :--- | :--- |@@ -27,12 +27,12 @@ The Hub automatically translates OIDC claims into undeniable cryptographic facts### 1.1 Translating Identity to Capability: OIDC to BiscuitThe core innovation of the SAM Network's security model is translating standard web identity (OIDC JSON Web Tokens defined in [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html#Claims)) into decentralized capability tokens (Biscuits). This translation happens securely at the `sam-control-plane` during the authentication phase.-The Datalog authority facts generated by the Hub are constructed using the Biscuit [Symbol Table specification](https://doc.biscuitsec.org/reference/specifications.html#symbol-table), ensuring compact serialization and cryptographically undeniable credentials.+The Datalog authority facts generated by the control plane are constructed using the Biscuit [Symbol Table specification](https://doc.biscuitsec.org/reference/specifications.html#symbol-table), ensuring compact serialization and cryptographically undeniable credentials.Here is exactly how an OIDC JWT is transformed into a policy-ready Biscuit:#### 1. Claim Extraction-When an agent or user submits a valid OIDC JWT, the sam-control-plane verifies the token's signature against the Identity Provider. Once validated, the Hub extracts the payload claims—typically attributes like sub (subject), email, and custom arrays like groups or roles.+When an agent or user submits a valid OIDC JWT, the sam-control-plane verifies the token's signature against the Identity Provider. Once validated, the control plane extracts the payload claims—typically attributes like sub (subject), email, and custom arrays like groups or roles.#### 2. Datalog Fact GenerationBiscuit policies are written in Datalog, a declarative logic language. The sam-control-plane acts as a translator, mapping the JSON claims from the OIDC token into immutable Datalog facts.@@ -47,7 +47,7 @@ For example, an incoming OIDC payload like this:}```-Is translated by the Hub into the following Datalog facts:+Is translated by the control plane into the following Datalog facts:```dataloguser("user-12345");@@ -57,9 +57,9 @@ group("engineering");```#### 3. Minting the Authority Block-The sam-control-plane takes these generated Datalog facts and embeds them into the Authority Block of a brand new Biscuit token. The Hub signs this block with its private cryptographic key.+The sam-control-plane takes these generated Datalog facts and embeds them into the Authority Block of a brand new Biscuit token. The control plane signs this block with its private cryptographic key.-Because the facts are sealed in the Authority Block by the Hub, any sam-node in the mesh can implicitly trust that the user holding the Biscuit possesses those specific emails and groups.+Because the facts are sealed in the Authority Block by the control plane, any sam-node in the mesh can implicitly trust that the user holding the Biscuit possesses those specific emails and groups.#### 4. Policy Evaluation at the NodeWhen the agent presents the Biscuit to a sam-node to execute a tool, the node evaluates its local policies against the facts embedded in the token.@@ -67,18 +67,18 @@ When the agent presents the Biscuit to a sam-node to execute a tool, the node evBecause the OIDC claims were translated into Datalog, a node administrator can write elegant, logic-based rules in policy.go or their YAML configs:```datalog-// The node will only execute the tool if the Hub certified the agent is in the engineering group+// The node will only execute the tool if the control plane certified the agent is in the engineering groupallow if group("engineering");```-## 2. Hub Policy Configuration (REST API)+## 2. Control plane policy configuration (REST API)Admins manage central permissions dynamically via the Control Plane REST API. The policy database defines a set of **Roles** and **Bindings**.* **Roles**: Define specific capabilities (allowed destinations and services).* `allowed_targets`: Defines which logical groups or specific peers a user can route messages to, analogous to Active Directory security groups. Target definitions must be formatted as resolved facts (e.g., `group:<name>`, `user:<sub-id>`, `email:<email>`, `role:<role-name>`, or `node:<peer-id>`). *Note: These are evaluated dynamically at the destination node using its own identity (see Section 3.1).** `allowed_services`: Defines the application-level tools or endpoints a user can access. Services use a strict `type://name` convention (e.g., `mcp://db-agent` or `inference://openrouter`).* **Strict Namespaces**: There are no implicit fallbacks. `system://...` is used for internal services, `mcp://...` for node services, `inference://...` for AI models, etc. Service names must be valid domain labels (e.g. `value1.value2.value3`).- * **Wildcards**: SAM natively supports domain-level wildcards to build complex policies. The hub generates specific facts like `granted_service_exact($type, $name)`, `granted_service_prefix($type, $prefix)`, `granted_service_suffix($type, $suffix)`, `granted_service_all_in_type($type)`, or `granted_service_all_types()`. You can grant access to an entire type via `mcp://*`, allow prefix-based wildcard matching like `mcp://*.service.local` (which matches services ending in `.service.local`), suffix-based wildcard matching like `mcp://service.*` (which matches services starting with `service.`), or global access to everything via `*`.+ * **Wildcards**: SAM natively supports domain-level wildcards to build complex policies. The control plane generates specific facts like `granted_service_exact($type, $name)`, `granted_service_prefix($type, $prefix)`, `granted_service_suffix($type, $suffix)`, `granted_service_all_in_type($type)`, or `granted_service_all_types()`. You can grant access to an entire type via `mcp://*`, allow prefix-based wildcard matching like `mcp://*.service.local` (which matches services ending in `.service.local`), suffix-based wildcard matching like `mcp://service.*` (which matches services starting with `service.`), or global access to everything via `*`.* **MCP Namespace Convention**: The `mcp://` prefix (`api.MCPServicePrefix`) is the explicit convention for all Model Context Protocol targets.* **Bindings**: Map OIDC identities (sub/user, email, group) to specific Roles.@@ -120,17 +120,17 @@ attenuation:- 'deny if service("mcp", "restricted-tool"), group("externals");'```-### 3.1 Understanding Authorization Limits (Local vs. Hub)-The SAM network operates on a Zero Trust architecture where authorization is typically managed centrally by the Hub. However, local nodes have full sovereignty over their resources and can define their own authorization policies using the local `sam-node` configuration.+### 3.1 Understanding Authorization Limits (Local vs. control plane)+The SAM network operates on a Zero Trust architecture where authorization is typically managed centrally by the control plane. However, local nodes have full sovereignty over their resources and can define their own authorization policies using the local `sam-node` configuration.Local policies (defined under `attenuation.policies`) configure the **Verifier** on the local node.-* **Restrictive Policies (Deny)**: Local nodes can narrow down or restrict permissions granted by the Hub. For example, blocking users during off-hours, restricting specific contractors, or adding custom time-bound checks using `deny if` policies.-* **Permissive Policies (Allow)**: Local nodes can explicitly grant access to peers, overriding an **implicit deny** (e.g., when the Hub omits a `granted_service` fact). However, local allow policies **cannot bypass explicit constraints** (such as target restrictions or expirations) enforced via Hub-injected `check if` statements. In Biscuit, all `check if` conditions must evaluate to true; if the Hub seals a token with a target restriction that the destination node does not satisfy, the request is unconditionally rejected regardless of any local `allow if` policies.+* **Restrictive Policies (Deny)**: Local nodes can narrow down or restrict permissions granted by the control plane. For example, blocking users during off-hours, restricting specific contractors, or adding custom time-bound checks using `deny if` policies.+* **Permissive Policies (Allow)**: Local nodes can explicitly grant access to peers, overriding an **implicit deny** (e.g., when the control plane omits a `granted_service` fact). However, local allow policies **cannot bypass explicit constraints** (such as target restrictions or expirations) enforced via control-plane-injected `check if` statements. In Biscuit, all `check if` conditions must evaluate to true; if the control plane seals a token with a target restriction that the destination node does not satisfy, the request is unconditionally rejected regardless of any local `allow if` policies.### 3.2 Evaluating `allowed_targets` at the Destination-The SAM network operates on a Zero Trust architecture. The origin node does not police its own traffic. When the Hub injects `allowed_targets` permissions (like `- "group:backend-nodes"`) into the token, it creates `granted_target_group("backend-nodes")` capability facts and seals the token with a `target_restricted()` fact. If no targets are specified, the Hub mints a `target_unrestricted()` fact.+The SAM network operates on a Zero Trust architecture. The origin node does not police its own traffic. When the control plane injects `allowed_targets` permissions (like `- "group:backend-nodes"`) into the token, it creates `granted_target_group("backend-nodes")` capability facts and seals the token with a `target_restricted()` fact. If no targets are specified, the control plane mints a `target_unrestricted()` fact.It is up to the **destination node** to mathematically prove that it is the intended target. To do this, the destination node automatically injects its own identity into the local authorization context as target facts (e.g., `target_fact("group", "backend-nodes")`).@@ -145,7 +145,7 @@ If the token is `target_restricted()` and the destination node does not possess> [!NOTE]> **Policy Evaluation Precedence**-> Local policies defined in `sam-node-config.yaml` are evaluated **before** baseline rules. This means local administrators can write rules that explicitly `deny` access based on custom logic, overriding access granted by the Hub. While they can also use local `allow` policies to bypass Hub service capability constraints, all hardcoded baseline checks (OIDC signatures, replay defense, and target group restrictions) remain strictly enforced.+> Local policies defined in `sam-node-config.yaml` are evaluated **before** baseline rules. This means local administrators can write rules that explicitly `deny` access based on custom logic, overriding access granted by the control plane. While they can also use local `allow` policies to bypass control plane service capability constraints, all hardcoded baseline checks (OIDC signatures, replay defense, and target group restrictions) remain strictly enforced.## 4. Node Baseline Security Rules@@ -160,7 +160,7 @@ check if client_peer_id($id), connection_peer_id($id);### 4.2 The Catalog Service (`sam.catalog`)To allow remote peers to discover tools and query connectivity, each node hosts a built-in catalog service at the special target `sam.catalog`. This service exposes local metadata tools (e.g. `list_local_services`, `get_mesh_info`).-Access to the catalog service is not granted by default and must be explicitly permitted (e.g. via a Hub role mapping allowing `system://sam.catalog` to verified nodes) to facilitate peer-to-peer discovery.+Access to the catalog service is not granted by default and must be explicitly permitted (e.g. via a control plane role mapping allowing `system://sam.catalog` to verified nodes) to facilitate peer-to-peer discovery.Example policy allowing catalog discovery:```datalog@@ -195,10 +195,10 @@ graph TD- Performs exactly **two Biscuit authorizer execution runs** to process authorization:#### Run 1: Destination Identity Fact Evaluation-- **Target**: The node's **own identity token** (issued by the Hub during enrollment).+- **Target**: The node's **own identity token** (issued by the control plane during enrollment).- **Purpose**: We must mathematically evaluate the node's own OIDC group/user claims and node ID to produce `target_fact(...)` datalog assertions (e.g. `target_fact("group", "backend-nodes")`). These facts represent *who we are*.- **Mechanism**:- 1. We create an authorizer for our own token signed by the Hub's public key.+ 1. We create an authorizer for our own token signed by the control plane's public key.2. We add a baseline `allow if true` policy. This policy is required by Biscuit so that the authorizer can execute (since the token itself holds only identity facts and has no operation-level authorization policies).3. We execute `Authorize()` to verify our token signature and validate internal checks (such as expiration).4. We query `api.TargetFactRules` against this authorizer to extract target facts.@@ -206,9 +206,9 @@ graph TD#### Run 2: Caller Request Authorization- **Target**: The caller's **request token** (the Biscuit token presented in the request's `X-Sam-Biscuit` header or `AuthFrame`).-- **Purpose**: Verifies that the caller has been granted access by the Hub to the requested target service, checks for replay protection, and evaluates local attenuation constraints.+- **Purpose**: Verifies that the caller has been granted access by the control plane to the requested target service, checks for replay protection, and evaluates local attenuation constraints.- **Mechanism**:- 1. We create an authorizer for the caller's token using the Hub's public key.+ 1. We create an authorizer for the caller's token using the control plane's public key.2. We inject the target matching facts derived from Run 1.3. We add baseline rules (e.g. peer ID matching connection ID check, system catalog access policies) and local attenuation configurations (`sam-node-config.yaml`).4. We execute `Authorize()` to check all signatures, checks, and policies. If successful, the request is forwarded to the underlying service.@@ -217,7 +217,7 @@ graph TDHere is a representative configuration for an engineering mesh deployment. It shows how to use roles, target groups, service namespaces, wildcards, and local attenuation checks to build a zero-trust development network.-### 6.1 Central Hub Policy API Update+### 6.1 Central control plane policy API updateSend this JSON payload via `POST /policies` to define global roles and user/service-account mappings.@@ -296,13 +296,13 @@ attenuation:# 1. Enforce strict TLS certificate expiry limit- 'check if time($time), $time < 2026-12-31T23:59:59Z;'- # local policies can contain deny rules (to restrict Hub grants) or allow rules (to override implicit denies)+ # local policies can contain deny rules (to restrict control plane grants) or allow rules (to override implicit denies)policies:# 2. Block db-writer calls during off-hours (9 PM to 6 AM)- 'deny if service("mcp", "db-writer"), current_hour($hour), $hour >= 21;'- 'deny if service("mcp", "db-writer"), current_hour($hour), $hour < 6;'- # 3. Restrict contractors from accessing db-writer even if Hub granted it+ # 3. Restrict contractors from accessing db-writer even if the control plane granted it- 'deny if service("mcp", "db-writer"), role("contractor");'# 4. Explicitly allow local admin bypassdiff --git a/site/content/docs/development/testnet-validation.md b/site/content/docs/development/testnet-validation.mdindex b4c6bec3..07fb1ee6 100644--- a/site/content/docs/development/testnet-validation.md+++ b/site/content/docs/development/testnet-validation.md@@ -26,7 +26,7 @@ Before starting, ensure you have:-p 5001:5001/udp -p 5002:5002 -p 8080:8080 \sam-node:local \run --data-dir /data \- --hub https://bananas.sam-mesh.dev \+ --control-plane https://bananas.sam-mesh.dev \--bind-addr 0.0.0.0:8080 \--api-token secret-token \--log-level debug@@ -38,7 +38,7 @@ Before starting, ensure you have:Check the logs of your local `sam-node` to ensure it has successfully joined and is online:```text-INFO sam-node [AuthN] Successfully authenticated with hub via libp2p+INFO sam-node [AuthN] Successfully authenticated with router via libp2pSAM Node Online.PeerID: 12D3KooWKquLDsMiFc5BXsaHmVoJLDDGddqEWbVYYCpUnHR9u6RR```diff --git a/site/content/docs/integrations/_index.md b/site/content/docs/integrations/_index.mdindex eee1f485..982acb3d 100644--- a/site/content/docs/integrations/_index.md+++ b/site/content/docs/integrations/_index.md@@ -87,5 +87,5 @@ Discovered tools:Calling get_mesh_info tool...Result:-{'known_peers': [...], 'connected_peers': [...], 'dht_size': 1, 'hub_peer_id': '...'}+{'known_peers': [...], 'connected_peers': [...], 'dht_size': 1, 'router_peer_id': '...'}```diff --git a/site/content/docs/integrations/openrouter.md b/site/content/docs/integrations/openrouter.mdindex 558c77a5..033f6eb6 100644--- a/site/content/docs/integrations/openrouter.md+++ b/site/content/docs/integrations/openrouter.md@@ -53,9 +53,9 @@ By default, services on your node are completely locked down. To allow agents inThe service format for an inference service is always `inference:<service-name>`.-To allow **any** authenticated mesh agent to use the service, no local attenuation policies are necessary—the Hub will manage access centrally based on the node's assigned roles.+To allow **any** authenticated mesh agent to use the service, no local attenuation policies are necessary—the control plane will manage access centrally based on the node's assigned roles.-If you only want to allow specific identities or groups (e.g., agents belonging to the "research" group) and want to enforce this restriction locally at the node (regardless of Hub configuration), you can add a local check based on the cryptographic facts injected by the Hub:+If you only want to allow specific identities or groups (e.g., agents belonging to the "research" group) and want to enforce this restriction locally at the node (regardless of control plane configuration), you can add a local check based on the cryptographic facts injected by the control plane:```yamlversion: "v1alpha1"attenuation:diff --git a/site/content/docs/quickstart.md b/site/content/docs/quickstart.mdindex 9db1b430..9c2c95e3 100644--- a/site/content/docs/quickstart.md+++ b/site/content/docs/quickstart.md@@ -82,7 +82,7 @@ docker run -it \join --data-dir /data --bootstrap-token <your-token> https://bananas.sam-mesh.dev```-*Note: In non-interactive mode, unless the Hub runs with `--auto-approve-enrollment`, the enrollment request remains **PENDING** until approved manually by a network administrator.*+*Note: In non-interactive mode, unless the control plane runs with `--auto-approve-enrollment`, the enrollment request remains **PENDING** until approved manually by a network administrator.*---@@ -96,7 +96,7 @@ sam-node run --bind-addr 127.0.0.1:8080 --api-token my-secret-token```You should see in the logs:```text-INFO sam-node [AuthN] Successfully authenticated with hub via libp2p: ...+INFO sam-node [AuthN] Successfully authenticated with router via libp2p: ...SAM Node Online.PeerID: 12D3KooW...```diff --git a/site/content/docs/use-cases/gemini-buddy.md b/site/content/docs/use-cases/gemini-buddy.mdindex 5087ff07..dbb8abed 100644--- a/site/content/docs/use-cases/gemini-buddy.md+++ b/site/content/docs/use-cases/gemini-buddy.md@@ -95,7 +95,7 @@ node-e:```bashmake build # builds ./bin/sam-node (once)-make kind-up # hub + buddy (node-b)+make kind-up # control plane + router + buddy (node-b)make kind-local-node # local sam-node enrolled in the mesh — LEAVE RUNNING```diff --git a/site/content/docs/use-cases/warm-agent-pool.md b/site/content/docs/use-cases/warm-agent-pool.mdindex f7a56f58..9d670034 100644--- a/site/content/docs/use-cases/warm-agent-pool.md+++ b/site/content/docs/use-cases/warm-agent-pool.md@@ -118,7 +118,7 @@ node-e: code-reviewer-pool/manager # manager```bashmake build # builds ./bin/sam-node (once)-make kind-up # hub + reviewer pool (node-b/c/d) + manager (node-e)+make kind-up # control plane + router + reviewer pool (node-b/c/d) + manager (node-e)make kind-local-node # local sam-node enrolled in the mesh — LEAVE RUNNING```diff --git a/site/content/docs/user/_index.md b/site/content/docs/user/_index.mdindex 8770c61b..95c804c9 100644--- a/site/content/docs/user/_index.md+++ b/site/content/docs/user/_index.md@@ -4,11 +4,11 @@ linkTitle: "User Guides"weight: 3----Welcome to the User & Operator Guides. This section provides detailed documentation on how to configure, run, and manage Sovereign Agent Mesh (SAM) clusters, hubs, and node configurations.+Welcome to the User & Operator Guides. This section provides detailed documentation on how to configure, run, and manage Sovereign Agent Mesh (SAM) clusters, control planes, and node configurations.### In This Section-1. **[Hub Configuration](hub-configuration/)**+1. **[Control Plane Configuration](control-plane-configuration/)**Learn how to configure the OIDC identity bridge, set up cryptographic private keys, enforce TLS/mTLS, and write custom security role policy mappings in `policies.yaml`.2. **[Agent Usage & Connectivity](agent-usage/)**@@ -18,7 +18,7 @@ Welcome to the User & Operator Guides. This section provides detailed documentatLearn how to configure the local node, set up binding addresses, and manage local storage.4. **[Production Kubernetes Deployment](kubernetes-deployment/)**- Deploy a production-grade mesh cluster in Kubernetes, including Dex OIDC setups, StatefulSet P2P hubs, DNS A-record synchronizers, and Workload Identity ServiceAccount token projections.+ Deploy a production-grade mesh cluster in Kubernetes, including Dex OIDC setups, StatefulSet P2P routers, DNS A-record synchronizers, and Workload Identity ServiceAccount token projections.5. **[SAM Mobile App](mobile-app/)**Turn your mobile device into a SAM node, exposing sensors and telemetry securely to the mesh, and integrating with native OS assistants.diff --git a/site/content/docs/user/agent-usage.md b/site/content/docs/user/agent-usage.mdindex 5d25d8fc..21cb0ef6 100644--- a/site/content/docs/user/agent-usage.md+++ b/site/content/docs/user/agent-usage.md@@ -15,16 +15,16 @@ Connecting your AI agent to the Sovereign Agent Mesh involves two phases:sequenceDiagramactor User as Developer/Operatorparticipant Node as sam-node (Local)- participant Hub as sam-control-plane (Mesh)+ participant ControlPlane as sam-control-plane (Mesh)participant Agent as AI Agent (Gemini/Claude)- Note over User,Hub: Phase 1: Mesh Join (OIDC Authorization)+ Note over User,ControlPlane: Phase 1: Mesh Join (OIDC Authorization)User->>Node: sam-node join <control-plane-url>- Node->>Hub: Get OIDC Info- Hub-->>Node: OIDC Issuer, Client ID+ Node->>ControlPlane: Get OIDC Info+ ControlPlane-->>Node: OIDC Issuer, Client IDNode->>User: Display Login URL & CodeUser->>User: Login in Browser- Node->>Hub: Exchange Code for Biscuit Identity+ Node->>ControlPlane: Exchange Code for Biscuit IdentityNode->>Node: Persist Biscuit in Local Store (agent.db)Note over User,Agent: Phase 2: Agent Tool Invocation@@ -32,7 +32,7 @@ sequenceDiagramNode->>Node: Start local MCP server on 127.0.0.1:8080Agent->>Node: Connect to local MCP (X-Sam-Authentication: Bearer "secret-key")Agent->>Node: Call Remote P2P Tool- Node->>Hub: Verify Biscuit / Allowed Policies+ Node->>ControlPlane: Verify Biscuit / Allowed PoliciesNode-->>Agent: Execute tool and return result```@@ -43,12 +43,12 @@ sequenceDiagramBefore starting the node daemon, you must authorize your node and obtain a cryptographic Biscuit identity.### Standard Login-Run the `join` command, pointing to the mesh control hub:+Run the `join` command, pointing to the mesh control plane:```bashsam-node join https://bananas.sam-mesh.dev```-* **Browser Flow**: The CLI will discover the OIDC credentials from the hub, print an OIDC authorization URL, and attempt to open your system's default web browser automatically.+* **Browser Flow**: The CLI will discover the OIDC credentials from the control plane, print an OIDC authorization URL, and attempt to open your system's default web browser automatically.* **Approval**: Log in with your corporate or identity credentials (e.g. Google Accounts), approve the authorization request, and return to the terminal. The node will automatically exchange the credentials for a Biscuit token and save it to `~/.config/sam-mesh/agent.db`.### Headless (Server) Logindiff --git a/site/content/docs/user/control-plane-configuration.md b/site/content/docs/user/control-plane-configuration.mdindex 60aafc1c..15727865 100644--- a/site/content/docs/user/control-plane-configuration.md+++ b/site/content/docs/user/control-plane-configuration.md@@ -93,7 +93,7 @@ To enforce the principle of least privilege, the Sovereign Agent Mesh implements- `sam-box` requests `sam:role:sambox` (Secure Gateway sidecar)- `sam-router` requests `sam:role:router` (P2P routing and relay service)-The Hub control plane validates that the enrolling client is authorized for the requested role before issuing the Biscuit identity token:+The control plane control plane validates that the enrolling client is authorized for the requested role before issuing the Biscuit identity token:1. **Node Fallback**: By default, any successfully authenticated OIDC identity or generic bootstrap token can claim the `sam:role:node` role.2. **Explicit Bindings**: The higher-privilege capability roles `sam:role:router` and `sam:role:sambox` must be explicitly authorized to the user/service account by mapping the role name in bindings. For example:diff --git a/site/content/docs/user/kubernetes-deployment.md b/site/content/docs/user/kubernetes-deployment.mdindex e1b9ad05..6d103051 100644--- a/site/content/docs/user/kubernetes-deployment.md+++ b/site/content/docs/user/kubernetes-deployment.md@@ -4,7 +4,7 @@ linkTitle: "Kubernetes Deployment"weight: 30----This guide explains how to deploy a production-grade SAM cluster (Hub, DNS synchronizer, OIDC bridge, and Nodes) in a Kubernetes environment (like GKE, EKS, AKS, or custom bare-metal clusters), based on our official public testnet architectures.+This guide explains how to deploy a production-grade SAM cluster (control plane, router, DNS synchronizer, OIDC bridge, and Nodes) in a Kubernetes environment (like GKE, EKS, AKS, or custom bare-metal clusters), based on our official public testnet architectures.---@@ -299,7 +299,7 @@ spec:args:- "run"- "--config=/etc/sam/sam-node.yaml"- - "--hub=http://sam-control-plane.sam.svc.cluster.local:8080"+ - "--control-plane=http://sam-control-plane.sam.svc.cluster.local:8080"- "--jwt-path=/var/run/secrets/tokens/sam-token"- "--api-token=secret-token"volumeMounts:diff --git a/site/content/docs/user/mobile-app.md b/site/content/docs/user/mobile-app.mdindex 26e4310e..f031f78d 100644--- a/site/content/docs/user/mobile-app.md+++ b/site/content/docs/user/mobile-app.md@@ -37,7 +37,7 @@ Exposes capabilities directly to the OS registry, allowing native assistants (li## How to Use the Application-1. **Enrollment**: Enter the **Hub URL** (e.g., `https://bananas.sam-mesh.dev`) and your **Enrollment JWT**.+1. **Enrollment**: Enter the **Control plane URL** (e.g., `https://bananas.sam-mesh.dev`) and your **Enrollment JWT**.2. **API Token**: Set a local API token (defaults to `secret-token`) to secure local access.3. **Start Node**: Launches the background Go node runtime.4. **Dashboard**: Monitor connected peers and DHT size.diff --git a/site/content/docs/user/node-configuration.md b/site/content/docs/user/node-configuration.mdindex 491bb16f..63da9edb 100644--- a/site/content/docs/user/node-configuration.md+++ b/site/content/docs/user/node-configuration.md@@ -4,7 +4,7 @@ linkTitle: "Node Configuration"weight: 15----The `sam-node` acts as a local security gateway and tool proxy for AI agents. While the Hub acts as the central control plane, each Node independently defines its own local tool catalogue and enforces its own local security identity.+The `sam-node` acts as a local security gateway and tool proxy for AI agents. While the control plane is the central authority, each Node independently defines its own local tool catalogue and enforces its own local security identity.---@@ -51,12 +51,12 @@ attenuation:## 2. Defining Local Services-The `services` array allows you to register endpoints that remote peers in the SAM Network can discover and execute (provided they possess the proper `granted_service_*` credentials issued by the Hub).+The `services` array allows you to register endpoints that remote peers in the SAM Network can discover and execute (provided they possess the proper `granted_service_*` credentials issued by the control plane).| Property | Description || :--- | :--- || `type` | The protocol protocol type. Supported values are `mcp` (Model Context Protocol), `inference`, or `a2a`. |-| `name` | The unique name of the service (e.g., `git-helper`). This must exactly match the name authorized by the Hub's `policies.yaml` (e.g., `mcp://git-helper`). |+| `name` | The unique name of the service (e.g., `git-helper`). This must exactly match the name authorized by the control plane's `policies.yaml` (e.g., `mcp://git-helper`). || `description` | A human-readable description published to the mesh discovery catalogue. || `command` | *(For MCP)* The executable command array to spawn as a local subprocess (e.g. `["node", "index.js"]`). || `env` | *(For MCP)* Key-value environment variables passed to the subprocess. |@@ -68,12 +68,12 @@ The `services` array allows you to register endpoints that remote peers in the SIn a Zero Trust architecture, the destination node is entirely responsible for verifying that it is the intended recipient of an incoming request.-While the Hub limits token capabilities based on target restrictions (e.g., `target_restricted()` or `target_unrestricted()`), the destination node evaluates these dynamically. The node automatically resolves its local identity context based on its configuration, generating facts internally (such as `allow_network_target($fact, $value)`).+While the control plane limits token capabilities based on target restrictions (e.g., `target_restricted()` or `target_unrestricted()`), the destination node evaluates these dynamically. The node automatically resolves its local identity context based on its configuration, generating facts internally (such as `allow_network_target($fact, $value)`).If the caller's token has target restrictions, the connection will only be allowed if the token's `granted_target_*` facts match the dynamically injected identity of the node. You do **not** need to write manual Datalog rules to enforce this mechanism; it is baked directly into the node middleware via baseline policies.### Local Custom Policies-You can further restrict access using the `attenuation` block. Local policies defined here are evaluated **before** the baseline rules. This means local administrators can write custom rules that explicitly `deny` access based on custom logic, overriding broad access granted by the Hub.+You can further restrict access using the `attenuation` block. Local policies defined here are evaluated **before** the baseline rules. This means local administrators can write custom rules that explicitly `deny` access based on custom logic, overriding broad access granted by the control plane.1. **`rules`**: Inject custom Datalog facts asserting local node state (e.g., `time($time)`).2. **`policies`**: Add local restrictions (e.g., `deny if user("banned_user");`).diff --git a/site/content/docs/user/secure-gateway.md b/site/content/docs/user/secure-gateway.mdindex d9cd96be..4055ec94 100644--- a/site/content/docs/user/secure-gateway.md+++ b/site/content/docs/user/secure-gateway.md@@ -17,13 +17,13 @@ sequenceDiagramparticipant Agent as AI Agent (Inside Sandbox)participant Init as nano-init (Sandbox PID 1)participant Box as sam-box (Host / Shared Vol)- participant Hub as sam-control-plane (Mesh)+ participant ControlPlane as sam-control-plane (Mesh)participant Upstream as External Service (e.g. OpenAI API)Agent->>Init: HTTP GET http://api.openai.com/v1/models (via HTTP_PROXY)Init->>Box: Forward raw bytes via Unix Domain Socket (UDS)Box->>Box: Parse & verify client's Biscuit token- Box->>Hub: Verify policy rights+ Box->>ControlPlane: Verify policy rightsBox->>Box: Lookup & Inject real API Key (e.g. Bearer sk-...)Box->>Upstream: HTTPS GET https://api.openai.com/v1/models (Upgraded to SSL)Upstream-->>Box: Response@@ -154,7 +154,7 @@ spec:- "--uds-path=/var/run/sam/sam-box.sock"- "--config=/etc/sam/sam-node.yaml"- "--secrets-file=/etc/sam/secrets.yaml"- - "--hub=http://sam-control-plane.sam.svc.cluster.local:8080"+ - "--control-plane=http://sam-control-plane.sam.svc.cluster.local:8080"- "--jwt-path=/var/run/secrets/tokens/sam-token"volumeMounts:- name: config-volumediff --git a/site/layouts/index.html b/site/layouts/index.htmlindex 68e45099..d70520ac 100644--- a/site/layouts/index.html+++ b/site/layouts/index.html@@ -38,14 +38,14 @@<div class="terminal-title">bash - sam-node join</div></div><div class="terminal-body">- <div class="terminal-line"><span class="t-prompt">$</span> <span class="t-cmd">sam-node join --hub bananas.sam-mesh.dev</span></div>+ <div class="terminal-line"><span class="t-prompt">$</span> <span class="t-cmd">sam-node join --control-plane bananas.sam-mesh.dev</span></div><div class="terminal-line t-output">Discovering hub info from https://bananas.sam-mesh.dev...</div><div class="terminal-line t-output">... [OIDC Device Authorization Flow Completed] ...</div><div class="terminal-line t-output">Successfully joined the Sovereign Agent Mesh!</div><div class="terminal-line"><span class="t-prompt">$</span> <span class="t-cmd">sam-node run</span></div><div class="terminal-line t-output">Using stored identity.</div><div class="terminal-line t-output">... [Mesh and DHT Initialization] ...</div>- <div class="terminal-line t-output">[DHT] Bootstrapping DHT with connected hub...</div>+ <div class="terminal-line t-output">[DHT] Bootstrapping DHT with connected router...</div><div class="terminal-line t-success">SAM Node Online.</div><div class="terminal-line t-success">PeerID: 12D3KooWQPXLN3mZ2mfYtNJWqLr2BBMxjPcVhQxydJNkanYH78eR</div></div>diff --git a/tests/e2e/auth_flows.bats b/tests/e2e/auth_flows.batsindex fae083da..b6c78d6e 100644--- a/tests/e2e/auth_flows.bats+++ b/tests/e2e/auth_flows.bats@@ -14,7 +14,7 @@ teardown() {run mesh_start_mock_oidc[[ "$status" -eq 0 ]]- run mesh_start_hub+ run mesh_start_router[[ "$status" -eq 0 ]]# mesh_start_node uses --token-url by default, which implements Client Credentials flow@@ -28,7 +28,7 @@ teardown() {run mesh_start_mock_oidc[[ "$status" -eq 0 ]]- run mesh_start_hub+ run mesh_start_router[[ "$status" -eq 0 ]]# 1. Get a token from mock provider using Python helper@@ -39,8 +39,8 @@ teardown() {# 2. Run sam-node join to enroll and store identitylocal node_name="${MESH_PREFIX}-node-login"- local hub_peer_id- hub_peer_id=$(cat "/tmp/${MESH_PREFIX}-hub-peer-id")+ local router_peer_id+ router_peer_id=$(cat "/tmp/${MESH_PREFIX}-router-peer-id")local data_vol="${MESH_PREFIX}-data"docker volume create "${data_vol}"@@ -97,7 +97,7 @@ teardown() {"sam-node:local" \run \--data-dir /data \- --hub "http://sam-hub:9090"+ --control-plane "http://sam-control-plane:9090"MESH_CONTAINERS+=("${node_name}")mesh_wait_for_log "${node_name}" "Using stored identity." 20@@ -107,7 +107,7 @@ teardown() {run mesh_start_mock_oidc[[ "$status" -eq 0 ]]- run mesh_start_hub+ run mesh_start_router[[ "$status" -eq 0 ]]# 1. Get a token from mock provider@@ -128,8 +128,8 @@ teardown() {# 3. Run sam-node with --jwt-pathlocal node_name="${MESH_PREFIX}-node-wi"- local hub_peer_id- hub_peer_id=$(cat "/tmp/${MESH_PREFIX}-hub-peer-id")+ local router_peer_id+ router_peer_id=$(cat "/tmp/${MESH_PREFIX}-router-peer-id")docker run -d \--name "${node_name}" \@@ -138,7 +138,7 @@ teardown() {-v "${token_vol}:/var/run/secrets/tokens" \"sam-node:local" \run \- --hub "http://sam-control-plane:8080" \+ --control-plane "http://sam-control-plane:8080" \--jwt-path "/var/run/secrets/tokens/sa-token" \--api-token "secret-token"MESH_CONTAINERS+=("${node_name}")@@ -150,7 +150,7 @@ teardown() {run mesh_start_mock_oidc[[ "$status" -eq 0 ]]- run mesh_start_hub+ run mesh_start_router[[ "$status" -eq 0 ]]# 1. Generate bootstrap token via control plane API running in Kubernetes@@ -204,7 +204,7 @@ teardown() {"sam-node:local" \run \--data-dir /data \- --hub "http://sam-control-plane:8080"+ --control-plane "http://sam-control-plane:8080"MESH_CONTAINERS+=("${node_name}")mesh_wait_for_log "${node_name}" "Using stored identity." 20diff --git a/tests/e2e/console.bats b/tests/e2e/console.batsindex 6a15cc3e..eac43ddc 100644--- a/tests/e2e/console.bats+++ b/tests/e2e/console.bats@@ -14,7 +14,7 @@ teardown() {run mesh_start_mock_oidc[[ "$status" -eq 0 ]]- run mesh_start_hub+ run mesh_start_router[[ "$status" -eq 0 ]]local console_name="${MESH_PREFIX}-console"@@ -25,7 +25,7 @@ teardown() {--network "${MESH_NETWORK}" \$(mesh_get_add_hosts) \"sam-console:local" \- --hub "http://sam-control-plane:8080" \+ --control-plane "http://sam-control-plane:8080" \--bind-addr ":8081" \--admin-token "super-secret-admin-token"diff --git a/tests/e2e/container_mesh.bats b/tests/e2e/container_mesh.batsindex 1c090439..57ce98f9 100644--- a/tests/e2e/container_mesh.bats+++ b/tests/e2e/container_mesh.bats@@ -11,11 +11,11 @@ teardown() {mesh_cleanup_env}-@test "container framework starts hub and multiple nodes" {+@test "container framework starts router and multiple nodes" {run mesh_start_mock_oidc[[ "$status" -eq 0 ]]- run mesh_start_hub+ run mesh_start_router[[ "$status" -eq 0 ]]local node_count=5@@ -26,7 +26,7 @@ teardown() {done# Verify every container remains healthy enough to keep the process running.- run mesh_assert_container_running "${MESH_PREFIX}-hub"+ run mesh_assert_container_running "${MESH_PREFIX}-router"[[ "$status" -eq 0 ]]for i in $(seq 1 "$node_count"); dodiff --git a/tests/e2e/datapath.bats b/tests/e2e/datapath.batsindex 5dfa7c75..d0d6cd3d 100644--- a/tests/e2e/datapath.bats+++ b/tests/e2e/datapath.bats@@ -16,11 +16,11 @@ teardown() {run mesh_start_mock_oidc[[ "$status" -eq 0 ]]- # Start Hub- mesh_start_hub- local hub_name="${MESH_PREFIX}-hub"- local hub_peer_id- hub_peer_id=$(cat "/tmp/${MESH_PREFIX}-hub-peer-id")+ # Start router+ mesh_start_router+ local router_name="${MESH_PREFIX}-router"+ local router_peer_id+ router_peer_id=$(cat "/tmp/${MESH_PREFIX}-router-peer-id")# Start Node 1echo "[$(date +%T)] Starting Node 1"diff --git a/tests/e2e/docker/calc-mcp/sam-node-config.yaml b/tests/e2e/docker/calc-mcp/sam-node-config.yamlindex 97a6465c..b2c4b703 100644--- a/tests/e2e/docker/calc-mcp/sam-node-config.yaml+++ b/tests/e2e/docker/calc-mcp/sam-node-config.yaml@@ -1,7 +1,7 @@version: "v1alpha1"attenuation:# Receiver-side: allow MCP only when the caller's biscuit was minted by- # our hub for some peer (zero-trust narrow than "any valid OIDC token").+ # our control plane for some peer (zero-trust narrow than "any valid OIDC token").policies:services:- type: "mcp"diff --git a/tests/e2e/docs_snippets.bats b/tests/e2e/docs_snippets.batsindex 6642435a..6d32f65c 100644--- a/tests/e2e/docs_snippets.bats+++ b/tests/e2e/docs_snippets.bats@@ -18,7 +18,7 @@ teardown() {run mesh_start_mock_oidc[[ "$status" -eq 0 ]]- run mesh_start_hub+ run mesh_start_router[[ "$status" -eq 0 ]]mesh_start_node 1 "--log-level debug"diff --git a/tests/e2e/find_remote_tools.bats b/tests/e2e/find_remote_tools.batsindex 1ad06e61..a5b0e2b5 100644--- a/tests/e2e/find_remote_tools.bats+++ b/tests/e2e/find_remote_tools.bats@@ -36,7 +36,7 @@ teardown() {run mesh_start_mock_oidc[[ "$status" -eq 0 ]]- mesh_start_hub+ mesh_start_routerecho "[$(date +%T)] Starting Node 1"mesh_start_node 1 "--log-level debug"@@ -88,7 +88,7 @@ teardown() {run mesh_start_mock_oidc[[ "$status" -eq 0 ]]- mesh_start_hub+ mesh_start_routerecho "[$(date +%T)] Starting Node 1"mesh_start_node 1 "--log-level debug"@@ -137,7 +137,7 @@ teardown() {run mesh_start_mock_oidc[[ "$status" -eq 0 ]]- mesh_start_hub+ mesh_start_routerecho "[$(date +%T)] Starting Node 1"mesh_start_node 1 "--log-level debug"@@ -200,7 +200,7 @@ teardown() {run mesh_start_mock_oidc[[ "$status" -eq 0 ]]- mesh_start_hub+ mesh_start_routerecho "[$(date +%T)] Starting Node 1"mesh_start_node 1 "--log-level debug"diff --git a/tests/e2e/gen_db.go b/tests/e2e/gen_db.goindex fce898b3..23fab2e5 100644--- a/tests/e2e/gen_db.go+++ b/tests/e2e/gen_db.go@@ -80,11 +80,11 @@ func main() {if err := b.Put([]byte("identity_biscuit"), biscuitBytes); err != nil {return err}- if err := b.Put([]byte("hub_public_key"), pub); err != nil {+ if err := b.Put([]byte("control_plane_public_key"), pub); err != nil {return err}addrsData, _ := json.Marshal([]string{"/ip4/127.0.0.1/tcp/4002/p2p/QmYyQSo1sn1GjUuQwca9AdvV8Zeyvmxrww8dDnewPrfJs9"})- if err := b.Put([]byte("hub_addresses"), addrsData); err != nil {+ if err := b.Put([]byte("router_addresses"), addrsData); err != nil {return err}return nildiff --git a/tests/e2e/lib/container_mesh.bash b/tests/e2e/lib/container_mesh.bashindex 789d22bd..5be2464d 100644--- a/tests/e2e/lib/container_mesh.bash+++ b/tests/e2e/lib/container_mesh.bash@@ -1,7 +1,7 @@#!/usr/bin/env bash# Shared BATS helpers for containerized SAM mesh tests.-# Refactored to use Kind-hosted unified OIDC and Hub services.+# Refactored to use Kind-hosted unified OIDC and control plane services.if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; thenMESH_HELPERS_LOADED=1@@ -180,24 +180,24 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; thenlocal oidc_node_ipoidc_node_ip=$(docker inspect -f "{{(index .NetworkSettings.Networks \"${net}\").IPAddress}}" "${oidc_node}")- # Check if a custom local Hub container exists in this test scope- local hub_ip=""- local custom_hub="${MESH_PREFIX}-hub"- if docker inspect "${custom_hub}" >/dev/null 2>&1; then- hub_ip=$(docker inspect -f "{{(index .NetworkSettings.Networks \"${net}\").IPAddress}}" "${custom_hub}")+ # Check if a custom local router container exists in this test scope+ local router_ip=""+ local custom_router="${MESH_PREFIX}-router"+ if docker inspect "${custom_router}" >/dev/null 2>&1; then+ router_ip=$(docker inspect -f "{{(index .NetworkSettings.Networks \"${net}\").IPAddress}}" "${custom_router}")local cp_ip=""- local custom_cp="${MESH_PREFIX}-hub-cp"+ local custom_cp="${MESH_PREFIX}-control-plane"if docker inspect "${custom_cp}" >/dev/null 2>&1; thencp_ip=$(docker inspect -f "{{(index .NetworkSettings.Networks \"${net}\").IPAddress}}" "${custom_cp}")fi- echo "--add-host mock-oidc:${oidc_node_ip} --add-host sam-hub:${hub_ip} --add-host sam-control-plane:${cp_ip}"+ echo "--add-host mock-oidc:${oidc_node_ip} --add-host sam-router:${router_ip} --add-host sam-control-plane:${cp_ip}"else# Resolve sam-router-0 node IPlocal router_noderouter_node=$(kubectl --context="${KUBECONTEXT:-kind-sam-wi-test}" get pod sam-router-0 -o jsonpath='{.spec.nodeName}')local router_node_iprouter_node_ip=$(docker inspect -f "{{(index .NetworkSettings.Networks \"${net}\").IPAddress}}" "${router_node}")- echo "--add-host mock-oidc:${oidc_node_ip} --add-host sam-hub:${router_node_ip} --add-host sam-router:${router_node_ip} --add-host sam-control-plane:${router_node_ip} --add-host ${router_node}:${router_node_ip}"+ echo "--add-host mock-oidc:${oidc_node_ip} --add-host sam-router:${router_node_ip} --add-host sam-control-plane:${router_node_ip} --add-host ${router_node}:${router_node_ip}"fi}@@ -295,11 +295,11 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; thenfisleep 0.1done- local hub_peer_id- hub_peer_id=$(kubectl --context="${KUBECONTEXT}" logs "sam-router-0" | grep -oE '12D3Koo[a-zA-Z0-9]+' | head -n 1 || true)- [[ -n "${hub_peer_id}" ]]+ local router_peer_id+ router_peer_id=$(kubectl --context="${KUBECONTEXT}" logs "sam-router-0" | grep -oE '12D3Koo[a-zA-Z0-9]+' | head -n 1 || true)+ [[ -n "${router_peer_id}" ]]- echo "${hub_peer_id}" > "/tmp/sam-wi-test-hub-peer-id"+ echo "${router_peer_id}" > "/tmp/sam-wi-test-router-peer-id"return 0}@@ -319,8 +319,8 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; thenlocal add_hostsadd_hosts=$(mesh_get_add_hosts)- local hub_peer_id- hub_peer_id=$(cat "/tmp/${MESH_PREFIX}-hub-peer-id")+ local router_peer_id+ router_peer_id=$(cat "/tmp/${MESH_PREFIX}-router-peer-id")local mount_args=()local config_args=()@@ -342,7 +342,7 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then${flags} \--log-level debug \--discovery-interval 2s \- --hub "http://sam-control-plane:8080" \+ --control-plane "http://sam-control-plane:8080" \--client-id "sam-mesh-audience" \--client-secret "sam-e2e-secret" \--oidc-issuer "http://mock-oidc:18080" \@@ -363,17 +363,17 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; thenreturn 0}- mesh_start_hub() {- # No-op: Hub is running in k8s+ mesh_start_router() {+ # No-op: router is running in k8slocal peer_id- peer_id=$(cat "/tmp/sam-wi-test-hub-peer-id")- echo "${peer_id}" > "/tmp/${MESH_PREFIX}-hub-peer-id"+ peer_id=$(cat "/tmp/sam-wi-test-router-peer-id")+ echo "${peer_id}" > "/tmp/${MESH_PREFIX}-router-peer-id"return 0}mesh_assert_container_running() {local name="$1"- if [[ "${name}" == *"-hub" ]]; then+ if [[ "${name}" == *"-router" ]]; thenkubectl --context="${KUBECONTEXT:-kind-sam-wi-test}" get pod sam-router-0 -o jsonpath='{.status.phase}' | grep -q "Running"return $?fidiff --git a/tests/e2e/policy.bats b/tests/e2e/policy.batsindex 96a02f19..1efad84a 100644--- a/tests/e2e/policy.bats+++ b/tests/e2e/policy.bats@@ -172,8 +172,8 @@ attenuation:# Start servicesstart_calc_mcp- # Initialize Hub PeerID from suite-level file- mesh_start_hub+ # Initialize router PeerID from suite-level file+ mesh_start_router# Start Node 1 (Target) with local policy filemesh_start_node 1 "" "${config_file}"@@ -189,14 +189,14 @@ attenuation:# Wait for discovery (Node 2 should see Node 1)local i- local hub_id- hub_id="$(cat "/tmp/${MESH_PREFIX}-hub-peer-id")"+ local router_id+ router_id="$(cat "/tmp/${MESH_PREFIX}-router-peer-id")"export TARGET_PEER_ID=""for ((i=0; i<40; i++)); dolocal outputoutput="$(docker run --rm --network "${MESH_NETWORK}" "${MESH_RUNTIME_IMAGE}" mcp-client -url "http://${MESH_PREFIX}-node-2:8080/mcp" -tool "get_mesh_info")"- TARGET_PEER_ID=$(echo "${output}" | grep -oE '12D3Koo[a-zA-Z0-9]+' | grep -v "${hub_id}" | grep -v "${node2_id}" | head -n 1)+ TARGET_PEER_ID=$(echo "${output}" | grep -oE '12D3Koo[a-zA-Z0-9]+' | grep -v "${router_id}" | grep -v "${node2_id}" | head -n 1)if [[ -n "${TARGET_PEER_ID}" ]]; thenbreakfi@@ -231,7 +231,7 @@ teardown() {rm -f "/tmp/${MESH_PREFIX}-local_policy.yaml" || true}-@test "Policy E2E: Positive Path (Allowed by Hub, Not blocked by Node)" {+@test "Policy E2E: Positive Path (Allowed by control plane, Not blocked by Node)" {local call_args="{\"peer_id\":\"${TARGET_PEER_ID}\",\"tool_name\":\"mcp://calculator/add\",\"arguments\":{\"a\":2,\"b\":3}}"run docker run --rm --network "${MESH_NETWORK}" "${MESH_RUNTIME_IMAGE}" mcp-client -url "http://${MESH_PREFIX}-node-2:8080/mcp" -tool "call_remote_tool" -args "${call_args}"echo "Output: $output"@@ -239,14 +239,14 @@ teardown() {[[ "$output" == *"5"* ]]}-@test "Policy E2E: Negative Path (Denied by Hub)" {+@test "Policy E2E: Negative Path (Denied by control plane)" {local call_args="{\"peer_id\":\"${TARGET_PEER_ID}\",\"tool_name\":\"mcp://unauthorized-service/reboot_server\",\"arguments\":{}}"run docker run --rm --network "${MESH_NETWORK}" "${MESH_RUNTIME_IMAGE}" mcp-client -url "http://${MESH_PREFIX}-node-2:8080/mcp" -tool "call_remote_tool" -args "${call_args}"echo "Output: $output"[[ "$output" == *"denied"* ]]}-@test "Policy E2E: Attenuation Path (Allowed by Hub, Blocked by Node)" {+@test "Policy E2E: Attenuation Path (Allowed by control plane, Blocked by Node)" {local call_args="{\"peer_id\":\"${TARGET_PEER_ID}\",\"tool_name\":\"mcp://db-agent/delete_tables\",\"arguments\":{}}"run docker run --rm --network "${MESH_NETWORK}" "${MESH_RUNTIME_IMAGE}" mcp-client -url "http://${MESH_PREFIX}-node-2:8080/mcp" -tool "call_remote_tool" -args "${call_args}"echo "Output: $output"diff --git a/tests/e2e/python_sdk_test.bats b/tests/e2e/python_sdk_test.batsindex fef4dcf9..36e7e22b 100644--- a/tests/e2e/python_sdk_test.bats+++ b/tests/e2e/python_sdk_test.bats@@ -18,7 +18,7 @@ teardown() {run mesh_start_mock_oidc[[ "$status" -eq 0 ]]- run mesh_start_hub+ run mesh_start_router[[ "$status" -eq 0 ]]run mesh_start_node 1 "--log-level debug"diff --git a/tests/e2e/relay.bats b/tests/e2e/relay.batsindex 8b37af96..32533e3f 100644--- a/tests/e2e/relay.bats+++ b/tests/e2e/relay.bats@@ -40,7 +40,7 @@ teardown() {run mesh_start_mock_oidc[[ "$status" -eq 0 ]]- run mesh_start_hub+ run mesh_start_router[[ "$status" -eq 0 ]]# Start node with relay flag@@ -55,21 +55,21 @@ teardown() {run mesh_start_mock_oidc[[ "$status" -eq 0 ]]- run mesh_start_hub+ run mesh_start_router[[ "$status" -eq 0 ]]local MESH_NETWORK_2="${MESH_PREFIX}-2-net"docker network create "${MESH_NETWORK_2}"CLEANUP_NETWORKS+=("${MESH_NETWORK_2}")- local hub_node- hub_node=$(kubectl --context="${KUBECONTEXT}" get pod sam-router-0 -o jsonpath='{.spec.nodeName}')+ local router_node+ router_node=$(kubectl --context="${KUBECONTEXT}" get pod sam-router-0 -o jsonpath='{.spec.nodeName}')local oidc_nodeoidc_node=$(kubectl --context="${KUBECONTEXT}" get pod -l app=mock-oidc -o jsonpath='{.items[0].spec.nodeName}')- docker network connect "${MESH_NETWORK_2}" "${hub_node}"- DISCONNECT_CONTAINERS+=("${hub_node}:${MESH_NETWORK_2}")- if [[ "${oidc_node}" != "${hub_node}" ]]; then+ docker network connect "${MESH_NETWORK_2}" "${router_node}"+ DISCONNECT_CONTAINERS+=("${router_node}:${MESH_NETWORK_2}")+ if [[ "${oidc_node}" != "${router_node}" ]]; thendocker network connect "${MESH_NETWORK_2}" "${oidc_node}"DISCONNECT_CONTAINERS+=("${oidc_node}:${MESH_NETWORK_2}")fi@@ -86,11 +86,11 @@ teardown() {run mesh_wait_for_log "${MESH_PREFIX}-node-2" "PeerID:" 20[[ "$status" -eq 0 ]]- # Node 1 should eventually see 1 peer (node 2) besides the hub+ # Node 1 should eventually see 1 peer (node 2) besides the routerrun mesh_wait_for_node_count "1" 1 30[[ "$status" -eq 0 ]]- # Node 2 should eventually see 1 peer (node 1) besides the hub+ # Node 2 should eventually see 1 peer (node 1) besides the routerOLD_NET=$MESH_NETWORKMESH_NETWORK=$MESH_NETWORK_2run mesh_wait_for_node_count "2" 1 30diff --git a/tests/e2e/services.bats b/tests/e2e/services.batsindex e074c538..80890277 100644--- a/tests/e2e/services.bats+++ b/tests/e2e/services.bats@@ -35,7 +35,7 @@ teardown() {run mesh_start_mock_oidc[[ "$status" -eq 0 ]]- mesh_start_hub+ mesh_start_routerecho "[$(date +%T)] Starting Node 1"mesh_start_node 1 "--log-level debug"diff --git a/tests/e2e/watch.bats b/tests/e2e/watch.batsindex 3f29ff45..784aafb6 100644--- a/tests/e2e/watch.bats+++ b/tests/e2e/watch.bats@@ -19,7 +19,7 @@ teardown() {rm -rf "$TEST_TMPDIR"}-@test "sam-node run with stored identity fails if hub is unreachable" {+@test "sam-node run with stored identity fails if the control plane is unreachable" {run "$SAM_NODE_BINARY" run --listen /ip4/127.0.0.1/udp/0/quic-v1 --listen /ip4/127.0.0.1/tcp/0if [[ "$status" -eq 0 ]]; thendiff --git a/tests/integration/auth_test.go b/tests/integration/auth_test.goindex b51ef636..82c615ba 100644--- a/tests/integration/auth_test.go+++ b/tests/integration/auth_test.go@@ -28,7 +28,7 @@ import (func TestNodeAuthEnforcementIntegration(t *testing.T) {nodeBin := buildBinary(t, "./cmd/sam-node")- _, mockHubURL := startMockLibp2pHub(t)+ _, mockRouterAddr := startMockRouter(t)home := t.TempDir()logFile, err := os.Create(filepath.Join(home, "node.log"))@@ -45,7 +45,7 @@ func TestNodeAuthEnforcementIntegration(t *testing.T) {apiToken := "secret-integration-token"cmd := exec.Command(nodeBin, "run",- "--hub", mockHubURL,+ "--control-plane", mockRouterAddr,"--data-dir", home,"--api-token", apiToken,"--jwt", "fake-jwt",diff --git a/tests/integration/catalog_test.go b/tests/integration/catalog_test.goindex 44e7bbd3..ad88f67d 100644--- a/tests/integration/catalog_test.go+++ b/tests/integration/catalog_test.go@@ -15,13 +15,13 @@ import ("github.com/modelcontextprotocol/go-sdk/mcp")-func startBackgroundNode(t *testing.T, nodeBin string, hubAddr string, homeDir string, args ...string) *exec.Cmd {+func startBackgroundNode(t *testing.T, nodeBin string, routerAddr string, homeDir string, args ...string) *exec.Cmd {t.Helper()env := append(os.Environ(),"HOME="+homeDir,"XDG_CONFIG_HOME="+filepath.Join(homeDir, ".config"),)- allArgs := append([]string{"run", "--hub", hubAddr, "--jwt", "test-jwt", "--bind-addr", "127.0.0.1:0", "--api-token", "test-token", "--allow-loopback"}, args...)+ allArgs := append([]string{"run", "--control-plane", routerAddr, "--jwt", "test-jwt", "--bind-addr", "127.0.0.1:0", "--api-token", "test-token", "--allow-loopback"}, args...)cmd := exec.Command(nodeBin, allArgs...)cmd.Env = env@@ -158,7 +158,7 @@ func waitForPeerInfoInLog(t *testing.T, logPath string) string {func TestCatalogRoutingAndFailover(t *testing.T) {nodeBin := buildBinary(t, "./cmd/sam-node")- _, hubAddr := startMockLibp2pHub(t)+ _, routerAddr := startMockRouter(t)homeA := t.TempDir()homeB := t.TempDir()@@ -166,7 +166,7 @@ func TestCatalogRoutingAndFailover(t *testing.T) {// Start Node A (Client)t.Log("Starting Node A...")- _ = startBackgroundNode(t, nodeBin, hubAddr, homeA, "--listen", "/ip4/127.0.0.1/udp/0/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/0", "--discovery-interval", "100ms")+ _ = startBackgroundNode(t, nodeBin, routerAddr, homeA, "--listen", "/ip4/127.0.0.1/udp/0/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/0", "--discovery-interval", "100ms")t.Log("Node A started.")// Wait for Node A to start and get its MCP address@@ -174,12 +174,12 @@ func TestCatalogRoutingAndFailover(t *testing.T) {// Start Node B (Provider 1)t.Log("Starting Node B...")- cmdB := startBackgroundNode(t, nodeBin, hubAddr, homeB, "--listen", "/ip4/127.0.0.1/udp/0/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/0", "--discovery-interval", "100ms")+ cmdB := startBackgroundNode(t, nodeBin, routerAddr, homeB, "--listen", "/ip4/127.0.0.1/udp/0/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/0", "--discovery-interval", "100ms")t.Log("Node B started.")// Start Node C (Provider 2)t.Log("Starting Node C...")- _ = startBackgroundNode(t, nodeBin, hubAddr, homeC, "--listen", "/ip4/127.0.0.1/udp/0/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/0", "--discovery-interval", "100ms")+ _ = startBackgroundNode(t, nodeBin, routerAddr, homeC, "--listen", "/ip4/127.0.0.1/udp/0/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/0", "--discovery-interval", "100ms")t.Log("Node C started.")// Wait for Node B and C to start and get their addresses@@ -247,7 +247,7 @@ func TestCatalogRoutingAndFailover(t *testing.T) {time.Sleep(2 * time.Second)}if !connected {- t.Fatalf("failed to discover peers (Hub + 2 nodes) in time")+ t.Fatalf("failed to discover peers (router + 2 nodes) in time")}respData := callMCP(t, mcpAddrA, "send_message", map[string]any{"peer_id": "target-peer", "message": "hello"})diff --git a/tests/integration/cuj_test.go b/tests/integration/cuj_test.goindex d18685dc..b0556bfc 100644--- a/tests/integration/cuj_test.go+++ b/tests/integration/cuj_test.go@@ -25,7 +25,7 @@ import (func TestSamNodeRunWithManualTokenStarts(t *testing.T) {nodeBin := buildBinary(t, "./cmd/sam-node")- _, hubAddr := startMockLibp2pHub(t)+ _, routerAddr := startMockRouter(t)tmpHome := t.TempDir()env := append(os.Environ(),"HOME="+tmpHome,@@ -39,7 +39,7 @@ func TestSamNodeRunWithManualTokenStarts(t *testing.T) {env,"",nodeBin,- "run", "--hub", hubAddr,+ "run", "--control-plane", routerAddr,"--jwt", "test-jwt","--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0",diff --git a/tests/integration/datapath_test.go b/tests/integration/datapath_test.goindex 10335f45..a64c8a4f 100644--- a/tests/integration/datapath_test.go+++ b/tests/integration/datapath_test.go@@ -32,7 +32,7 @@ import (func TestIntegrationStdioDatapath(t *testing.T) {nodeBin := buildBinary(t, "./cmd/sam-node")- _, hubAddr := startMockLibp2pHub(t)+ _, routerAddr := startMockRouter(t)homeA := t.TempDir()homeB := t.TempDir()@@ -41,7 +41,7 @@ func TestIntegrationStdioDatapath(t *testing.T) {// Start Node At.Log("Starting Node A...")- _ = startBackgroundNode(t, nodeBin, hubAddr, homeA,+ _ = startBackgroundNode(t, nodeBin, routerAddr, homeA,"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0","--discovery-interval", "100ms",@@ -51,7 +51,7 @@ func TestIntegrationStdioDatapath(t *testing.T) {// Start Node Bt.Log("Starting Node B...")- _ = startBackgroundNode(t, nodeBin, hubAddr, homeB,+ _ = startBackgroundNode(t, nodeBin, routerAddr, homeB,"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0","--discovery-interval", "100ms",@@ -157,7 +157,7 @@ func TestIntegrationStdioDatapath(t *testing.T) {func TestIntegrationHTTPDatapath(t *testing.T) {nodeBin := buildBinary(t, "./cmd/sam-node")- _, hubAddr := startMockLibp2pHub(t)+ _, routerAddr := startMockRouter(t)homeA := t.TempDir()homeB := t.TempDir()@@ -166,7 +166,7 @@ func TestIntegrationHTTPDatapath(t *testing.T) {// Start Node At.Log("Starting Node A...")- _ = startBackgroundNode(t, nodeBin, hubAddr, homeA,+ _ = startBackgroundNode(t, nodeBin, routerAddr, homeA,"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0","--discovery-interval", "100ms",@@ -176,7 +176,7 @@ func TestIntegrationHTTPDatapath(t *testing.T) {// Start Node Bt.Log("Starting Node B...")- _ = startBackgroundNode(t, nodeBin, hubAddr, homeB,+ _ = startBackgroundNode(t, nodeBin, routerAddr, homeB,"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0","--discovery-interval", "100ms",diff --git a/tests/integration/failover_test.go b/tests/integration/failover_test.goindex 26c4f3f1..b692d6a8 100644--- a/tests/integration/failover_test.go+++ b/tests/integration/failover_test.go@@ -78,11 +78,11 @@ roles: {}// Dynamic Load Balancer for HTTP discoveryvar lbMu sync.Mutex- activeHubPort := httpPortCP_A+ activeControlPlanePort := httpPortCP_Alb := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {lbMu.Lock()- targetPort := activeHubPort+ targetPort := activeControlPlanePortlbMu.Unlock()target, _ := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", targetPort))@@ -201,7 +201,7 @@ roles: {}"HOME="+nodeHome,"XDG_CONFIG_HOME="+filepath.Join(nodeHome, ".config"),)- cmdNode := exec.Command(nodeBin, "run", "--hub", lb.URL,+ cmdNode := exec.Command(nodeBin, "run", "--control-plane", lb.URL,"--listen", "/ip4/127.0.0.1/tcp/0","--jwt-path", jwtPath,"--bind-addr", "127.0.0.1:0",@@ -247,9 +247,9 @@ roles: {}t.Logf("Node started. Node PeerID: %s", nodePeerID)// Now FAILOVER: Switch LB to CP B and KILL CP A and Router A- t.Logf("Initiating failover to Hub B...")+ t.Logf("Initiating failover to control plane B...")lbMu.Lock()- activeHubPort = httpPortCP_B+ activeControlPlanePort = httpPortCP_BlbMu.Unlock()_ = cmdCP_A.Process.Kill()_ = cmdRouterA.Process.Kill()@@ -257,15 +257,15 @@ roles: {}// Wait for Node's AutoRelay to get updatedfor i := 0; i < 150; i++ {out = stdoutNode.String() + stderrNode.String()- if strings.Contains(out, "Successfully reconnected to Hub via HTTP fallback") {+ if strings.Contains(out, "Successfully reconnected to router via HTTP fallback") {break}time.Sleep(100 * time.Millisecond)}- if !strings.Contains(out, "Successfully reconnected to Hub via HTTP fallback") {+ if !strings.Contains(out, "Successfully reconnected to router via HTTP fallback") {t.Fatalf("Node failed to detect failover and reconnect.\nOutput:\n%s", out)}- t.Log("Node successfully reconnected to Hub B!")+ t.Log("Node successfully reconnected to router B!")// Final verification: Ensure we can actually reach Node B via the Router B relayrelayAddrStr := fmt.Sprintf("/ip4/127.0.0.1/tcp/%d/p2p/%s/p2p-circuit/p2p/%s", routerPortB, peerIDB, nodePeerID)@@ -296,9 +296,9 @@ roles: {}}if connectErr != nil {- t.Fatalf("Failed to connect to Node B via Hub B relay: %v\nOutput: %s", connectErr, stdoutNode.String()+stderrNode.String())+ t.Fatalf("Failed to connect to Node B via router B relay: %v\nOutput: %s", connectErr, stdoutNode.String()+stderrNode.String())}- t.Log("Successfully connected to Node B via Hub B relay circuit!")+ t.Log("Successfully connected to Node B via router B relay circuit!")}// waitForActiveRouters polls the control plane's /info endpoint until at@@ -337,13 +337,13 @@ func fetchActiveRouters(t *testing.T, httpPort int) []string {t.Fatal(err)}- var info api.HubInfoResponse+ var info api.ControlPlaneInfoResponseif err := proto.Unmarshal(body, &info); err != nil {- t.Fatalf("failed to unmarshal HubInfoResponse: %v", err)+ t.Fatalf("failed to unmarshal ControlPlaneInfoResponse: %v", err)}var peerIDs []string- for _, addrStr := range info.HubAddresses {+ for _, addrStr := range info.RouterAddresses {ma, err := multiaddr.NewMultiaddr(addrStr)if err != nil {continuediff --git a/tests/integration/fallback_test.go b/tests/integration/fallback_test.goindex 674b60bd..1a25a82d 100644--- a/tests/integration/fallback_test.go+++ b/tests/integration/fallback_test.go@@ -73,7 +73,7 @@ func TestSelfHealingHTTPFallback(t *testing.T) {pub, priv, err := ed25519.GenerateKey(rand.Reader)if err != nil {- t.Fatalf("Failed to generate hub key: %v", err)+ t.Fatalf("Failed to generate control plane key: %v", err)}createNewHost := func() host.Host {@@ -155,9 +155,9 @@ func TestSelfHealingHTTPFallback(t *testing.T) {}resp := &api.EnrollResponse{- BiscuitToken: createMockBiscuitToken(t, enrollReq.PeerId, priv, api.RoleNode),- HubPublicKey: pub,- HubAddresses: []string{addr},+ BiscuitToken: createMockBiscuitToken(t, enrollReq.PeerId, priv, api.RoleNode),+ ControlPlanePublicKey: pub,+ RouterAddresses: []string{addr},}data, _ := proto.Marshal(resp)w.Header().Set("Content-Type", "application/x-protobuf")@@ -167,11 +167,11 @@ func TestSelfHealingHTTPFallback(t *testing.T) {mu.Lock()addr := currentP2PAddrmu.Unlock()- resp := &api.HubInfoResponse{- OidcIssuer: "http://" + r.Host,- ClientId: "sam-mesh-audience",- Audience: "sam-mesh-audience",- HubAddresses: []string{addr},+ resp := &api.ControlPlaneInfoResponse{+ OidcIssuer: "http://" + r.Host,+ ClientId: "sam-mesh-audience",+ Audience: "sam-mesh-audience",+ RouterAddresses: []string{addr},}data, _ := proto.Marshal(resp)w.Header().Set("Content-Type", "application/x-protobuf")@@ -208,7 +208,7 @@ func TestSelfHealingHTTPFallback(t *testing.T) {t.Fatalf("Join did not succeed:\n%s", out)}- // Step 2: Simulate Hub changing its P2P port (HTTP URL stays the same)+ // Step 2: Simulate router changing its P2P port (HTTP URL stays the same)_ = h.Close()h = createNewHost()defer func() { _ = h.Close() }()@@ -236,8 +236,8 @@ func TestSelfHealingHTTPFallback(t *testing.T) {success := falsefor i := 0; i < 50; i++ {out = stdout.String()- if strings.Contains(out, "Fetching latest hub addresses via HTTP") &&- strings.Contains(out, "Successfully authenticated with hub via libp2p") {+ if strings.Contains(out, "Fetching latest router addresses via HTTP") &&+ strings.Contains(out, "Successfully authenticated with router via libp2p") {success = truebreak}diff --git a/tests/integration/federation_test.go b/tests/integration/federation_test.goindex f9d42562..f6651fb5 100644--- a/tests/integration/federation_test.go+++ b/tests/integration/federation_test.go@@ -34,7 +34,7 @@ import ("github.com/libp2p/go-libp2p/core/peer")-func TestHubFederationAndRelay(t *testing.T) {+func TestRouterFederationAndRelay(t *testing.T) {cpBin := buildBinary(t, "./cmd/sam-control-plane")routerBin := buildBinary(t, "./cmd/sam-router")nodeBin := buildBinary(t, "./cmd/sam-node")@@ -63,7 +63,7 @@ roles:// Start Fake DNS ServerdnsServer, err := NewFakeDNSServer(map[string]string{- "test-hub.local": "127.0.0.1",+ "test-router.local": "127.0.0.1",}, map[string][]string{})if err != nil {t.Fatalf("failed to start fake dns: %v", err)@@ -139,7 +139,7 @@ roles:"--listen", fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", routerPortA),"--keys-path", routerKeysPathA,"--allow-loopback",- "--external-addr", "/dnsaddr/test-hub.local",+ "--external-addr", "/dnsaddr/test-router.local","--oidc-token", routerJWT,)var stdoutRouterA, stderrRouterA safeBuffer@@ -157,7 +157,7 @@ roles:"--listen", fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", routerPortB),"--keys-path", routerKeysPathB,"--allow-loopback",- "--external-addr", "/dnsaddr/test-hub.local",+ "--external-addr", "/dnsaddr/test-router.local","--oidc-token", routerJWT,)var stdoutRouterB, stderrRouterB safeBuffer@@ -179,7 +179,7 @@ roles:}// Update Fake DNS with Router A and Router B multiaddresses- dnsServer.UpdateTXT("_dnsaddr.test-hub.local", []string{+ dnsServer.UpdateTXT("_dnsaddr.test-router.local", []string{fmt.Sprintf("dnsaddr=/ip4/127.0.0.1/tcp/%d/p2p/%s", routerPortA, peerIDA),fmt.Sprintf("dnsaddr=/ip4/127.0.0.1/tcp/%d/p2p/%s", routerPortB, peerIDB),})@@ -194,7 +194,7 @@ roles:// Node A connects to Router A (via shared CP)apiPortA := getFreePort(t)- nodeACmd := exec.Command(nodeBin, "run", "--hub", fmt.Sprintf("http://127.0.0.1:%d", cpPort),+ nodeACmd := exec.Command(nodeBin, "run", "--control-plane", fmt.Sprintf("http://127.0.0.1:%d", cpPort),"--data-dir", filepath.Join(tmpDir, "nodeA"),"--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortA),"--api-token", "tokenA",@@ -216,7 +216,7 @@ roles:// Node B connects to Router B (via shared CP)apiPortB := getFreePort(t)- nodeBCmd := exec.Command(nodeBin, "run", "--hub", fmt.Sprintf("http://127.0.0.1:%d", cpPort),+ nodeBCmd := exec.Command(nodeBin, "run", "--control-plane", fmt.Sprintf("http://127.0.0.1:%d", cpPort),"--data-dir", filepath.Join(tmpDir, "nodeB"),"--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortB),"--api-token", "tokenB",diff --git a/tests/integration/local_policy_test.go b/tests/integration/local_policy_test.goindex db4e9b0d..c5d743bf 100644--- a/tests/integration/local_policy_test.go+++ b/tests/integration/local_policy_test.go@@ -17,9 +17,9 @@ func TestLocalPolicyCanGrantPermissions(t *testing.T) {oidcURL, mintToken := startCustomMockOIDC(t)- // Hub Policy that grants NOTHING.- hubPolicyFile := filepath.Join(tmpDir, "policies.yaml")- hubPolicyYAML := `version: "v1alpha1"+ // Control plane policy that grants NOTHING.+ controlPlanePolicyFile := filepath.Join(tmpDir, "policies.yaml")+ controlPlanePolicyYAML := `version: "v1alpha1"roles:none:allowed_services: []@@ -30,12 +30,12 @@ bindings:- role: nonemembers: ["user:nodeB-user"]`- if err := os.WriteFile(hubPolicyFile, []byte(hubPolicyYAML), 0644); err != nil {+ if err := os.WriteFile(controlPlanePolicyFile, []byte(controlPlanePolicyYAML), 0644); err != nil {t.Fatal(err)}- httpPortHub, cleanupHub := startControlPlaneAndRouter(t, tmpDir, oidcURL, mintToken, hubPolicyFile)- defer cleanupHub()+ httpPortCP, cleanupCP := startControlPlaneAndRouter(t, tmpDir, oidcURL, mintToken, controlPlanePolicyFile)+ defer cleanupCP()// Node B Config with a permissive local policynodeBPolicyFile := filepath.Join(tmpDir, "nodeB_config.yaml")@@ -57,7 +57,7 @@ attenuation:apiPortB := getFreePort(t)cmdB := exec.Command(nodeBin, "run",- "--hub", fmt.Sprintf("http://127.0.0.1:%d", httpPortHub),+ "--control-plane", fmt.Sprintf("http://127.0.0.1:%d", httpPortCP),"--data-dir", homeB,"--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortB),"--api-token", apiTokenB,@@ -101,7 +101,7 @@ attenuation:apiPortA := getFreePort(t)cmdA := exec.Command(nodeBin, "run",- "--hub", fmt.Sprintf("http://127.0.0.1:%d", httpPortHub),+ "--control-plane", fmt.Sprintf("http://127.0.0.1:%d", httpPortCP),"--data-dir", homeA,"--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortA),"--api-token", apiTokenA,@@ -132,7 +132,7 @@ attenuation:waitForAPI(t, actualApiAddrA)// Make request from Node A to Node B- // Even though Node A has no Hub permissions, Node B's local policy "allow if true;" should permit it.+ // Even though Node A has no control plane permissions, Node B's local policy "allow if true;" should permit it.resp, callErr := callMCPAllowError(t, actualApiAddrA, apiTokenA, "call_remote_tool", map[string]any{"peer_id": peerIDB,"tool_name": "mcp://test-tool/test_tool",@@ -155,15 +155,15 @@ attenuation:}}-func TestLocalPolicyCannotBypassHubTargetConstraint(t *testing.T) {+func TestLocalPolicyCannotBypassControlPlaneTargetConstraint(t *testing.T) {nodeBin := buildBinary(t, "./cmd/sam-node")tmpDir := t.TempDir()oidcURL, mintToken := startCustomMockOIDC(t)- // Hub Policy that grants service access but RESTRICTS target to "group:admin-only".- hubPolicyFile := filepath.Join(tmpDir, "policies.yaml")- hubPolicyYAML := `version: "v1alpha1"+ // Control plane policy that grants service access but RESTRICTS target to "group:admin-only".+ controlPlanePolicyFile := filepath.Join(tmpDir, "policies.yaml")+ controlPlanePolicyYAML := `version: "v1alpha1"roles:restricted-role:allowed_services: ["*"]@@ -174,15 +174,15 @@ bindings:- role: restricted-rolemembers: ["user:nodeB-user"]`- if err := os.WriteFile(hubPolicyFile, []byte(hubPolicyYAML), 0644); err != nil {+ if err := os.WriteFile(controlPlanePolicyFile, []byte(controlPlanePolicyYAML), 0644); err != nil {t.Fatal(err)}- httpPortHub, cleanupHub := startControlPlaneAndRouter(t, tmpDir, oidcURL, mintToken, hubPolicyFile)- defer cleanupHub()+ httpPortCP, cleanupCP := startControlPlaneAndRouter(t, tmpDir, oidcURL, mintToken, controlPlanePolicyFile)+ defer cleanupCP()// Node B Config with a permissive local policy ("allow if true;")- // Node B will NOT claim "group:admin-only", so it will fail the Hub's target check.+ // Node B will NOT claim "group:admin-only", so it will fail the control plane's target check.nodeBPolicyFile := filepath.Join(tmpDir, "nodeB_config.yaml")nodeBPolicyYAML := `version: "v1alpha1"services:@@ -202,7 +202,7 @@ attenuation:apiPortB := getFreePort(t)cmdB := exec.Command(nodeBin, "run",- "--hub", fmt.Sprintf("http://127.0.0.1:%d", httpPortHub),+ "--control-plane", fmt.Sprintf("http://127.0.0.1:%d", httpPortCP),"--data-dir", homeB,"--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortB),"--api-token", apiTokenB,@@ -246,7 +246,7 @@ attenuation:apiPortA := getFreePort(t)cmdA := exec.Command(nodeBin, "run",- "--hub", fmt.Sprintf("http://127.0.0.1:%d", httpPortHub),+ "--control-plane", fmt.Sprintf("http://127.0.0.1:%d", httpPortCP),"--data-dir", homeA,"--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortA),"--api-token", apiTokenA,@@ -298,6 +298,6 @@ attenuation:}if !failed {- t.Errorf("expected failure due to Hub target constraint check, got success. Resp: %s", resp)+ t.Errorf("expected failure due to control plane target constraint check, got success. Resp: %s", resp)}}diff --git a/tests/integration/login_test.go b/tests/integration/login_test.goindex 1c085917..7d8ad9ae 100644--- a/tests/integration/login_test.go+++ b/tests/integration/login_test.go@@ -72,8 +72,8 @@ func TestSamNodeJoin(t *testing.T) {oidcServer := httptest.NewServer(mux)defer oidcServer.Close()- // Start mock libp2p hub that knows about our mock OIDC server- _, hubAddr := startMockLibp2pHubWithOIDC(t, oidcServer.URL)+ // Start mock libp2p router that knows about our mock OIDC server+ _, routerAddr := startMockRouterWithOIDC(t, oidcServer.URL)stdout, stderr, err := runCommandWithCallback(t,@@ -83,7 +83,7 @@ func TestSamNodeJoin(t *testing.T) {"", // No stdin needednodeBin,"join",- hubAddr,+ routerAddr,)if err != nil {t.Fatalf("join command failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)@@ -102,7 +102,7 @@ func TestSamNodeJoin(t *testing.T) {env,"",nodeBin,- "run", "--hub", hubAddr,+ "run", "--control-plane", routerAddr,"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0","--bind-addr", "127.0.0.1:0",diff --git a/tests/integration/mcp_local_tools_test.go b/tests/integration/mcp_local_tools_test.goindex 0c3ffaed..221b3475 100644--- a/tests/integration/mcp_local_tools_test.go+++ b/tests/integration/mcp_local_tools_test.go@@ -41,12 +41,12 @@ roles: {}}oidcURL, mintToken := startCustomMockOIDC(t)- httpPortHub, cleanupHub := startControlPlaneAndRouter(t, tmpDir, oidcURL, mintToken, policyFile)- defer cleanupHub()+ httpPortCP, cleanupCP := startControlPlaneAndRouter(t, tmpDir, oidcURL, mintToken, policyFile)+ defer cleanupCP()- fetchPeerID(t, httpPortHub)+ fetchPeerID(t, httpPortCP)- hubURL := fmt.Sprintf("http://127.0.0.1:%d", httpPortHub)+ controlPlaneURL := fmt.Sprintf("http://127.0.0.1:%d", httpPortCP)apiToken := "test-token"homeA := t.TempDir()@@ -59,7 +59,7 @@ roles: {}// Start Node At.Log("Starting Node A...")- _ = startBackgroundNode(t, nodeBin, hubURL, homeA,+ _ = startBackgroundNode(t, nodeBin, controlPlaneURL, homeA,"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0","--bind-addr", "127.0.0.1:0",@@ -69,7 +69,7 @@ roles: {}// Start Node Bt.Log("Starting Node B...")- _ = startBackgroundNode(t, nodeBin, hubURL, homeB,+ _ = startBackgroundNode(t, nodeBin, controlPlaneURL, homeB,"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0","--bind-addr", "127.0.0.1:0",@@ -122,13 +122,13 @@ roles: {}if err := json.Unmarshal([]byte(resp), &info); err != nil {t.Fatalf("failed to unmarshal JSON: %v", err)}- if hubLatency, ok := info["hub_latency_ms"].(float64); !ok || hubLatency < 0 {- t.Errorf("expected valid hub_latency_ms float64, got %v", info)+ if routerLatency, ok := info["router_latency_ms"].(float64); !ok || routerLatency < 0 {+ t.Errorf("expected valid router_latency_ms float64, got %v", info)}connectedPeers, ok := info["connected_peers"].(float64)if !ok || connectedPeers < 2 {- t.Errorf("expected at least 2 connected peers (hub + node B), got %v", info)+ t.Errorf("expected at least 2 connected peers (router + node B), got %v", info)}})diff --git a/tests/integration/minimal_helpers_test.go b/tests/integration/minimal_helpers_test.goindex e1efcb53..b73249a7 100644--- a/tests/integration/minimal_helpers_test.go+++ b/tests/integration/minimal_helpers_test.go@@ -209,12 +209,12 @@ func runCommandWithCallback(return stdout.String(), stderr.String(), err}-func startMockLibp2pHub(t *testing.T) (peer.ID, string) {+func startMockRouter(t *testing.T) (peer.ID, string) {t.Helper()pub, priv, err := ed25519.GenerateKey(rand.Reader)if err != nil {- t.Fatalf("Failed to generate hub key: %v", err)+ t.Fatalf("Failed to generate control plane key: %v", err)}h, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"))@@ -242,7 +242,7 @@ func startMockLibp2pHub(t *testing.T) (peer.ID, string) {kdht, err := dht.New(h, dht.Mode(dht.ModeServer), dht.ProtocolPrefix("/sam"))if err != nil {- t.Fatalf("failed to create DHT on mock hub: %v", err)+ t.Fatalf("failed to create DHT on mock router: %v", err)}// Start HTTP server for enrollment@@ -265,9 +265,9 @@ func startMockLibp2pHub(t *testing.T) (peer.ID, string) {}resp := &api.EnrollResponse{- BiscuitToken: createMockBiscuitToken(t, req.PeerId, priv, api.RoleNode),- HubPublicKey: pub,- HubAddresses: []string{h.Addrs()[0].String() + "/p2p/" + h.ID().String()},+ BiscuitToken: createMockBiscuitToken(t, req.PeerId, priv, api.RoleNode),+ ControlPlanePublicKey: pub,+ RouterAddresses: []string{h.Addrs()[0].String() + "/p2p/" + h.ID().String()},}data, err := proto.Marshal(resp)if err != nil {@@ -290,12 +290,12 @@ func startMockLibp2pHub(t *testing.T) (peer.ID, string) {return h.ID(), httpServer.URL}-func startMockLibp2pHubWithOIDC(t *testing.T, oidcIssuerURL string) (peer.ID, string) {+func startMockRouterWithOIDC(t *testing.T, oidcIssuerURL string) (peer.ID, string) {t.Helper()pub, priv, err := ed25519.GenerateKey(rand.Reader)if err != nil {- t.Fatalf("Failed to generate hub key: %v", err)+ t.Fatalf("Failed to generate control plane key: %v", err)}h, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"))@@ -323,7 +323,7 @@ func startMockLibp2pHubWithOIDC(t *testing.T, oidcIssuerURL string) (peer.ID, stkdht, err := dht.New(h, dht.Mode(dht.ModeServer), dht.ProtocolPrefix("/sam"))if err != nil {- t.Fatalf("failed to create DHT on mock hub: %v", err)+ t.Fatalf("failed to create DHT on mock router: %v", err)}// Start HTTP server for enrollment and info@@ -334,7 +334,7 @@ func startMockLibp2pHubWithOIDC(t *testing.T, oidcIssuerURL string) (peer.ID, sthttp.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return}- resp := &api.HubInfoResponse{+ resp := &api.ControlPlaneInfoResponse{OidcIssuer: oidcIssuerURL,ClientId: "sam-mesh-audience",Audience: "sam-mesh-audience",@@ -365,9 +365,9 @@ func startMockLibp2pHubWithOIDC(t *testing.T, oidcIssuerURL string) (peer.ID, st}resp := &api.EnrollResponse{- BiscuitToken: createMockBiscuitToken(t, req.PeerId, priv, api.RoleNode),- HubPublicKey: pub,- HubAddresses: []string{h.Addrs()[0].String() + "/p2p/" + h.ID().String()},+ BiscuitToken: createMockBiscuitToken(t, req.PeerId, priv, api.RoleNode),+ ControlPlanePublicKey: pub,+ RouterAddresses: []string{h.Addrs()[0].String() + "/p2p/" + h.ID().String()},}data, err := proto.Marshal(resp)if err != nil {@@ -540,10 +540,10 @@ func fetchPeerID(t *testing.T, port int) string {bodyBytes, err := io.ReadAll(resp.Body)_ = resp.Body.Close()if err == nil {- var info api.HubInfoResponse+ var info api.ControlPlaneInfoResponseif err := proto.Unmarshal(bodyBytes, &info); err == nil {- if len(info.HubAddresses) > 0 {- peerID = extractPeerID(info.HubAddresses[0])+ if len(info.RouterAddresses) > 0 {+ peerID = extractPeerID(info.RouterAddresses[0])}}}diff --git a/tests/integration/multimaster_test.go b/tests/integration/multimaster_test.goindex 254e7782..01f6eef4 100644--- a/tests/integration/multimaster_test.go+++ b/tests/integration/multimaster_test.go@@ -35,7 +35,7 @@ import ("google.golang.org/protobuf/proto")-func TestMultiMasterHub(t *testing.T) {+func TestMultiMasterControlPlane(t *testing.T) {cpBin := buildBinary(t, "./cmd/sam-control-plane")routerBin := buildBinary(t, "./cmd/sam-router")diff --git a/tests/integration/policy_permutations_test.go b/tests/integration/policy_permutations_test.goindex 571997a3..25db06ac 100644--- a/tests/integration/policy_permutations_test.go+++ b/tests/integration/policy_permutations_test.go@@ -75,9 +75,9 @@ func TestPolicyPermutations(t *testing.T) {oidcURL, mintToken := startCustomMockOIDC(t)- // 1. Hub Policies- hubPolicyFile := filepath.Join(tmpDir, "policies.yaml")- hubPolicyYAML := `version: "v1alpha1"+ // 1. Control plane policies+ controlPlanePolicyFile := filepath.Join(tmpDir, "policies.yaml")+ controlPlanePolicyYAML := `version: "v1alpha1"roles:role-user:allowed_services: ["mcp://test-user"]@@ -112,12 +112,12 @@ bindings:- role: adminmembers: ["user:nodeB"]`- if err := os.WriteFile(hubPolicyFile, []byte(hubPolicyYAML), 0644); err != nil {+ if err := os.WriteFile(controlPlanePolicyFile, []byte(controlPlanePolicyYAML), 0644); err != nil {t.Fatal(err)}- httpPortHub, cleanupHub := startControlPlaneAndRouter(t, tmpDir, oidcURL, mintToken, hubPolicyFile)- defer cleanupHub()+ httpPortCP, cleanupCP := startControlPlaneAndRouter(t, tmpDir, oidcURL, mintToken, controlPlanePolicyFile)+ defer cleanupCP()// 2. Node B (Target) ConfignodeBPolicyFile := filepath.Join(tmpDir, "nodeB_config.yaml")@@ -148,7 +148,7 @@ services:apiPortB := getFreePort(t)cmdB := exec.Command(nodeBin, "run",- "--hub", fmt.Sprintf("http://127.0.0.1:%d", httpPortHub),+ "--control-plane", fmt.Sprintf("http://127.0.0.1:%d", httpPortCP),"--data-dir", homeB,"--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortB),"--api-token", apiTokenB,@@ -184,11 +184,11 @@ services:// 3. Test Permutationstests := []struct {- name string- jwtClaims map[string]interface{}- targetSvc string- expectAllow bool- expectHubErr bool+ name string+ jwtClaims map[string]interface{}+ targetSvc string+ expectAllow bool+ expectControlPlaneErr bool}{{name: "Fact sub: user(bob-subject)",@@ -221,7 +221,7 @@ services:expectAllow: true,},{- name: "Unknown User / No Roles -> Hub Error",+ name: "Unknown User / No Roles -> control plane error",jwtClaims: map[string]interface{}{"sub": "unknown"},targetSvc: "mcp://test-user",expectAllow: false,@@ -244,7 +244,7 @@ services:jwtA := mintToken(tt.jwtClaims)cmdA := exec.Command(nodeBin, "run",- "--hub", fmt.Sprintf("http://127.0.0.1:%d", httpPortHub),+ "--control-plane", fmt.Sprintf("http://127.0.0.1:%d", httpPortCP),"--data-dir", homeA,"--bind-addr", fmt.Sprintf("127.0.0.1:%d", apiPortA),"--api-token", apiTokenA,diff --git a/tests/integration/proxy_test.go b/tests/integration/proxy_test.goindex b5085d45..72a32493 100644--- a/tests/integration/proxy_test.go+++ b/tests/integration/proxy_test.go@@ -57,11 +57,11 @@ func TestSamNodeRunWithStoredIdentity(t *testing.T) {if err := b.Put([]byte("identity_biscuit"), biscuitBytes); err != nil {return err}- if err := b.Put([]byte("hub_public_key"), pub); err != nil {+ if err := b.Put([]byte("control_plane_public_key"), pub); err != nil {return err}addrsData, _ := json.Marshal([]string{"/ip4/127.0.0.1/tcp/4002/p2p/Qm..."})- if err := b.Put([]byte("hub_addresses"), addrsData); err != nil {+ if err := b.Put([]byte("router_addresses"), addrsData); err != nil {return err}return nildiff --git a/tests/integration/pubsub_test.go b/tests/integration/pubsub_test.goindex 240ad159..a6bd3197 100644--- a/tests/integration/pubsub_test.go+++ b/tests/integration/pubsub_test.go@@ -26,7 +26,7 @@ import (func TestPubSubTools(t *testing.T) {nodeBin := buildBinary(t, "./cmd/sam-node")- _, hubAddr := startMockLibp2pHub(t)+ _, routerAddr := startMockRouter(t)tmpHome1, err := os.MkdirTemp("", "pubsub-test-1")if err != nil {t.Fatal(err)@@ -44,7 +44,7 @@ func TestPubSubTools(t *testing.T) {// Start Node 1env1 := append(os.Environ(), "HOME="+tmpHome1, "XDG_CONFIG_HOME="+filepath.Join(tmpHome1, ".config"))- cmd1 := exec.CommandContext(ctx, nodeBin, "run", "--hub", hubAddr, "--bind-addr", "127.0.0.1:0", "--listen", "/ip4/127.0.0.1/udp/5003/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/5004", "--jwt", "dummy-token", "--log-level", "debug", "--discovery-interval", "100ms", "--api-token", "test-token", "--allow-loopback")+ cmd1 := exec.CommandContext(ctx, nodeBin, "run", "--control-plane", routerAddr, "--bind-addr", "127.0.0.1:0", "--listen", "/ip4/127.0.0.1/udp/5003/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/5004", "--jwt", "dummy-token", "--log-level", "debug", "--discovery-interval", "100ms", "--api-token", "test-token", "--allow-loopback")cmd1.Env = env1logFile1, err := os.Create(filepath.Join(tmpHome1, "node1.log"))if err != nil {@@ -59,7 +59,7 @@ func TestPubSubTools(t *testing.T) {// Start Node 2env2 := append(os.Environ(), "HOME="+tmpHome2, "XDG_CONFIG_HOME="+filepath.Join(tmpHome2, ".config"))- cmd2 := exec.CommandContext(ctx, nodeBin, "run", "--hub", hubAddr, "--bind-addr", "127.0.0.1:0", "--listen", "/ip4/127.0.0.1/udp/5005/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/5006", "--jwt", "dummy-token", "--log-level", "debug", "--discovery-interval", "100ms", "--api-token", "test-token", "--allow-loopback")+ cmd2 := exec.CommandContext(ctx, nodeBin, "run", "--control-plane", routerAddr, "--bind-addr", "127.0.0.1:0", "--listen", "/ip4/127.0.0.1/udp/5005/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/5006", "--jwt", "dummy-token", "--log-level", "debug", "--discovery-interval", "100ms", "--api-token", "test-token", "--allow-loopback")cmd2.Env = env2logFile2, err := os.Create(filepath.Join(tmpHome2, "node2.log"))if err != nil {diff --git a/tests/integration/revocation_test.go b/tests/integration/revocation_test.goindex 3277f583..24e4a071 100644--- a/tests/integration/revocation_test.go+++ b/tests/integration/revocation_test.go@@ -124,7 +124,7 @@ roles:defer func() { _ = node1LogFile.Close() }()node1Cmd := exec.Command(nodeBin, "run",- "--hub", fmt.Sprintf("http://127.0.0.1:%d", cpPort),+ "--control-plane", fmt.Sprintf("http://127.0.0.1:%d", cpPort),"--jwt", mintToken(map[string]interface{}{"sub": "mock-user", "roles": []string{api.RoleNode}}),"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0",@@ -154,7 +154,7 @@ roles:defer func() { _ = node2LogFile.Close() }()node2Cmd := exec.Command(nodeBin, "run",- "--hub", fmt.Sprintf("http://127.0.0.1:%d", cpPort),+ "--control-plane", fmt.Sprintf("http://127.0.0.1:%d", cpPort),"--jwt", mintToken(map[string]interface{}{"sub": "mock-user", "roles": []string{api.RoleNode}}),"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0",diff --git a/tests/integration/rotation_test.go b/tests/integration/rotation_test.goindex 6c667b64..74178d82 100644--- a/tests/integration/rotation_test.go+++ b/tests/integration/rotation_test.go@@ -126,7 +126,7 @@ roles:defer func() { _ = nodeLogFile.Close() }()nodeCmd := exec.Command(nodeBin, "run",- "--hub", fmt.Sprintf("http://127.0.0.1:%d", cpPort),+ "--control-plane", fmt.Sprintf("http://127.0.0.1:%d", cpPort),"--jwt", nodeJWT,"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0",diff --git a/tests/integration/service_discovery_test.go b/tests/integration/service_discovery_test.goindex 93164bc8..9d48ef86 100644--- a/tests/integration/service_discovery_test.go+++ b/tests/integration/service_discovery_test.go@@ -34,7 +34,7 @@ import (func TestServiceDiscovery(t *testing.T) {nodeBin := buildBinary(t, "./cmd/sam-node")- _, hubAddr := startMockLibp2pHub(t)+ _, routerAddr := startMockRouter(t)homeA := t.TempDir()homeB := t.TempDir()@@ -43,7 +43,7 @@ func TestServiceDiscovery(t *testing.T) {// Start Node At.Log("Starting Node A...")- _ = startBackgroundNode(t, nodeBin, hubAddr, homeA,+ _ = startBackgroundNode(t, nodeBin, routerAddr, homeA,"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0","--discovery-interval", "100ms",@@ -53,7 +53,7 @@ func TestServiceDiscovery(t *testing.T) {// Start Node Bt.Log("Starting Node B...")- _ = startBackgroundNode(t, nodeBin, hubAddr, homeB,+ _ = startBackgroundNode(t, nodeBin, routerAddr, homeB,"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0","--discovery-interval", "100ms",@@ -138,7 +138,7 @@ func TestServiceDiscovery(t *testing.T) {func TestServiceDiscoveryStreaming(t *testing.T) {nodeBin := buildBinary(t, "./cmd/sam-node")- _, hubAddr := startMockLibp2pHub(t)+ _, routerAddr := startMockRouter(t)homeA := t.TempDir()homeB := t.TempDir()@@ -147,7 +147,7 @@ func TestServiceDiscoveryStreaming(t *testing.T) {// Start Node At.Log("Starting Node A...")- _ = startBackgroundNode(t, nodeBin, hubAddr, homeA,+ _ = startBackgroundNode(t, nodeBin, routerAddr, homeA,"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0","--discovery-interval", "100ms",@@ -157,7 +157,7 @@ func TestServiceDiscoveryStreaming(t *testing.T) {// Start Node Bt.Log("Starting Node B...")- _ = startBackgroundNode(t, nodeBin, hubAddr, homeB,+ _ = startBackgroundNode(t, nodeBin, routerAddr, homeB,"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0","--discovery-interval", "100ms",