{"modulePath":"github.com/plexsphere/plexd","version":"v0.42.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package api\n\n## Constants\n\n```go\nconst (\n\t// Contract types are emitted by the control plane per the OpenAPI events\n\t// document. Their payloads are treated as opaque: the reconciler pull is\n\t// authoritative, so each of these events triggers a reconcile.\n\tEventNodeStateUpdated    = \"node_state_updated\"\n\tEventPolicyUpdated       = \"policy_updated\"\n\tEventBridgeConfigUpdated = \"bridge_config_updated\"\n\n\t// EventActionRequest exists as a push-latency optimisation: action\n\t// dispatches are delivered in the executions block of the state pull, so the\n\t// event's payload is opaque and it triggers a reconcile like the rest of the\n\t// tier — the resulting pull carries the dispatch.\n\tEventActionRequest = \"action_request\"\n\n\t// EventSessionSetup is the same push-latency optimisation for mediated\n\t// access: sessions are delivered in the sessions block of the state pull, so\n\t// the event's payload is opaque and it triggers a reconcile like the rest of\n\t// the tier — the resulting pull carries the session.\n\tEventSessionSetup = \"session_setup\"\n\n\t// EventNodeSecretsUpdated carries the node's full secret inventory, but the\n\t// inventory also rides the secrets block of the state pull, which is\n\t// authoritative: the payload is treated as opaque and the event triggers a\n\t// reconcile like the rest of the tier, so an event that arrives late can\n\t// never roll the node API's secret index back.\n\tEventNodeSecretsUpdated = \"node_secrets_updated\"\n\n\t// Documented-coming family: types that land with the platform's 14-type\n\t// taxonomy. They are already named so the agent can subscribe to them once\n\t// the control plane starts emitting them; every one triggers a reconcile.\n\tEventPeerRegistered      = \"peer_registered\"\n\tEventPeerPSKAssigned     = \"peer_psk_assigned\"\n\tEventPeerDeregistered    = \"peer_deregistered\"\n\tEventPeerEndpointChanged = \"peer_endpoint_changed\"\n\tEventRotateKeys          = \"rotate_keys\"\n\tEventPeerKeyRotated      = \"peer_key_rotated\"\n\tEventSigningKeyRotated   = \"signing_key_rotated\"\n\n\t// EventSessionRevoked names a session the control plane revoked, in a\n\t// SessionRevocation payload. tunnel.Dispatcher.SessionRevokedHandler closes\n\t// that session when it is live and reports the payload's revoke_reason as\n\t// its terminated_by, then triggers a reconcile. The session leaving the\n\t// pull's sessions block stays the teardown for a revocation whose event\n\t// never arrives.\n\tEventSessionRevoked = \"session_revoked\"\n\n\t// EventSessionConnect asks the node to open one connection for an ssh\n\t// session it serves, in a SessionConnectRequest payload. The control plane\n\t// sends it when a client attaches to the session, and\n\t// tunnel.Dispatcher.SessionConnectHandler opens the connection with\n\t// ControlPlane.OpenSessionConnection and serves the session's SSH login on\n\t// it. It carries no desired state, so it triggers no reconcile.\n\tEventSessionConnect = \"session_connect\"\n)\n```\n\n```go\nconst (\n\t// ReachabilityHealthy marks a node whose heartbeats arrive on schedule.\n\tReachabilityHealthy = \"healthy\"\n\t// ReachabilityStale marks a node whose last admitted heartbeat is older than\n\t// the control plane's freshness window.\n\tReachabilityStale = \"stale\"\n\t// ReachabilityUnreachable marks a node the control plane has given up on.\n\tReachabilityUnreachable = \"unreachable\"\n\t// ReachabilityNeverReported marks a node whose first heartbeat was never\n\t// admitted. It is the verdict a freshly enrolled node is born with.\n\tReachabilityNeverReported = \"never_reported\"\n)\n```\nReachability verdicts the platform contract documents today. The set is open: these are the values plexd expects to see, not the values it accepts.\n\n```go\nconst (\n\tRevokeReasonOperatorRequest        = \"operator_request\"\n\tRevokeReasonPolicyViolation        = \"policy_violation\"\n\tRevokeReasonIdentityCompromise     = \"identity_compromise\"\n\tRevokeReasonResourceDecommissioned = \"resource_decommissioned\"\n\tRevokeReasonTTLExpired             = \"ttl_expired\"\n\tRevokeReasonIdleTimeout            = \"idle_timeout\"\n)\n```\nReasons the control plane revokes a session, carried on SessionRevocation.RevokeReason. The first four are operator-driven, supplied on the explicit revoke call; the last two are set by the control plane's sweeper when the session reaches its hard expiry or its idle timeout.\n\n```go\nconst (\n\t// ActionKindBuiltin dispatches an action built into plexd.\n\tActionKindBuiltin = \"builtin\"\n\t// ActionKindHook dispatches a hook registered by the node.\n\tActionKindHook = \"hook\"\n\t// ActionKindPlexdHook dispatches a PlexdHook resource of the node's\n\t// cluster. The entry's Action is the resource's metadata.name.\n\tActionKindPlexdHook = \"plexd_hook\"\n)\n```\nThe three legal values of a NodeStateExecution.Type.\n\n```go\nconst (\n\t// ExecutionStatusAck acknowledges receipt of the action request.\n\tExecutionStatusAck = \"ack\"\n\t// ExecutionStatusStarted reports that the action has begun running.\n\tExecutionStatusStarted = \"started\"\n\t// ExecutionStatusSucceeded is the terminal callback for a successful run.\n\tExecutionStatusSucceeded = \"succeeded\"\n\t// ExecutionStatusFailed is the terminal callback for a failed run.\n\tExecutionStatusFailed = \"failed\"\n\t// ExecutionStatusCancelled is the terminal callback for a cancelled run.\n\tExecutionStatusCancelled = \"cancelled\"\n)\n```\nExecution callback statuses a node reports on the v1 execution callback (POST /v1/nodes/{node\\_id}/executions/{execution\\_id}).\n\n```go\nconst (\n\t// CodeNSKNodeMismatch (403) means the callback's node id does not match the\n\t// node identified by the NSK bearer credential.\n\tCodeNSKNodeMismatch = \"nsk_node_mismatch\"\n\t// CodeInvalidStateTransition (409) means the callback would advance the\n\t// invocation along an illegal edge of the execution state machine.\n\tCodeInvalidStateTransition = \"invalid_state_transition\"\n\t// CodeExecutionAlreadyTerminal (409) means the invocation has already\n\t// settled and accepts no further callbacks.\n\tCodeExecutionAlreadyTerminal = \"execution_already_terminal\"\n)\n```\nRFC 9457 problem codes with which the control plane refuses an execution callback. A refusal carrying one of these is deliberate and permanent: the node must stop driving the execution instead of retrying or double-reporting.\n\n```go\nconst (\n\t// SessionKindSSH mediates an SSH session; Target.SSH is set.\n\tSessionKindSSH = \"ssh\"\n\t// SessionKindK8s mediates a Kubernetes API session; Target.K8s is set.\n\tSessionKindK8s = \"k8s\"\n\t// SessionKindTCP mediates a plain TCP forward; Target.TCP is set.\n\tSessionKindTCP = \"tcp\"\n)\n```\nThe three legal values of a NodeStateSession.Kind.\n\n```go\nconst (\n\tMetricGroupNodeResources = \"node_resources\"\n\tMetricGroupTunnelHealth  = \"tunnel_health\"\n\tMetricGroupPeerLatency   = \"peer_latency\"\n\tMetricGroupAgentStats    = \"agent_stats\"\n)\n```\nWire metric groups (closed set; out-of-set → 400 ingest\\_batch\\_malformed).\n\n```go\nconst (\n\t// HookSourceLocal marks a hook placed on the node by other means than a\n\t// rollout, such as a script in hooks_dir. Its pin is the digest first seen.\n\tHookSourceLocal = \"local\"\n\t// HookSourceRollout marks a script installed from a published hook\n\t// version. Its pin is the checksum the pull delivered.\n\tHookSourceRollout = \"rollout\"\n)\n```\nValues of DeclaredHook.Source and HookInfo.Source: where a hook the agent runs came from. The wire treats an absent source as local, which is why a hand-placed hook is sent with no source key at all.\n\n```go\nconst (\n\t// HookRolloutCodeCollision means hooks_dir holds a hook of the rollout's\n\t// name. The node leaves that hook in place, keeps reporting it as local,\n\t// and reports the collision rather than resolving it.\n\tHookRolloutCodeCollision = \"collision\"\n\t// HookRolloutCodeVerificationFailed means the node fetched the version,\n\t// and its signature or its checksum did not verify.\n\tHookRolloutCodeVerificationFailed = \"verification_failed\"\n\t// HookRolloutCodeFetchFailed means the node could not fetch the version.\n\tHookRolloutCodeFetchFailed = \"fetch_failed\"\n\t// HookRolloutCodeInstallFailed means the node could not install the\n\t// version, or will not on this platform or under this configuration.\n\tHookRolloutCodeInstallFailed = \"install_failed\"\n)\n```\nCodes of a HookRolloutError the contract documents. The control plane accepts any code that matches ^\\[a-z0-9\\_]{1,64}$ and shows it as sent, so a newer agent's code never refuses the manifest.\n\n```go\nconst (\n\t// MaxHookRolloutErrors is the most entries one manifest may carry.\n\tMaxHookRolloutErrors = 64\n\t// MaxHookRolloutDetailChars is the longest detail, in Unicode code points.\n\tMaxHookRolloutDetailChars = 1024\n)\n```\nLimits the control plane puts on hook\\_rollout\\_errors. plexd keeps a copy so a manifest it builds stays inside them; IsHookMetadataRefused covers the case where the copies drift apart.\n\n```go\nconst (\n\t// RelayStateRunning marks a relay whose socket is bound on ListenPort.\n\tRelayStateRunning = \"running\"\n\t// RelayStateStopped marks a relay that does not run: the pull does not\n\t// enable it, names a listen_port outside 1..65535, or plexd stops it\n\t// because it shuts down.\n\tRelayStateStopped = \"stopped\"\n\t// RelayStateBindFailed marks a relay whose socket could not be bound on\n\t// ListenPort.\n\tRelayStateBindFailed = \"bind_failed\"\n\t// RelayStateNotConsented marks a relay the pull enables while\n\t// bridge.relay_enabled does not consent to it.\n\tRelayStateNotConsented = \"not_consented\"\n)\n```\nRelay states of a RelayStatusRequest.\n\n```go\nconst (\n\t// IngressStateEnabled marks a bridge whose local configuration serves the\n\t// public ingress rules the state pull enables.\n\tIngressStateEnabled = \"enabled\"\n\t// IngressStateOptedOut marks a bridge whose local configuration,\n\t// bridge.ingress_enabled: false, rules public ingress out: it opens no\n\t// public listener whatever the pull says.\n\tIngressStateOptedOut = \"opted_out\"\n)\n```\nIngress states of an IngressStatusRequest.\n\n```go\nconst (\n\t// IngressListenerListening marks a rule whose listen port is bound.\n\tIngressListenerListening = \"listening\"\n\t// IngressListenerNotListening marks a rule the bridge does not listen\n\t// for; ListenerReason says why.\n\tIngressListenerNotListening = \"not_listening\"\n\n\t// IngressCertificateNotRequired marks a passthrough rule, which needs no\n\t// certificate at the bridge.\n\tIngressCertificateNotRequired = \"not_required\"\n\t// IngressCertificateReady marks a terminate or acme rule whose\n\t// certificate is in place.\n\tIngressCertificateReady = \"ready\"\n\t// IngressCertificateNotReady marks a terminate or acme rule without its\n\t// certificate; CertificateReason says why.\n\tIngressCertificateNotReady = \"not_ready\"\n\n\t// IngressDialNone marks a rule for which the bridge has dialled no target\n\t// yet, or a target it has not dialled yet. For a udp rule a dial is a\n\t// send of a client's datagram.\n\tIngressDialNone = \"none\"\n\t// IngressDialSucceeded marks a rule whose last unit a target took, or a\n\t// target whose last dial succeeded.\n\tIngressDialSucceeded = \"succeeded\"\n\t// IngressDialFailed marks a rule whose last unit no target took, or a\n\t// target whose last dial failed; DialReason says why.\n\tIngressDialFailed = \"failed\"\n)\n```\nThe facets of an IngressStatusRule.\n\n```go\nconst (\n\t// UserAccessStateEnabled marks a bridge whose local configuration serves\n\t// the user access providers the state pull enables.\n\tUserAccessStateEnabled = \"enabled\"\n\t// UserAccessStateOptedOut marks a bridge whose local configuration,\n\t// bridge.user_access_enabled: false, rules user access out: it serves no\n\t// provider whatever the pull says.\n\tUserAccessStateOptedOut = \"opted_out\"\n)\n```\nUser access states of a UserAccessStatusRequest.\n\n```go\nconst (\n\t// UserAccessHealthUp marks a provider the bridge serves.\n\tUserAccessHealthUp = \"up\"\n\t// UserAccessHealthDown marks a provider the bridge does not serve; Reason\n\t// says why.\n\tUserAccessHealthDown = \"down\"\n)\n```\nThe health values of a UserAccessStatusProvider.\n\n```go\nconst (\n\t// SiteToSiteStateEnabled marks a bridge whose local configuration serves\n\t// the site-to-site tunnels the state pull enables.\n\tSiteToSiteStateEnabled = \"enabled\"\n\t// SiteToSiteStateOptedOut marks a bridge whose local configuration,\n\t// bridge.site_to_site_enabled: false, rules site-to-site tunnels out: it\n\t// serves no tunnel whatever the pull says.\n\tSiteToSiteStateOptedOut = \"opted_out\"\n)\n```\nSite-to-site states of a SiteToSiteStatusRequest.\n\n```go\nconst (\n\t// SiteToSiteHealthUp marks a tunnel the bridge serves.\n\tSiteToSiteHealthUp = \"up\"\n\t// SiteToSiteHealthDown marks a tunnel the bridge does not serve; Reason\n\t// says why.\n\tSiteToSiteHealthDown = \"down\"\n)\n```\nThe health values of a SiteToSiteStatusTunnel.\n\n```go\nconst (\n\t// PolicyEnforcementEnforcing marks a node that programs the rulesets it\n\t// applies, with its default deny after them.\n\tPolicyEnforcementEnforcing = \"enforcing\"\n\t// PolicyEnforcementDisabled marks a node whose local configuration turned\n\t// enforcement off (policy.enabled: false).\n\tPolicyEnforcementDisabled = \"disabled\"\n\t// PolicyEnforcementUnavailable marks a node that enforces but has no\n\t// firewall backend that can program rules.\n\tPolicyEnforcementUnavailable = \"unavailable\"\n)\n```\nEnforcement values of a PolicyStatusRequest.\n\n```go\nconst (\n\t// TCPPhaseSessionStarted marks the opening of a TCP session.\n\tTCPPhaseSessionStarted = \"session_started\"\n\t// TCPPhaseSessionActive reports that a TCP session forwarded bytes since its\n\t// previous session_active row. The row carries Phase alone.\n\tTCPPhaseSessionActive = \"session_active\"\n\t// TCPPhaseSessionEnded marks the close of a TCP session.\n\tTCPPhaseSessionEnded = \"session_ended\"\n)\n```\nTCP session lifecycle phases reported on a TCPActivity.\n\n```go\nconst (\n\t// SSHPhaseSessionStarted marks an SSH session ready to serve the\n\t// connections the control plane asks for.\n\tSSHPhaseSessionStarted = \"session_started\"\n\t// SSHPhaseSessionEnded marks the close of an SSH session.\n\tSSHPhaseSessionEnded = \"session_ended\"\n)\n```\nSSH session lifecycle phases reported on an SSHActivity.\n\n```go\nconst (\n\t// TerminatedByTTLExpired means the session reached its time-to-live.\n\tTerminatedByTTLExpired = \"ttl_expired\"\n\t// TerminatedByIdleTimeout means the session was idle past its timeout.\n\tTerminatedByIdleTimeout = \"idle_timeout\"\n\t// TerminatedByPlexdClose means plexd closed the session locally.\n\tTerminatedByPlexdClose = \"plexd_close\"\n\t// TerminatedByOperatorRevoke means the operator's access was revoked.\n\tTerminatedByOperatorRevoke = \"operator_revoke\"\n)\n```\nReasons a TCP or SSH session was terminated, reported on a session\\_ended TCPActivity or SSHActivity.\n\n```go\nconst (\n\t// UserAccessKindWireGuard is a WireGuard interface on the bridge that\n\t// admits the devices the operator registers by their public keys.\n\tUserAccessKindWireGuard = \"wireguard\"\n\t// UserAccessKindTailscale joins the bridge to a tailnet.\n\tUserAccessKindTailscale = \"tailscale\"\n\t// UserAccessKindNetbird joins the bridge to a NetBird network.\n\tUserAccessKindNetbird = \"netbird\"\n)\n```\nThe kinds of a user access provider.\n\n```go\nconst (\n\tIngressModePassthrough = \"passthrough\"\n\tIngressModeTerminate   = \"terminate\"\n\tIngressModeACME        = \"acme\"\n)\n```\nThe modes of an ingress rule.\n\n```go\nconst (\n\tIngressProtocolTCP = \"tcp\"\n\tIngressProtocolUDP = \"udp\"\n)\n```\nThe protocols of an ingress rule. A tcp rule forwards the connections that reach its listen port, and a udp rule the datagrams.\n\n```go\nconst (\n\t// SiteToSiteKindWireGuard is a WireGuard interface on the bridge with\n\t// one peer, the remote site.\n\tSiteToSiteKindWireGuard = \"wireguard\"\n\t// SiteToSiteKindIPsec is an IKE connection to the remote site,\n\t// authenticated with a pre-shared key.\n\tSiteToSiteKindIPsec = \"ipsec\"\n\t// SiteToSiteKindOpenVPN is a point-to-point OpenVPN connection to the\n\t// remote site with a static key.\n\tSiteToSiteKindOpenVPN = \"openvpn\"\n)\n```\nThe kinds of a site-to-site tunnel.\n\n```go\nconst DefaultConnectTimeout = 10 * time.Second\n```\nDefaultConnectTimeout is the default TCP connect timeout.\n\n```go\nconst DefaultRequestTimeout = 30 * time.Second\n```\nDefaultRequestTimeout is the default HTTP request timeout.\n\n```go\nconst DefaultSSEIdleTimeout = 90 * time.Second\n```\nDefaultSSEIdleTimeout is the default SSE idle timeout.\n\n```go\nconst DefaultSSEReprobeInterval = 10 * time.Minute\n```\nDefaultSSEReprobeInterval is how often pull-only delivery mode re-probes the descoped SSE endpoint to detect that it has come back.\n\n```go\nconst DefaultStalenessWindow = 5 * time.Minute\n```\nDefaultStalenessWindow is the maximum age of an event before it is considered stale.\n\n```go\nconst EdgePSKEnvelopeSize = 60\n```\nEdgePSKEnvelopeSize is the exact length of an edge-PSK envelope: the 12-byte AES-256-GCM nonce, the 32-byte PSK and the 16-byte GCM tag.\n\n```go\nconst (\n\t// ExecutionStatusPending marks an execution the control plane has dispatched\n\t// and the node has not yet acknowledged. It appears in the executions block\n\t// of the node state snapshot and is never reported by a node on the\n\t// execution callback.\n\tExecutionStatusPending = \"pending\"\n)\n```\nExecution status observed only on the pull block.\n\n```go\nconst FeatureMeshReaddress = \"mesh_readdress\"\n```\nFeatureMeshReaddress is the feature a node declares in HeartbeatRequest.Features when it applies a changed NodeStateSnapshot.MeshIP while it runs. The control plane moves a node to another mesh address only while the node's latest heartbeat declared it.\n\n```go\nconst HookVersionEnvelopeType = \"hook_version\"\n```\nHookVersionEnvelopeType is the type of the envelope a published hook version is signed in. The envelope is not an event and never rides the event stream, so the type sits here rather than among the SSE event types.\n\n```go\nconst MaxEndpointCandidates = 8\n```\nMaxEndpointCandidates is the contract's ceiling on one candidate report.\n\n```go\nconst MaxHandshakeReportPeers = 4096\n```\nMaxHandshakeReportPeers is the contract's ceiling on the peers array of one handshake report. A longer array is refused whole with 400 malformed\\_handshake\\_report, taking every edge in it down, so ReportHandshakes refuses one before sending it.\n\n```go\nconst MaxHandshakeSharedSubnets = 256\n```\nMaxHandshakeSharedSubnets is the contract's ceiling on the shared\\_subnets of one handshake report entry. A longer list is refused whole with 400 malformed\\_handshake\\_report.\n\n```go\nconst MaxIngressStatusClientRefusals = 8\n```\nMaxIngressStatusClientRefusals is the contract's ceiling on the refusal entries of one rule entry.\n\n```go\nconst MaxIngressStatusDialAgeSeconds = 2147483647\n```\nMaxIngressStatusDialAgeSeconds is the contract's ceiling on dial\\_age\\_seconds, the largest signed 32-bit integer.\n\n```go\nconst MaxIngressStatusRefusalAgeSeconds = 2147483647\n```\nMaxIngressStatusRefusalAgeSeconds is the contract's ceiling on a refusal's age\\_seconds, the largest signed 32-bit integer.\n\n```go\nconst MaxIngressStatusRules = 1024\n```\nMaxIngressStatusRules is the contract's ceiling on the entries of one ingress status report.\n\n```go\nconst MaxIngressStatusTargets = 8\n```\nMaxIngressStatusTargets is the contract's ceiling on the target entries of one rule entry, the most targets a rule holds.\n\n```go\nconst MaxIntegrityViolationsPerBatch = 128\n```\nMaxIntegrityViolationsPerBatch is the contract's per-request ceiling on the violations array. A larger batch is refused whole with 400 integrity\\_violations\\_too\\_many, and an empty one with integrity\\_violations\\_empty.\n\n```go\nconst MaxRelayStatusBoundSeconds = 315360000\n```\nMaxRelayStatusBoundSeconds is the contract's ceiling on bound\\_seconds.\n\n```go\nconst MaxSharedSubnetBridges = 8\n```\nMaxSharedSubnetBridges is the contract's ceiling on the bridges of one shared\\_subnets entry: a carrier and up to seven standbys.\n\n```go\nconst MaxSiteToSiteStatusTunnels = 256\n```\nMaxSiteToSiteStatusTunnels is the contract's ceiling on the entries of one site-to-site status report. A bridge with more tunnels reports the first ones in the order of the pull.\n\n```go\nconst MaxUserAccessStatusProviders = 256\n```\nMaxUserAccessStatusProviders is the contract's ceiling on the entries of one user access status report. A bridge with more providers reports the first ones in the order of the pull.\n\n## Variables\n\n```go\nvar (\n\tErrBadRequest      = \u0026APIError{StatusCode: 400, Message: \"bad request\"}\n\tErrUnauthorized    = \u0026APIError{StatusCode: 401, Message: \"unauthorized\"}\n\tErrForbidden       = \u0026APIError{StatusCode: 403, Message: \"forbidden\"}\n\tErrNotFound        = \u0026APIError{StatusCode: 404, Message: \"not found\"}\n\tErrConflict        = \u0026APIError{StatusCode: 409, Message: \"conflict\"}\n\tErrPayloadTooLarge = \u0026APIError{StatusCode: 413, Message: \"payload too large\"}\n\tErrUnprocessable   = \u0026APIError{StatusCode: 422, Message: \"unprocessable entity\"}\n\tErrRateLimit       = \u0026APIError{StatusCode: 429, Message: \"rate limit exceeded\"}\n\tErrServer          = \u0026APIError{StatusCode: 500, Message: \"server error\"}\n)\n```\nSentinel errors for common HTTP error status codes.\n\n```go\nvar (\n\tErrIntegrityViolationsEmpty   = errors.New(\"integrity violation batch is empty\")\n\tErrIntegrityViolationsTooMany = fmt.Errorf(\"integrity violation batch exceeds %d entries\", MaxIntegrityViolationsPerBatch)\n)\n```\nErrIntegrityViolationsEmpty and ErrIntegrityViolationsTooMany are returned by ReportIntegrityViolations before any HTTP request when the batch is outside the contract's 1..MaxIntegrityViolationsPerBatch bounds.\n\n```go\nvar ErrCredentialRefused = errors.New(\"api: node credential refused by the control plane, requests suspended until a heartbeat is accepted\")\n```\nErrCredentialRefused is returned before any HTTP request by every call that presents the node's bearer credential while the client is marked refused (see ControlPlane.SetCredentialRefused). The heartbeat marks it after the control plane keeps answering 401, which is how a removed Node's agent stops calling at its usual rates. It is deliberately not an \\*APIError: no response was received, so errors.Is(err, ErrUnauthorized) stays false for it.\n\n```go\nvar ErrEndpointCandidatesTooMany = fmt.Errorf(\"endpoint candidate report exceeds %d candidates\", MaxEndpointCandidates)\n```\nErrEndpointCandidatesTooMany is returned by ReportEndpointCandidates before any HTTP request when the report carries more than MaxEndpointCandidates candidates.\n\n```go\nvar ErrHandshakeReportTooMany = fmt.Errorf(\"handshake report exceeds %d peers\", MaxHandshakeReportPeers)\n```\nErrHandshakeReportTooMany is returned by ReportHandshakes before any HTTP request when the report carries more than MaxHandshakeReportPeers peers.\n\n```go\nvar ErrHookNameInvalid = fmt.Errorf(\"hook name is outside the grammar %s\", hookNamePattern)\n```\nErrHookNameInvalid is returned by FetchHookVersion before any HTTP request when the requested hook name is outside the contract's published-hook name grammar.\n\n```go\nvar ErrSSEConnectTimeout = errors.New(\"api: SSE connect timeout\")\n```\nErrSSEConnectTimeout is returned when the SSE request does not reach its response headers within the client's request timeout.\n\n```go\nvar ErrSSEIdleTimeout = errors.New(\"api: SSE idle timeout\")\n```\nErrSSEIdleTimeout is returned when the SSE stream receives no data within the configured idle timeout period.\n\n```go\nvar ErrSecretNameInvalid = fmt.Errorf(\"secret name is outside the grammar %s\", secretNamePattern)\n```\nErrSecretNameInvalid is returned by FetchSecret before any HTTP request when the requested secret name is outside the contract's name grammar.\n\n## Functions\n\n```go\nfunc CanonicalBytes(env Envelope) ([]byte, error)\n```\nCanonicalBytes returns the bytes an envelope's signature covers, as the \"Signed event envelope\" section of plexsphere's agent contract (docs/reference/api/plexd-agent-contract.md) defines them: one JSON object with exactly the members id, issued\\_at, key\\_id, payload, scope and type in that order, no whitespace, and never the signature. issued\\_at is UTC with nine fractional digits, scope is an object rather than the wire string, and the payload is decoded and written again with sorted keys and normalised numbers. An absent or empty Payload is null.\n\nThe frame's data: line is not the signed message: its member order, time format and payload spelling are whatever the control plane's encoder wrote, so the bytes are rebuilt from the decoded values. This is the single canonical-form seam shared by the agent's verifier and the mock control plane, and it mirrors the control plane's own CanonicalBytes (internal/signing/envelope/canonical.go in plexsphere).\n\n```go\nfunc IsEdgePSKNotServed(err error) bool\n```\nIsEdgePSKNotServed reports whether err says the control plane does not serve GET /v1/nodes/{node\\_id}/peers/{peer\\_node\\_id}/psk: a 404 with any code but peer\\_not\\_found, or a 501 carrying the psk\\_delivery\\_not\\_provisioned problem code.\n\nA control plane older than the operation has no route for it, and its router answers 404 with whatever its not-found handler writes, so no code can be required of it. The operation's own 404 is peer\\_not\\_found: the peer has not landed in the Domain yet, the post-registration lag the contract asks the agent to retry on its next reconcile, so it is not a missing surface.\n\n```go\nfunc IsEndpointCandidatesNotServed(err error) bool\n```\nIsEndpointCandidatesNotServed reports whether err says the control plane does not serve PUT /v1/nodes/{node\\_id}/endpoint-candidates: a 404 with any code but endpoint\\_peer\\_not\\_found, or a 501 carrying the endpoint\\_candidates\\_not\\_provisioned problem code.\n\nA control plane older than the operation has no route for it, and its router answers 404 with whatever its not-found handler writes, so no code can be required of it. The operation's own 404 is endpoint\\_peer\\_not\\_found, the first-report race plexsphere/plexsphere#868 documents: the node reports before the control plane has registered it as a peer, and a later cycle heals it, so it is not a missing surface.\n\n```go\nfunc IsEventBusNotProvisioned(err error) bool\n```\nIsEventBusNotProvisioned reports whether err is the control plane's long-term descope of the signed event stream for the node: a 501 carrying the signed\\_event\\_bus\\_not\\_provisioned problem code. Unlike a transient 5xx, this is a durable verdict — the endpoint stays unavailable until the node is re-provisioned — so it is answered by switching to pull-only delivery rather than by retrying against a channel that is not there.\n\n```go\nfunc IsHandshakeReportNotServed(err error) bool\n```\nIsHandshakeReportNotServed reports whether err says the control plane does not serve POST /v1/nodes/{node\\_id}/handshakes: a 404 with any code or none, or a 501 carrying the handshakes\\_not\\_provisioned problem code.\n\nThe two statuses are one condition met on two control-plane generations. A control plane older than the operation has no route for it, and its router answers 404 with whatever body its not-found handler writes, so no code can be required of it. A control plane that has the route but not the recording service wired answers 501 handshakes\\_not\\_provisioned. Either way nothing stores the report until the control plane is upgraded or provisioned, so the reporter says so once and keeps sending on its interval instead of warning on every tick.\n\nTaking every 404 is safe because the operation has none of its own: the contract answers it with 200, 400, 401, 403, 413, 500 or 501, and an entry naming an unknown or deregistered peer is counted as ignored rather than refused. A 501 with another code is a different surface's refusal and stays a failure.\n\n```go\nfunc IsHookMetadataRefused(err error) bool\n```\nIsHookMetadataRefused reports whether err is a refusal of a capability manifest that the short form can answer: a 413 with any code or none, or a 400 carrying the malformed\\_capabilities\\_request, declared\\_hook\\_invalid, declared\\_hooks\\_too\\_many, hook\\_rollout\\_errors\\_too\\_many or hook\\_rollout\\_error\\_invalid problem code.\n\nA control plane refuses a manifest whole, so the reporter answers each of these by dropping the hook metadata, which keeps a failure of the metadata from costing the manifest. The metadata is every declared-hook field past name and checksum, a rolled-out hook's source and version among them, and the hook\\_rollout\\_errors list. A 400 malformed\\_capabilities\\_request comes from a control plane that predates the fields and refuses them as unknown keys. A 400 declared\\_hook\\_invalid, declared\\_hooks\\_too\\_many, hook\\_rollout\\_errors\\_too\\_many or hook\\_rollout\\_error\\_invalid means plexd's copy of the limits has drifted from the control plane's. A 413 means the manifest is over budget. It ignores the code because any layer on the path can say so, and a proxy's own 413 carries no problem code.\n\nEvery other failure says nothing about the metadata and is not classified here. That includes a 400 with another code or none, such as binary\\_checksum\\_invalid, which the short entry would draw again.\n\n```go\nfunc IsIngestNotProvisioned(err error) bool\n```\nIsIngestNotProvisioned reports whether err is the control plane's refusal to accept observability ingest because it is not provisioned for the node: a 501 carrying the observability\\_ingest\\_not\\_provisioned problem code.\n\n```go\nfunc IsIngestPermanentlyRefused(err error) bool\n```\nIsIngestPermanentlyRefused reports whether err is a refusal of an observability ingest batch that no retry can fix: a 400 carrying the ingest\\_batch\\_malformed problem code, which is a verdict on the batch bytes themselves. Re-sending them would draw the identical status forever, so a PlatformReporter drops such a batch rather than returning it for re-buffering.\n\nThe sibling refusals are deliberately not permanent. A 400 ingest\\_sent\\_at\\_invalid faults the X-Plexsphere-Sent-At header, which is re-stamped from the wall clock on every attempt, so it clears once the node's clock converges. A 415 faults the Content-Encoding, a transport property of the deployment rather than of the batch, so it clears once the gateway that rejects gzip is fixed. Both are returned to the caller for re-buffering. A 413 is classified by IsIngestTooLarge and answered by splitting the batch, and a 501 not-provisioned refusal by IsIngestNotProvisioned.\n\n```go\nfunc IsIngestTooLarge(err error) bool\n```\nIsIngestTooLarge reports whether err is the control plane's refusal of an observability ingest batch for exceeding its size limit: a 413. The batch content is acceptable, only its size is not, so the caller answers by splitting the batch and re-sending the halves rather than dropping it.\n\n```go\nfunc IsIngressStatusNotServed(err error) bool\n```\nIsIngressStatusNotServed reports whether err says the control plane does not serve PUT /v1/nodes/{node\\_id}/ingress-status: a 404 with any code but ingress\\_status\\_node\\_gone, or a 501 carrying the ingress\\_status\\_not\\_provisioned problem code.\n\nA control plane older than the operation has no route for it, and its router answers 404 with whatever its not-found handler writes, so no code can be required of it. The operation's own 404 is ingress\\_status\\_node\\_gone: the node was removed while the request ran, a verdict on the node rather than a missing surface.\n\n```go\nfunc IsPolicyStatusNotProvisioned(err error) bool\n```\nIsPolicyStatusNotProvisioned reports whether err is the 501 carrying the policy\\_status\\_not\\_provisioned problem code: the control plane serves PUT /v1/nodes/{node\\_id}/policy-status, but its recording service is not wired, so a later report may be accepted.\n\n```go\nfunc IsPolicyStatusNotServed(err error) bool\n```\nIsPolicyStatusNotServed reports whether err says the control plane has no route for PUT /v1/nodes/{node\\_id}/policy-status: a 404 with any code but policy\\_status\\_node\\_gone.\n\nA control plane older than the operation has no route for it, and its router answers 404 with whatever its not-found handler writes, so no code can be required of it. The operation's own 404 is policy\\_status\\_node\\_gone: the node was removed while the report was in flight. The contract asks the agent to stop reporting until it restarts on any other 404, which is why the 501 of a control plane that serves the route without its recording service is a separate classifier, IsPolicyStatusNotProvisioned.\n\n```go\nfunc IsRelayStatusNotServed(err error) bool\n```\nIsRelayStatusNotServed reports whether err says the control plane does not serve PUT /v1/nodes/{node\\_id}/relay-status: a 404 with any code but relay\\_status\\_node\\_gone, or a 501 carrying the relay\\_status\\_not\\_provisioned problem code.\n\nA control plane older than the operation has no route for it, and its router answers 404 with whatever its not-found handler writes, so no code can be required of it. The operation's own 404 is relay\\_status\\_node\\_gone: the node was removed while the request ran, a verdict on the node rather than a missing surface.\n\n```go\nfunc IsSecretAccessRevoked(err error) bool\n```\nIsSecretAccessRevoked reports whether err is the secret fetch's verdict that the Node may not read the secret: a 403 (no read grant, or a revoked one) or a 404 (no such Secret, or no value at the version read), with any problem code or none. The local-endpoint reporters drop their cached bearer token on it. Every other failure, including a 401, ErrCredentialRefused, a 429 and any 5xx, says nothing about the grant and is not classified here.\n\n```go\nfunc IsSessionRevokedOrExpired(err error) bool\n```\nIsSessionRevokedOrExpired reports whether err is the control plane's verdict that the session a session activity callback names has reached a terminal state: a 409 carrying session\\_already\\_revoked or session\\_expired. Like the not-provisioned refusals this is a durable verdict — neither state goes back to live, so re-sending the callback draws the identical status forever — and the node answers it by settling rather than by retrying.\n\nWhat it settles on is a drain signal, not a teardown. The answer itself never closes a session: the entry leaves the sessions block on a following pull, and the block drain, or a verified session\\_revoked event naming the session, performs the teardown.\n\nA 404 session\\_not\\_found is deliberately not classified here. It is not a terminal state but the sessions block and the session store disagreeing — a lagging read replica, a session record written after the block was rendered, a failover window — and the two are separate reads. The entry standing in the block is the control plane still asking for the session, so the callback stays retryable: settling on the 404 instead would strand a bound listener whose endpoint the control plane never learns, for the whole standing life of its entry.\n\nA 501 access\\_session\\_not\\_provisioned is not classified here either. It faults the callback endpoint rather than the session, and the endpoint may be provisioned mid-session, so it stays retryable too.\n\n```go\nfunc IsSiteToSiteStatusNotServed(err error) bool\n```\nIsSiteToSiteStatusNotServed reports whether err says the control plane does not serve PUT /v1/nodes/{node\\_id}/site-to-site-status: a 404 with any code but site\\_to\\_site\\_status\\_node\\_gone, or a 501 carrying the site\\_to\\_site\\_status\\_not\\_provisioned problem code.\n\nA control plane older than the operation has no route for it, and its router answers 404 with whatever its not-found handler writes, so no code can be required of it. The operation's own 404 is site\\_to\\_site\\_status\\_node\\_gone: the node was removed while the request ran, a verdict on the node rather than a missing surface.\n\n```go\nfunc IsTokenRateLimited(err error) bool\n```\nIsTokenRateLimited reports whether err is the control plane's refusal of a registration by the rate limit of the token's BootstrapToken policy: a 429 carrying the token\\_rate\\_limited problem code.\n\nThe answer is a verdict on the token, not on the caller: the token is valid, the refusal did not count as a redemption, and the same request succeeds once its Retry-After has passed. The per-IP limiter of the same route answers 429 rate\\_limited before any token is looked up, so that 429, and one without a code, is false here.\n\n```go\nfunc IsUserAccessStatusNotServed(err error) bool\n```\nIsUserAccessStatusNotServed reports whether err says the control plane does not serve PUT /v1/nodes/{node\\_id}/user-access-status: a 404 with any code but user\\_access\\_status\\_node\\_gone, or a 501 carrying the user\\_access\\_status\\_not\\_provisioned problem code.\n\nA control plane older than the operation has no route for it, and its router answers 404 with whatever its not-found handler writes, so no code can be required of it. The operation's own 404 is user\\_access\\_status\\_node\\_gone: the node was removed while the request ran, a verdict on the node rather than a missing surface.\n\n```go\nfunc LoadRootCAs(caFile string, logger *slog.Logger) (*x509.CertPool, error)\n```\nLoadRootCAs returns the host's system roots plus the certificates in caFile. An empty caFile returns nil, which a tls.Config reads as the system roots.\n\nThe file is read once, when this is called, and its path is used as given, so a relative one resolves against the working directory. Blocks of the file that are not certificates are skipped, but a file without any certificate is an error: the operator named a CA, and trusting the system roots alone would fail later with an error that does not say why.\n\n```go\nfunc RedactURLError(err error) error\n```\nRedactURLError strips the request URL from a \\*url.Error, keeping only the operation and the underlying cause. url.Error.Error() renders the full URL including its query string, and a presigned upload URL carries its credential there — logging such an error verbatim would publish a live write capability against the object it points at. Errors of any other type pass through.\n\n```go\nfunc SignedMessage(env Envelope) ([]byte, error)\n```\nSignedMessage returns the message an envelope's Ed25519 signature is made over: the 64-byte SHA-512 digest of its CanonicalBytes. The control plane signs the digest, not the canonical bytes themselves, so verifying the bytes directly fails for every envelope.\n\n```go\nfunc ValidHookName(name string) bool\n```\nValidHookName reports whether name is inside the control plane's published-hook name grammar, so it names a hook FetchHookVersion can ask for.\n\n```go\nfunc ValidIngressReason(s string) bool\n```\nValidIngressReason reports whether s is a reason token of an ingress status report: a lowercase letter, then up to 62 lowercase letters, digits and underscores (^\\[a-z]\\[a-z0-9\\_]{0,62}$).\n\n```go\nfunc ValidIngressRuleID(s string) bool\n```\nValidIngressRuleID reports whether s is a UUID in canonical form, groups of 8, 4, 4, 4 and 12 hex digits in either case joined by hyphens, other than the zero UUID: an id the control plane accepts in an ingress status report.\n\n```go\nfunc ValidIngressTargetNodeID(s string) bool\n```\nValidIngressTargetNodeID reports whether s is a node\\_id the control plane accepts in a target entry of an ingress status report: a UUID in canonical form other than the zero UUID, as ValidIngressRuleID.\n\n```go\nfunc ValidSecretName(name string) bool\n```\nValidSecretName reports whether name is inside the control plane's secret-name grammar, so it names a secret FetchSecret can ask for.\n\n```go\nfunc ValidSiteToSiteTunnelID(s string) bool\n```\nValidSiteToSiteTunnelID reports whether s is a UUID in canonical form, in either case, other than the zero UUID: the check of ValidUserAccessProviderID, and the id the control plane accepts in a site-to-site status report.\n\n```go\nfunc ValidUserAccessProviderID(s string) bool\n```\nValidUserAccessProviderID reports whether s is a UUID in canonical form, in either case, other than the zero UUID: the check of ValidIngressRuleID, and the id the control plane accepts in a user access status report.\n\n## Types\n\n```go\ntype APIError struct {\n\tStatusCode int\n\tMessage    string\n\t// Code carries the machine-readable code member of an RFC 9457\n\t// problem+json response. It is empty when the response carries no\n\t// code (or is not a problem+json body).\n\tCode string\n\t// CorrelationID carries the correlation_id member of an RFC 9457\n\t// problem+json response, falling back to the X-Correlation-Id header\n\t// of that same response. Both sources are read only from a response\n\t// that presents itself as a problem document, and that is the whole\n\t// of what the gate buys: a response an intermediary substituted for\n\t// the control plane's contributes no id. It does not authenticate the\n\t// header, so a tracing proxy that passes a genuine problem document\n\t// through and stamps its own X-Correlation-Id on it is read by the\n\t// fallback. It is empty when neither source carries a usable id.\n\tCorrelationID string\n\tRetryAfter    time.Duration // only set for 429\n}\n```\nAPIError is the base error type for HTTP API errors. It supports errors.Is matching by status code and errors.As extraction.\n\n```go\nfunc (e *APIError) Error() string\n```\nError returns the formatted error string. A non-empty CorrelationID is appended as a trailing \" (correlation\\_id=...)\" segment.\n\n```go\nfunc (e *APIError) Is(target error) bool\n```\nIs supports errors.Is matching by status code. ErrServer (500) matches any 5xx status code. All other sentinels require an exact status code match.\n\n```go\ntype ActionInfo struct {\n\tName        string        `json:\"name\"`\n\tDescription string        `json:\"description\"`\n\tParameters  []ActionParam `json:\"parameters,omitempty\"`\n}\n```\n\n```go\ntype ActionParam struct {\n\tName        string `json:\"name\"`\n\tType        string `json:\"type\"`\n\tRequired    bool   `json:\"required\"`\n\tDefault     string `json:\"default,omitempty\"`\n\tDescription string `json:\"description\"`\n}\n```\n\n```go\ntype AuditBatch = []AuditEntry\n```\nAuditBatch is the internal pipeline and local-endpoint payload for a batch of audit entries. The control-plane leg of POST /v1/nodes/{node\\_id}/audit sends AuditEvent instead.\n\n```go\ntype AuditEntry struct {\n\tTimestamp time.Time       `json:\"timestamp\"`\n\tSource    string          `json:\"source\"`\n\tEventType string          `json:\"event_type\"`\n\tSubject   json.RawMessage `json:\"subject\"`\n\tObject    json.RawMessage `json:\"object\"`\n\tAction    string          `json:\"action\"`\n\tResult    string          `json:\"result\"`\n\tHostname  string          `json:\"hostname\"`\n\tRaw       string          `json:\"raw\"`\n}\n```\nAuditEntry is the internal pipeline and local-endpoint format for a single audit record. The control-plane leg sends AuditEvent instead.\n\n```go\ntype AuditEvent struct {\n\tSource    string    `json:\"source\"`\n\tAction    string    `json:\"action\"`\n\tOutcome   string    `json:\"outcome\"`\n\tTimestamp time.Time `json:\"timestamp\"`\n}\n```\nAuditEvent is the control-plane wire format for a single audit record in the body of POST /v1/nodes/{node\\_id}/audit.\n\n```go\ntype BinaryInfo struct {\n\tVersion  string `json:\"version\"`\n\tChecksum string `json:\"checksum\"`\n}\n```\nBinaryInfo describes the running agent binary. It is reported through the node API's local surface; the control plane receives the same two values as the flat binary\\_version / binary\\_checksum fields of a capability manifest.\n\n```go\ntype BridgeInfo struct {\n\tEnabled                 bool   `json:\"enabled\"`\n\tAccessInterface         string `json:\"access_interface\"`\n\tActiveRoutes            int    `json:\"active_routes\"`\n\tRelayEnabled            bool   `json:\"relay_enabled\"`\n\tActiveRelaySessions     int    `json:\"active_relay_sessions\"`\n\tIngressEnabled          bool   `json:\"ingress_enabled\"`\n\tActiveIngressRules      int    `json:\"active_ingress_rules\"`\n\tSiteToSiteEnabled       bool   `json:\"site_to_site_enabled\"`\n\tActiveSiteToSiteTunnels int    `json:\"active_site_to_site_tunnels\"`\n}\n```\nBridgeInfo is the bridge status reported by the node in heartbeats.\n\n```go\ntype BridgeSnapshot struct {\n\tRelay      *RelayConfig      `json:\"relay\"`\n\tUserAccess *UserAccessConfig `json:\"user_access\"`\n\tIngress    *IngressConfig    `json:\"ingress\"`\n\tSiteToSite *SiteToSiteConfig `json:\"site_to_site\"`\n}\n```\nBridgeSnapshot carries the four bridge subtrees. Each child is present-but-nullable; there are no base fields on the wire.\n\n```go\ntype CapabilityManifestRequest struct {\n\t// BinaryVersion is the agent version string, non-empty after trimming.\n\tBinaryVersion string `json:\"binary_version\"`\n\t// BinaryChecksum is the running binary's SHA-256 as 32 raw bytes in\n\t// standard-padded base64 (see integrity.WireChecksum). Anything that does\n\t// not decode to exactly 32 bytes is refused with 400\n\t// binary_checksum_invalid.\n\tBinaryChecksum string `json:\"binary_checksum\"`\n\t// SSHHostKeyFingerprint is the optional OpenSSH host-key fingerprint in the\n\t// canonical `SHA256:\u003cbase64\u003e` form. Omitted when the agent has none.\n\tSSHHostKeyFingerprint string `json:\"ssh_host_key_fingerprint,omitempty\"`\n\t// DeclaredHooks are the hooks the agent advertises, at most 128, with\n\t// unique names. Omitted when empty rather than sent as null.\n\tDeclaredHooks []DeclaredHook `json:\"declared_hooks,omitempty\"`\n\t// PlexdHooks are the PlexdHook resources the agent found in its\n\t// ServiceAccount's namespace, at most 128, with unique names. The agent\n\t// reports the list again when those resources change. Omitted when the\n\t// agent runs outside a cluster or found nothing it can report, rather than\n\t// sent as null, and a missing key means none: every PUT replaces the stored\n\t// list whole.\n\tPlexdHooks []DiscoveredPlexdHook `json:\"plexd_hooks,omitempty\"`\n\t// BuiltinActions is the inventory of builtin actions the agent implements,\n\t// sorted by name, each with its parameters in registration order. Omitted\n\t// when empty rather than sent as null.\n\tBuiltinActions []ActionInfo `json:\"builtin_actions,omitempty\"`\n\t// HookRolloutErrors are the published hook versions the node's last pull\n\t// listed and the node could not install, at most MaxHookRolloutErrors.\n\t// Omitted when nil rather than sent as null. The control plane stores an\n\t// absent list as [], because every PUT replaces the whole snapshot, so the\n\t// node clears an error by leaving it out. More than MaxHookRolloutErrors\n\t// entries answer 400 hook_rollout_errors_too_many, and an entry that breaks\n\t// a limit 400 hook_rollout_error_invalid.\n\tHookRolloutErrors []HookRolloutError `json:\"hook_rollout_errors,omitempty\"`\n}\n```\nCapabilityManifestRequest is the body of PUT /v1/nodes/{node\\_id}/capabilities: the agent's binary version and digest, the hooks it advertises, and two inventories of what it can run: the builtin actions it implements and the PlexdHook resources it discovered in its cluster.\n\nThe handler decodes it with DisallowUnknownFields, so this struct carries the contract's fields and nothing else. A manifest is refused whole, so one inventory entry that breaks an invariant (422) costs the binary version and checksum with it. The agent therefore sends only entries the contract accepts: at most 128 per inventory, unique names, at most 64 parameters per action, and a canonical image digest on every PlexdHook.\n\nA declared hook's metadata has limits of its own: a description and each parameter text field at most 4096 characters, at most 64 parameters per hook, timeout\\_seconds 0 to 86400, sandbox\\_level at most 64 characters, and no NUL in any of them. Characters are Unicode code points. Those violations answer 400, not 422: declared\\_hooks\\_too\\_many past 64 parameters and declared\\_hook\\_invalid otherwise. A control plane that predates the fields refuses them with 400 malformed\\_capabilities\\_request.\n\n```go\ntype Clock interface {\n\tNow() time.Time\n\tAfter(d time.Duration) \u003c-chan time.Time\n}\n```\nClock abstracts time operations for testing.\n\n```go\ntype Config struct {\n\t// BaseURL is the control plane API base URL (required).\n\t// Example: \"https://api.plexsphere.com\"\n\tBaseURL string `yaml:\"base_url\"`\n\n\t// TLSInsecureSkipVerify disables TLS certificate verification.\n\t// WARNING: Only use for development/testing.\n\tTLSInsecureSkipVerify bool `yaml:\"tls_insecure_skip_verify\"`\n\n\t// TLSCAFile names a PEM file whose certificates the client trusts for the\n\t// control plane in addition to the host's system roots, so a control plane\n\t// behind a private CA needs neither that CA in the host's trust store nor\n\t// disabled verification. NewControlPlane reads it once. Empty means the\n\t// system roots alone.\n\tTLSCAFile string `yaml:\"tls_ca_file\"`\n\n\t// ConnectTimeout is the maximum time to wait for a TCP connection.\n\t// Default: 10s\n\tConnectTimeout time.Duration `yaml:\"connect_timeout\"`\n\n\t// RequestTimeout is the maximum time for a complete HTTP request/response cycle.\n\t// Default: 30s\n\tRequestTimeout time.Duration `yaml:\"request_timeout\"`\n\n\t// SSEIdleTimeout is the maximum time to wait for any data on the SSE stream\n\t// before considering the connection stale and reconnecting.\n\t// Default: 90s\n\tSSEIdleTimeout time.Duration `yaml:\"sse_idle_timeout\"`\n\n\t// SSEReprobeInterval is how often pull-only delivery re-probes the SSE\n\t// endpoint after the control plane descoped it.\n\t// Default: 10m\n\tSSEReprobeInterval time.Duration `yaml:\"sse_reprobe_interval\"`\n}\n```\nConfig holds the configuration for the ControlPlane client. Config is passed as a constructor argument: this package reads no configuration file, and the only files it opens are the CA bundles that LoadRootCAs reads.\n\n```go\nfunc (c *Config) ApplyDefaults()\n```\nApplyDefaults sets default values for zero-valued fields.\n\n```go\nfunc (c *Config) Validate() error\n```\nValidate checks that required fields are set.\n\n```go\ntype ConnectFunc func(ctx context.Context) error\n```\nConnectFunc is called to establish an SSE connection. It should block while the connection is active and return when it drops.\n\n```go\ntype ControlPlane struct {\n\t// contains filtered or unexported fields\n}\n```\nControlPlane is the client for the Plexsphere control plane API.\n\n```go\nfunc NewControlPlane(cfg Config, version string, logger *slog.Logger) (*ControlPlane, error)\n```\nNewControlPlane creates a new ControlPlane client with the given configuration.\n\n```go\nfunc (c *ControlPlane) ConnectSSE(ctx context.Context, nodeID, lastEventID string) (*http.Response, error)\n```\nConnectSSE opens an SSE connection to the node event stream. The caller is responsible for closing the response body.\n\nThe request timeout bounds only the setup: the wait for the response headers and, on a non-2xx answer, the read of its problem body. Headers that do not arrive in time fail with ErrSSEConnectTimeout; a problem body that stalls still yields the status as an \\*APIError, without whatever part of the body did not arrive. Once the stream is open, the request timeout no longer applies, and SSEStream bounds a silent stream with its idle timeout. GET /v1/nodes/{node\\_id}/events\n\n```go\nfunc (c *ControlPlane) CredentialRefused() bool\n```\nCredentialRefused reports whether the credential is currently marked refused.\n\n```go\nfunc (c *ControlPlane) DeleteStateReport(ctx context.Context, nodeID, key string) error\n```\nDeleteStateReport removes a single per-key node state report. A 204 No Content returns nil; a 404 report\\_not\\_found (and any other non-2xx status) surfaces as an \\*APIError through errorFromResponse. DELETE /v1/nodes/{node\\_id}/state/reports/{key}\n\n```go\nfunc (c *ControlPlane) ExecutionCallback(ctx context.Context, nodeID, executionID string, req ExecutionCallbackRequest) (*ExecutionCallbackResponse, error)\n```\nExecutionCallback posts a single execution lifecycle callback and returns the server's new invocation status, plus a presigned output upload URL when the callback declares an over-ceiling output. POST /v1/nodes/{node\\_id}/executions/{execution\\_id}\n\n```go\nfunc (c *ControlPlane) FetchEdgePSK(ctx context.Context, nodeID, peerNodeID string) (*EdgePSKEnvelope, error)\n```\nFetchEdgePSK retrieves the pairwise WireGuard PSK for the edge between the node and peerNodeID as the raw envelope the control plane seals under the node's NSK. The body must be exactly EdgePSKEnvelopeSize bytes, and both the X-Plexsphere-PSK-KID and X-Plexsphere-PSK-Epoch headers must be present: the epoch is part of the additional authenticated data the envelope is opened with. A non-2xx answer returns the \\*APIError the problem body describes.\n\nThe body is key material, so no error this returns quotes it. GET /v1/nodes/{node\\_id}/peers/{peer\\_node\\_id}/psk\n\n```go\nfunc (c *ControlPlane) FetchHookVersion(ctx context.Context, nodeID, name string, version int) (*NodeHookVersion, error)\n```\nFetchHookVersion retrieves one published hook version as the control plane serves it: the signed hook\\_version envelope and the script in standard base64. It refuses a name outside the grammar and a version below 1 before any request, and a non-2xx answer returns the \\*APIError the problem body describes, such as 404 hook\\_not\\_assigned or 503 signing\\_unavailable.\n\nIt verifies nothing. The envelope names a key the caller has to hold, and the script has to match the checksum of the pull entry that listed the version, both of which only the caller knows, so verification is the installer's job. GET /v1/nodes/{node\\_id}/hooks/{name}/versions/{version}\n\n```go\nfunc (c *ControlPlane) FetchSecret(ctx context.Context, nodeID, name string, version int) (*SecretEnvelope, error)\n```\nFetchSecret retrieves a specific secret for the node as the raw AES-256-GCM envelope served by the control plane: the octet-stream body carries \\\u003c12-byte nonce\u003e || \\\u003cciphertext + 16-byte GCM tag\u003e, and the version and KID ride in the X-Plexsphere-Secret-Version and X-Plexsphere-Secret-KID headers. A version \u003e 0 selects an older version via ?version=N; version == 0 is the current version. GET /v1/nodes/{node\\_id}/secrets/{name}\n\n```go\nfunc (c *ControlPlane) FetchState(ctx context.Context, nodeID string) (*NodeStateSnapshot, error)\n```\nFetchState retrieves the desired-state snapshot for a node. GET /v1/nodes/{node\\_id}/state\n\n```go\nfunc (c *ControlPlane) GetJSON(ctx context.Context, path string, result any) error\n```\nGetJSON sends a GET request and decodes the JSON response.\n\n```go\nfunc (c *ControlPlane) Heartbeat(ctx context.Context, nodeID string, req HeartbeatRequest) (*HeartbeatResponse, error)\n```\nHeartbeat sends a heartbeat to the control plane. POST /v1/nodes/{node\\_id}/heartbeat\n\nThe heartbeat is never stopped by the refused-credential gate: it is the probe whose acceptance clears the mark (see SetCredentialRefused).\n\n```go\nfunc (c *ControlPlane) OpenSessionConnection(ctx context.Context, nodeID, sessionID, connectionID string) (net.Conn, error)\n```\nOpenSessionConnection opens the connection a session\\_connect event asked for: a WebSocket, authenticated with the node's bearer, whose binary messages carry the ssh session's SSH bytes in both directions. A refused upgrade comes back as an \\*APIError with the status and the problem code, such as 404 session\\_connection\\_not\\_found once the request expired or 409 session\\_not\\_active for a session that ended. ctx bounds the handshake only; the returned connection lives until Close. Read returns only the payload of binary messages: pings are answered inside it, a normal close reads as io.EOF, and a text message closes the connection and fails the read. GET /v1/nodes/{node\\_id}/sessions/{session\\_id}/connections/{connection\\_id}\n\nDECISION: the handshake goes over the API client's own transport, so the connection reaches the control plane the way every other call does, with the same TLS settings, connect timeout and base URL. That transport sets its own TLSClientConfig without ForceAttemptHTTP2 and so speaks HTTP/1.1, which the WebSocket upgrade needs. The handshake context does not bound the connection, which lives as long as a client stays attached to the session.\n\n```go\nfunc (c *ControlPlane) PostJSON(ctx context.Context, path string, body any, result any) error\n```\nPostJSON sends a POST request with a JSON body and decodes the JSON response.\n\n```go\nfunc (c *ControlPlane) PutStateReport(ctx context.Context, nodeID, key string, req NodeStateReportRequest) (*NodeStateReportResponse, error)\n```\nPutStateReport publishes a single per-key node state report and returns the server's acknowledgement. PUT /v1/nodes/{node\\_id}/state/reports/{key}\n\n```go\nfunc (c *ControlPlane) Register(ctx context.Context, req RegisterRequest) (*RegisterResponse, error)\n```\nRegister sends a registration request to the control plane. POST /v1/register is security: \\[] — the bootstrap token travels in the body, so the request never carries the shared bearer token even if one is set.\n\n```go\nfunc (c *ControlPlane) ReportAudit(ctx context.Context, nodeID string, events []AuditEvent) (*IngestReceipt, error)\n```\nReportAudit posts a batch of audit events to the platform ingest endpoint as NDJSON (one JSON object per line) and returns the 202 ingest receipt. POST /v1/nodes/{node\\_id}/audit\n\n```go\nfunc (c *ControlPlane) ReportEndpoint(ctx context.Context, nodeID string, req EndpointRequest) (*EndpointResponse, error)\n```\nReportEndpoint reports the node's NAT endpoint information. PUT /v1/nodes/{node\\_id}/endpoint\n\n```go\nfunc (c *ControlPlane) ReportEndpointCandidates(ctx context.Context, nodeID string, req EndpointCandidatesRequest) (*EndpointCandidatesResponse, error)\n```\nReportEndpointCandidates reports the node's local endpoint candidates, which replace every candidate it reported before, and returns the control plane's receipt.\n\nA nil Candidates is sent as an empty array: the contract refuses a null candidates with 400 malformed\\_endpoint\\_candidates, while an empty array withdraws the earlier set. The substitution is made on a copy, so the caller's request is left as passed. A report over MaxEndpointCandidates is refused here, before any request, as ReportHandshakes refuses an oversized report. PUT /v1/nodes/{node\\_id}/endpoint-candidates\n\n```go\nfunc (c *ControlPlane) ReportHandshakes(ctx context.Context, nodeID string, req HandshakeReportRequest) (*HandshakeReportResponse, error)\n```\nReportHandshakes reports the age of the latest WireGuard handshake with each mesh peer and the endpoint WireGuard used for it, and returns the control plane's receipt.\n\nA nil Peers is sent as an empty array: the contract answers a null peers with 400 malformed\\_handshake\\_report, while an empty array is a valid report that records nothing. The substitution is made on a copy, so the caller's request is left as passed.\n\nThe peer ceiling is checked here rather than left to the server, as ReportIntegrityViolations does for its bounds: an oversized report is refused whole, so sending it would cost every edge it carries. POST /v1/nodes/{node\\_id}/handshakes\n\n```go\nfunc (c *ControlPlane) ReportIngressStatus(ctx context.Context, nodeID string, req IngressStatusRequest) (*IngressStatusResponse, error)\n```\nReportIngressStatus reports whether the bridge's local configuration serves public ingress, and the state of each ingress rule, and returns the control plane's receipt.\n\nIt validates nothing and sends the request as passed: the ingress status reporter builds only the shapes the contract admits, and the control plane refuses any other with 400 malformed\\_ingress\\_status or invalid\\_ingress\\_status. PUT /v1/nodes/{node\\_id}/ingress-status\n\n```go\nfunc (c *ControlPlane) ReportIntegrityViolations(ctx context.Context, nodeID string, req IntegrityViolationsRequest) error\n```\nReportIntegrityViolations reports a batch of integrity violations to the control plane. The 200 response carries a commit timestamp and an echo of the batch size; the agent keeps no replay queue to reconcile them against, so the body is not decoded and a non-2xx surfaces as an \\*APIError.\n\nThe batch bounds are checked here rather than left to the server: the two codes it answers with (integrity\\_violations\\_empty, integrity\\_violations\\_too\\_many) describe a caller mistake, and a refused request would take every violation in it down. POST /v1/nodes/{node\\_id}/integrity-violations\n\n```go\nfunc (c *ControlPlane) ReportLogs(ctx context.Context, nodeID string, lines []LogLine) (*IngestReceipt, error)\n```\nReportLogs posts a batch of log lines to the platform ingest endpoint as NDJSON (one JSON object per line) and returns the 202 ingest receipt. POST /v1/nodes/{node\\_id}/logs\n\n```go\nfunc (c *ControlPlane) ReportMetrics(ctx context.Context, nodeID string, samples []MetricSample) (*IngestReceipt, error)\n```\nReportMetrics posts a batch of metric samples to the platform ingest endpoint as a JSON array and returns the 202 ingest receipt. POST /v1/nodes/{node\\_id}/metrics\n\n```go\nfunc (c *ControlPlane) ReportPolicyStatus(ctx context.Context, nodeID string, req PolicyStatusRequest) (*PolicyStatusResponse, error)\n```\nReportPolicyStatus reports what the node did with the policy block of its pulls and returns the control plane's receipt.\n\nThe contract refuses a null revisions list, so a nil Revisions in Applied or Rejected is sent as \\[], on a copy: the caller's request is left as passed. It validates nothing else: the policy status reporter builds only the shapes the contract admits, and the control plane refuses any other with 400 invalid\\_policy\\_status or malformed\\_policy\\_status. PUT /v1/nodes/{node\\_id}/policy-status\n\n```go\nfunc (c *ControlPlane) ReportRelayStatus(ctx context.Context, nodeID string, req RelayStatusRequest) (*RelayStatusResponse, error)\n```\nReportRelayStatus reports the state of the bridge's relay and returns the control plane's receipt.\n\nIt validates nothing and sends the request as passed: the agent's request builder produces only the shapes the contract admits, and the control plane refuses any other with 400 invalid\\_relay\\_status or malformed\\_relay\\_status. PUT /v1/nodes/{node\\_id}/relay-status\n\n```go\nfunc (c *ControlPlane) ReportSessionActivity(ctx context.Context, nodeID, sessionID string, req SessionActivityRequest) error\n```\nReportSessionActivity posts a one-of session activity record (ssh, k8s, or tcp). Success is 204 No Content. POST /v1/nodes/{node\\_id}/sessions/{session\\_id}\n\n```go\nfunc (c *ControlPlane) ReportSiteToSiteStatus(ctx context.Context, nodeID string, req SiteToSiteStatusRequest) (*SiteToSiteStatusResponse, error)\n```\nReportSiteToSiteStatus reports whether the bridge's local configuration serves site-to-site tunnels, and whether each tunnel of its pull is up and answered by its remote site, and returns the control plane's receipt.\n\nIt validates nothing and sends the request as passed: the site-to-site status reporter builds only the shapes the contract admits, and the control plane refuses any other with 400 malformed\\_site\\_to\\_site\\_status or invalid\\_site\\_to\\_site\\_status. PUT /v1/nodes/{node\\_id}/site-to-site-status\n\n```go\nfunc (c *ControlPlane) ReportUserAccessStatus(ctx context.Context, nodeID string, req UserAccessStatusRequest) (*UserAccessStatusResponse, error)\n```\nReportUserAccessStatus reports whether the bridge's local configuration serves user access, and whether each user access provider of its pull is up, and returns the control plane's receipt.\n\nIt validates nothing and sends the request as passed: the user access status reporter builds only the shapes the contract admits, and the control plane refuses any other with 400 malformed\\_user\\_access\\_status or invalid\\_user\\_access\\_status. PUT /v1/nodes/{node\\_id}/user-access-status\n\n```go\nfunc (c *ControlPlane) RotateKeys(ctx context.Context, req KeyRotateRequest) (*KeyRotateResponse, error)\n```\nRotateKeys completes a pending mesh-key rotation; the server identifies the node from the NSK bearer credential. POST /v1/keys/rotate\n\n```go\nfunc (c *ControlPlane) SetAuthToken(token string)\n```\nSetAuthToken sets the bearer token used for API authentication.\n\n```go\nfunc (c *ControlPlane) SetCredentialRefused(refused bool)\n```\nSetCredentialRefused marks the node's credential as refused by the control plane, or clears that mark. While it is set, every request that would present the bearer fails with ErrCredentialRefused before any I/O, so a removed Node stops calling the control plane. Two requests are exempt: POST /v1/register, which carries no bearer, and the heartbeat, which is the probe that decides when the mark is cleared again.\n\n```go\nfunc (c *ControlPlane) UpdateCapabilities(ctx context.Context, nodeID string, caps CapabilityManifestRequest) error\n```\nUpdateCapabilities publishes the node's capability manifest. PUT /v1/nodes/{node\\_id}/capabilities\n\n```go\nfunc (c *ControlPlane) UploadExecutionOutput(ctx context.Context, uploadURL string, output []byte) error\n```\nUploadExecutionOutput PUTs an over-ceiling execution output to a presigned URL. Presigned URLs carry their own authentication, so this request sends neither the bearer token nor gzip encoding; it uploads the raw bytes with a Content-Type of application/octet-stream.\n\nThe upload URL comes from the control plane, and captured action output routinely contains configuration and credentials, so the transport is pinned twice over: the URL may not be less secure than the configured control-plane base URL (an https control plane can never downgrade an upload to http), and redirects are not followed — a 3xx is surfaced as an error rather than re-sending the body to whatever host the redirect names.\n\n```go\ntype DataEntry struct {\n\tKey         string          `json:\"key\"`\n\tContentType string          `json:\"content_type\"`\n\tPayload     json.RawMessage `json:\"payload\"`\n\tVersion     int             `json:\"version\"`\n\tUpdatedAt   time.Time       `json:\"updated_at\"`\n}\n```\n\n```go\ntype DeclaredHook struct {\n\tName string `json:\"name\"`\n\t// Checksum is the hook payload's SHA-256 as 32 raw bytes in\n\t// standard-padded base64, same encoding as BinaryChecksum.\n\tChecksum string `json:\"checksum\"`\n\t// Description says what the hook does, at most 4096 characters. Omitted\n\t// when the sidecar declares none.\n\tDescription string `json:\"description,omitempty\"`\n\t// Parameters are the parameters the hook expects, in sidecar order, at most\n\t// 64. Each name is non-empty after trimming and unique within the hook.\n\t// Omitted when empty rather than sent as null.\n\tParameters []ActionParam `json:\"parameters,omitempty\"`\n\t// TimeoutSeconds is the timeout the sidecar declares, in whole seconds from\n\t// 0 to 86400. 0 means none declared, and the key stays off the wire.\n\tTimeoutSeconds int64 `json:\"timeout_seconds,omitempty\"`\n\t// SandboxLevel is the sandbox level the sidecar declares, at most 64\n\t// characters. The contract keeps it free-form. Omitted when the sidecar\n\t// declares none.\n\tSandboxLevel string `json:\"sandbox_level,omitempty\"`\n\t// Source is HookSourceRollout for a script installed from a published\n\t// version. It is empty, and the key stays off the wire, for a hook placed\n\t// on the node by other means: the contract reads an absent source as\n\t// local, so a node with no rolled-out hook sends the manifest it sent\n\t// before rollouts existed. The contract also accepts HookSourceLocal, and\n\t// answers any value other than those two with 400 declared_hook_invalid.\n\tSource string `json:\"source,omitempty\"`\n\t// Version is the published version installed, 1 to 2147483647. It is\n\t// required with Source HookSourceRollout and refused on any other entry,\n\t// both with 400 declared_hook_invalid, so it is zero, and off the wire,\n\t// for every other entry.\n\tVersion int `json:\"version,omitempty\"`\n}\n```\nDeclaredHook is one hook the agent advertises. Its name and the digest of its payload let the integrity correlator see a hook change without re-fetching it. The four fields after them come from the hook's sidecar and describe the hook for an operator. They gate nothing at the control plane and sit outside its digest, so a sidecar edit changes them and leaves Checksum alone. plexd applies the sidecar's timeout and sandbox when it runs the hook. Source and Version, last, mark a hook a rollout installed and name its version. The control plane then takes that version's published checksum as the hook's baseline, so a rolled-out hook is never trusted on first use.\n\n```go\ntype DeliveryMode string\n```\nDeliveryMode identifies which channel currently delivers control-plane state.\n\n```go\nconst (\n\t// DeliveryModeStreaming means the SSE event stream is the live channel.\n\tDeliveryModeStreaming DeliveryMode = \"streaming\"\n\t// DeliveryModePullOnly means the event stream is descoped and the\n\t// reconciler's own loop is the only delivery channel; SSE is re-probed at\n\t// a low cadence to detect its return.\n\tDeliveryModePullOnly DeliveryMode = \"pull_only\"\n\t// DeliveryModeDegradedPolling means SSE has been failing transiently long\n\t// enough that the legacy polling fallback is driving state.\n\tDeliveryModeDegradedPolling DeliveryMode = \"degraded_polling\"\n)\n```\n\n```go\ntype DiscoveredPlexdHook struct {\n\t// Name is the resource name, unique within the namespace it was listed in.\n\tName string `json:\"name\"`\n\t// ImageDigest is the hook image's digest in canonical\n\t// `sha256:\u003c64 lowercase hex\u003e` form.\n\tImageDigest string `json:\"image_digest\"`\n\t// Parameters is the spec's name/value list folded into a map.\n\tParameters map[string]string `json:\"parameters,omitempty\"`\n\t// TimeoutSeconds is the execution timeout. The CRD has no timeout field,\n\t// so the agent never sets it and the key stays off the wire.\n\tTimeoutSeconds int64 `json:\"timeout_seconds,omitempty\"`\n\t// Sandbox reports that the hook runs sandboxed: a read-only root\n\t// filesystem with every capability dropped, which is how the controller\n\t// runs any hook that is not privileged.\n\tSandbox bool `json:\"sandbox,omitempty\"`\n}\n```\nDiscoveredPlexdHook is one PlexdHook resource as the manifest reports it (the contract's PlexdHook schema). It identifies the hook by its image digest rather than a payload checksum, so only a digest-pinned image can be reported.\n\n```go\ntype Ed25519Verifier struct {\n\t// contains filtered or unexported fields\n}\n```\nEd25519Verifier verifies Envelope signatures using Ed25519 keys selected by key id. It supports rotation by holding a current key and an optional previous key that stays accepted until a transition deadline.\n\n```go\nfunc NewEd25519Verifier(keyID string, key ed25519.PublicKey) *Ed25519Verifier\n```\nNewEd25519Verifier returns a new verifier that accepts envelopes signed with the given key and carrying the given key id.\n\n```go\nfunc (v *Ed25519Verifier) Install(key NodeStateSigningKey) (bool, error)\n```\nInstall makes the signing key a state pull carried the current key. It reports whether anything changed: a key whose id and bytes both equal the current pair is a no-op that leaves a rotation's grace entry alone, while any other key replaces the current one and drops the grace entry, because the node trusts exactly one key of its Domain. Comparing the bytes as well as the id is what lets a pull repair a pair persisted torn. On any error the installed keys are left unchanged.\n\n```go\nfunc (v *Ed25519Verifier) Rotate(rot SigningKeyRotation) error\n```\nRotate installs a new current signing key from a signing\\_key\\_rotated event. The previous key is retained as a grace entry only when the rotation names a previous key id the verifier currently holds and a non-zero transition deadline; otherwise no grace entry is kept. On any error the installed keys are left unchanged.\n\n```go\nfunc (v *Ed25519Verifier) TrustedKeys(now time.Time) []ed25519.PublicKey\n```\nTrustedKeys returns the signing keys a session token may be signed with at now: the current key, plus the previous key while its rotation grace window is open. The slice is fresh on every call, so a caller may keep it. It is what tunnel.SigningKeySource asks for.\n\n```go\nfunc (v *Ed25519Verifier) Verify(_ context.Context, env Envelope) error\n```\nVerify checks the freshness and Ed25519 signature of an event envelope. It refuses an envelope without issued\\_at, one issued more than DefaultStalenessWindow ago, and one issued more than that window ahead of now, and then checks the signature with VerifySignature.\n\n```go\nfunc (v *Ed25519Verifier) VerifySignature(env Envelope) error\n```\nVerifySignature checks an envelope's Ed25519 signature and leaves issued\\_at alone. It selects the verifying key by the envelope's key id, honouring the rotation grace window for the previous key, and checks the signature over SignedMessage, the SHA-512 digest of the envelope's canonical bytes.\n\nA hook\\_version envelope needs this without Verify's freshness window: its issued\\_at is the instant the version was signed, often days before the node fetches it, so Verify would refuse every one as stale. issued\\_at is still part of the canonical bytes, so a changed value fails the signature. What keeps an old version from being installed is the pull, which names the version and the script's checksum the installer has to find.\n\n```go\ntype EdgePSKEnvelope struct {\n\tData  []byte\n\tKID   string\n\tEpoch string\n}\n```\nEdgePSKEnvelope is the pairwise WireGuard PSK for one edge as GET /v1/nodes/{id}/peers/{peer\\_node\\_id}/psk serves it, sealed under the calling node's NSK: Data is \\\u003c12-byte nonce\u003e || \\\u003c32-byte PSK + 16-byte GCM tag\u003e, KID and Epoch come from the X-Plexsphere-PSK-KID and X-Plexsphere-PSK-Epoch headers. Epoch is part of the envelope's additional authenticated data and is used verbatim to open it. Data is key material and is never logged.\n\n```go\ntype EndpointCandidatesRequest struct {\n\t// Candidates holds 0 to MaxEndpointCandidates distinct host:port strings,\n\t// an IPv6 host in brackets and without a zone. A null array is refused,\n\t// so ReportEndpointCandidates sends nil as [].\n\tCandidates []string `json:\"candidates\"` // never null on the wire\n\t// ReportedAt must lie within 60 seconds of server time, or the report is\n\t// refused with 400 endpoint_clock_skew.\n\tReportedAt time.Time `json:\"reported_at\"`\n}\n```\nEndpointCandidatesRequest is the body of PUT /v1/nodes/{node\\_id}/endpoint-candidates: the node's local interface addresses joined with its WireGuard listen port. Each report replaces the previous set, so an empty Candidates withdraws every earlier candidate.\n\n```go\ntype EndpointCandidatesResponse struct {\n\tAcceptedAt time.Time `json:\"accepted_at\"`\n\t// StaleAfter is the deadline after which the control plane drops the set.\n\tStaleAfter time.Time `json:\"stale_after\"`\n}\n```\nEndpointCandidatesResponse is the 200 body of PUT /v1/nodes/{node\\_id}/endpoint-candidates.\n\n```go\ntype EndpointRequest struct {\n\tEndpoint string `json:\"endpoint\"`\n\tNATType  string `json:\"nat_type\"`\n\t// PortMapping is \"preserved\" or \"translated\": whether the NAT kept the\n\t// STUN probe's source port, and so whether Endpoint was observed or\n\t// assumed. Omitted when empty. A control plane that predates the member\n\t// refuses it with 400 malformed_endpoint_request.\n\tPortMapping string    `json:\"port_mapping,omitempty\"`\n\tReportedAt  time.Time `json:\"reported_at\"`\n}\n```\n\n```go\ntype EndpointResponse struct {\n\tAcceptedAt time.Time `json:\"accepted_at\"`\n\tStaleAfter time.Time `json:\"stale_after\"`\n}\n```\n\n```go\ntype Envelope struct {\n\tID        string          `json:\"id\"`\n\tType      string          `json:\"type\"`\n\tScope     string          `json:\"scope\"`\n\tKeyID     string          `json:\"key_id\"`\n\tIssuedAt  time.Time       `json:\"issued_at\"`\n\tPayload   json.RawMessage `json:\"payload\"`\n\tSignature string          `json:\"signature\"`\n}\n```\nEnvelope is the wire format for signed events the control plane streams over SSE. It matches the control plane's OpenAPI v1 events contract.\n\n```go\nfunc ParseEnvelope(data []byte) (Envelope, error)\n```\nParseEnvelope unmarshals data into an Envelope and validates required fields.\n\n```go\ntype EventDispatcher struct {\n\t// contains filtered or unexported fields\n}\n```\nEventDispatcher routes verified events to registered handlers by event type.\n\n```go\nfunc NewEventDispatcher(logger *slog.Logger) *EventDispatcher\n```\nNewEventDispatcher creates a new EventDispatcher.\n\n```go\nfunc (d *EventDispatcher) Dispatch(ctx context.Context, envelope Envelope)\n```\nDispatch invokes all handlers registered for the event's type. Handler errors are logged but do not stop processing of subsequent handlers. Events with no registered handler are logged at debug level and discarded.\n\n```go\nfunc (d *EventDispatcher) Register(eventType string, handler EventHandler)\n```\nRegister adds a handler for the given event type. Multiple handlers can be registered for the same event type.\n\n```go\ntype EventHandler func(ctx context.Context, envelope Envelope) error\n```\nEventHandler is a function that handles a verified SSE event.\n\n```go\ntype EventVerifier interface {\n\tVerify(ctx context.Context, envelope Envelope) error\n}\n```\nEventVerifier verifies the signature of an Envelope.\n\n```go\ntype ExecutionCallbackRequest struct {\n\tStatus              string           `json:\"status\"`\n\tExitCode            *int             `json:\"exit_code,omitempty\"`\n\tError               string           `json:\"error,omitempty\"`\n\tDeclaredOutputBytes int64            `json:\"declared_output_bytes,omitempty\"`\n\tOutput              *ExecutionOutput `json:\"output,omitempty\"`\n}\n```\nExecutionCallbackRequest is the single callback a node posts to POST /v1/nodes/{node\\_id}/executions/{execution\\_id} to advance an execution through its lifecycle. Status is one of the ExecutionStatus\\* values. ExitCode is a pointer so a terminal callback can report an explicit zero. Error is set on failed terminals. DeclaredOutputBytes is the byte length of the captured output; a declaration over the 16 KiB inline ceiling drives the presign mint.\n\n```go\ntype ExecutionCallbackResponse struct {\n\tStatus          string `json:\"status\"`\n\tOutputUploadURL string `json:\"output_upload_url,omitempty\"`\n}\n```\nExecutionCallbackResponse is the 200 response to an execution callback. Status is the new invocation status. OutputUploadURL is a presigned PUT URL present only on the first callback that declares an over-ceiling output; the node derives the object key from the URL path and uploads the bytes there.\n\n```go\ntype ExecutionOutput struct {\n\tInline    string `json:\"inline,omitempty\"`\n\tObjectKey string `json:\"object_key,omitempty\"`\n\tSHA256    string `json:\"sha256,omitempty\"`\n}\n```\nExecutionOutput carries an execution's captured output on a terminal callback. Inline is the base64-encoded output body and is used only when it is at most 16 KiB. ObjectKey and SHA256 describe an already-uploaded over-ceiling output: ObjectKey is the object-store key and SHA256 is the lowercase-hex SHA-256 of the uploaded bytes.\n\n```go\ntype FailureAction int\n```\nFailureAction indicates how the reconnect engine should handle a failure.\n\n```go\nconst (\n\t// RetryTransient means use exponential backoff (network errors, 5xx).\n\tRetryTransient FailureAction = iota\n\t// RetryAuth means the control plane refused the node credential: a 401,\n\t// or ErrCredentialRefused from the client's gate. Registration stops on\n\t// it; the reconnect engine backs off as on RetryTransient, so the stream\n\t// returns once the credential is accepted again.\n\tRetryAuth\n\t// RespectServer means use the server-provided Retry-After delay (429).\n\tRespectServer\n\t// PermanentFailure means stop reconnection entirely (403, 404).\n\tPermanentFailure\n\t// RetryDescoped means the endpoint is descoped long-term (a 501\n\t// signed_event_bus_not_provisioned) — switch to pull-only delivery\n\t// immediately, with no backoff, rather than retrying a channel that is\n\t// not there.\n\tRetryDescoped\n)\n```\n\n```go\nfunc ClassifyError(err error) FailureAction\n```\nClassifyError determines the appropriate reconnection action for an error.\n\n```go\ntype HandshakeReportPeer struct {\n\t// PeerNodeID is the peer's node_id, a non-zero UUID that no other entry of\n\t// the report repeats. An id the control plane does not know as a live peer\n\t// of the node's Domain is counted as ignored rather than refused.\n\tPeerNodeID string `json:\"peer_node_id\"`\n\t// LastHandshakeAgeSeconds is the whole seconds between the latest completed\n\t// handshake and ObservedAt, in 0..2147483647 (the contract's int32).\n\tLastHandshakeAgeSeconds int32 `json:\"last_handshake_age_seconds\"`\n\t// Endpoint is the address WireGuard uses for the peer as host:port, with an\n\t// IPv6 host in brackets ([2001:db8::7]:51820). A port of 0, an unspecified\n\t// address or an IPv6 zone is refused with 400\n\t// handshake_endpoint_unparseable, for the whole report.\n\tEndpoint string `json:\"endpoint\"`\n\t// RTTMicroseconds is the round-trip time to the peer through the tunnel in\n\t// whole microseconds, in 1..2147483647, and nil when the node holds no\n\t// measurement, which leaves the member off the wire. A control plane older\n\t// than plexsphere/plexsphere#1145 decodes without unknown fields and refuses\n\t// a report that carries it with 400 malformed_handshake_report.\n\tRTTMicroseconds *int32 `json:\"rtt_microseconds,omitempty\"`\n\t// SharedSubnets are the subnets of the pull's shared_subnets the node\n\t// routes through the peer when it assembles the report, as CIDRs without\n\t// host bits, none repeated, at most MaxHandshakeSharedSubnets. An absent\n\t// member, null and [] all mean none, and the control plane then clears\n\t// what it stored for the edge. A control plane that predates the member\n\t// refuses a report that carries it with 400 malformed_handshake_report;\n\t// the node sends it only for a subnet a pull named, which such a control\n\t// plane never does.\n\tSharedSubnets []string `json:\"shared_subnets,omitempty\"`\n}\n```\nHandshakeReportPeer is one entry of a HandshakeReportRequest.\n\nThe three required fields are not omitempty: an age of 0 (a handshake within the last second) is as legitimate as any other, so it must reach the wire rather than be dropped as a zero value and refused as missing. The optional RTTMicroseconds is omitempty and a pointer, so it leaves the wire only when the node holds no measurement, never for a value. The optional SharedSubnets is omitempty too: an entry that carries none sends no member, which the control plane reads as none.\n\n```go\ntype HandshakeReportRequest struct {\n\t// ObservedAt is the agent's wall clock when it assembled the report. It\n\t// gates the request only: a value more than 60 seconds from server time is\n\t// refused with 400 handshake_clock_skew.\n\tObservedAt time.Time `json:\"observed_at\"`\n\t// Peers carries at most MaxHandshakeReportPeers entries and omits a peer\n\t// with no handshake yet. An empty array is a valid report that records\n\t// nothing; a null one is refused, so ReportHandshakes sends nil as [].\n\tPeers []HandshakeReportPeer `json:\"peers\"` // never null on the wire\n}\n```\nHandshakeReportRequest is the body of POST /v1/nodes/{node\\_id}/handshakes: for each mesh peer the node has completed a WireGuard handshake with, the age of the latest handshake, the endpoint WireGuard used for it, when the node holds one, the round-trip time through the tunnel, and the shared subnets the node routes through the peer.\n\nThe control plane anchors every age on its own receive time, so a body is only true for the attempt it was assembled for. The agent builds a fresh one, with a fresh ObservedAt and fresh ages, for every attempt and never replays one: a replayed age would make the handshake look newer than it was. The handler decodes with DisallowUnknownFields, so the struct carries the contract's fields and nothing else.\n\n```go\ntype HandshakeReportResponse struct {\n\t// AcceptedAt is the server receive time every age was anchored on.\n\tAcceptedAt time.Time `json:\"accepted_at\"`\n\t// Recorded counts the entries stored as the latest observation of their\n\t// directed edge.\n\tRecorded int `json:\"recorded\"`\n\t// Ignored counts the entries naming the node itself, an unknown node, a\n\t// node of another Domain or a deregistered peer.\n\tIgnored int `json:\"ignored\"`\n}\n```\nHandshakeReportResponse is the 200 body of POST /v1/nodes/{node\\_id}/handshakes.\n\n```go\ntype HeartbeatRequest struct {\n\tClientNow      time.Time      `json:\"client_now\"`\n\tBinaryChecksum string         `json:\"binary_checksum\"`\n\tBinaryVersion  string         `json:\"binary_version\"`\n\tNATSummary     map[string]any `json:\"nat_summary\"`\n\t// Features are the features the node declares, such as\n\t// FeatureMeshReaddress. A nil or empty list leaves the member off, so a\n\t// node that declares nothing sends the four members a control plane\n\t// predating the member accepts.\n\tFeatures []string `json:\"features,omitempty\"`\n}\n```\n\n```go\ntype HeartbeatResponse struct {\n\tAcceptedAt time.Time `json:\"accepted_at\"`\n\tReconcile  bool      `json:\"reconcile\"`\n\tRotateKeys bool      `json:\"rotate_keys\"`\n}\n```\n\n```go\ntype HookInfo struct {\n\tName        string        `json:\"name\"`\n\tDescription string        `json:\"description\"`\n\tSource      string        `json:\"source\"`\n\tChecksum    string        `json:\"checksum\"`\n\tParameters  []ActionParam `json:\"parameters\"`\n\tTimeout     string        `json:\"timeout\"`\n\tSandbox     string        `json:\"sandbox\"`\n\t// Version is the published version a rolled-out hook was installed from.\n\t// It is zero, and omitted, for a hook whose Source is HookSourceLocal,\n\t// which has no version.\n\tVersion int `json:\"version,omitempty\"`\n}\n```\n\n```go\ntype HookRolloutError struct {\n\tName    string `json:\"name\"`\n\tVersion int    `json:\"version\"`\n\t// Code is one of the HookRolloutCode constants.\n\tCode string `json:\"code\"`\n\t// Detail explains the failure, at most MaxHookRolloutDetailChars code\n\t// points with no NUL. Omitted when empty.\n\tDetail string `json:\"detail,omitempty\"`\n}\n```\nHookRolloutError is one published hook version the node could not install, as the \"Published hooks\" section of plexsphere's agent contract (docs/reference/api/plexd-agent-contract.md) describes it. Name and Version are the pair the pull listed, so the operator's per-node rollout status can put the error beside the rollout that caused it.\n\n```go\ntype HookVersionPayload struct {\n\tProjectID      string        `json:\"project_id\"`\n\tName           string        `json:\"name\"`\n\tVersion        int           `json:\"version\"`\n\tChecksum       string        `json:\"checksum\"`\n\tDescription    string        `json:\"description,omitempty\"`\n\tParameters     []ActionParam `json:\"parameters,omitempty\"`\n\tTimeoutSeconds int64         `json:\"timeout_seconds,omitempty\"`\n\tSandboxLevel   string        `json:\"sandbox_level\"`\n}\n```\nHookVersionPayload is the payload of a hook\\_version envelope, the contract's HookVersionPayload. Name and Version repeat the pair the node fetched, and Checksum is the script's SHA-256 in the encoding of NodeStateHook.Checksum. Description, Parameters, TimeoutSeconds and SandboxLevel are the hook's sidecar fields, signed together with its checksum, and the control plane sends the first three only when the version declares them.\n\n```go\ntype IngestReceipt struct {\n\tAcceptedAt time.Time `json:\"accepted_at\"`\n\tRecords    int       `json:\"records\"`\n}\n```\nIngestReceipt is the 202 body of the three ingest operations (POST /v1/nodes/{node\\_id}/metrics|logs|audit). Records is the number of records the control plane accepted from the batch.\n\n```go\ntype IngressACME struct {\n\tDirectoryURL string `json:\"directory_url\"`\n\tContactEmail string `json:\"contact_email,omitempty\"`\n}\n```\nIngressACME is the ACME account of a bridge's acme rules: the directory the bridge registers at, and the contact it registers with, empty for none.\n\n```go\ntype IngressClientAuth struct {\n\tCABundle string `json:\"ca_bundle\"`\n}\n```\nIngressClientAuth is the client certificate requirement of an ingress rule, the control plane's BridgeIngressRuleClientAuthBundle: CABundle holds the rule's client authorities, 1 to 8 CA certificates as PEM CERTIFICATE blocks.\n\n```go\ntype IngressConditions struct {\n\tPathPrefix string                   `json:\"path_prefix,omitempty\"`\n\tHeaders    []IngressHeaderCondition `json:\"headers,omitempty\"`\n}\n```\nIngressConditions are the request conditions of an ingress rule, the control plane's NodeStateBridgeIngressConditions: a path prefix and up to 8 header conditions, all of which a request must match. The headers arrive in name order.\n\n```go\nfunc (c IngressConditions) IsZero() bool\n```\nIsZero reports whether c names no path prefix and no header, which is a rule without conditions. encoding/json's omitzero calls it.\n\n```go\ntype IngressConfig struct {\n\t// Enabled is the control plane's switch: a bridge serves Rules only when\n\t// it is true and its local configuration does not opt out. A block\n\t// without the member decodes to false and opens no public listener. The\n\t// control plane sends true on every block it delivers.\n\tEnabled bool          `json:\"enabled\"`\n\tRules   []IngressRule `json:\"rules\"`\n\t// ACME is the account the block's acme rules share, the control plane's\n\t// NodeStateBridgeIngressACME. It is present exactly when a rule has mode\n\t// acme.\n\tACME *IngressACME `json:\"acme,omitempty\"`\n}\n```\nIngressConfig is the bridge.ingress block of the state pull, the control plane's NodeStateBridgeIngress.\n\n```go\ntype IngressHeaderCondition struct {\n\tName  string `json:\"name\"`\n\tValue string `json:\"value\"`\n}\n```\nIngressHeaderCondition is one header condition: a field of Name, a lowercase token, that carries exactly Value.\n\n```go\ntype IngressInfo struct {\n\tEnabled   bool `json:\"enabled\"`\n\tRuleCount int  `json:\"rule_count\"`\n\t// ConnectionCount counts the open client connections of the tcp rules\n\t// and the open flows of the udp rules. A flow carries the datagrams of\n\t// one client address and port and the target's answers to them.\n\tConnectionCount int  `json:\"connection_count\"`\n\tACMEEnabled     bool `json:\"acme_enabled\"`\n}\n```\nIngressInfo is the ingress status reported by the node in heartbeats.\n\n```go\ntype IngressRule struct {\n\tID   string `json:\"id\"`\n\tSlug string `json:\"slug\"`\n\t// Protocol is IngressProtocolTCP or IngressProtocolUDP. A rule of a\n\t// control plane before plexsphere/plexsphere#1110 carries none and\n\t// decodes to an empty Protocol, which a bridge serves as tcp.\n\tProtocol string `json:\"protocol,omitempty\"`\n\t// ListenPort is the public port the bridge listens on, TCP or UDP by\n\t// Protocol.\n\tListenPort int `json:\"listen_port\"`\n\t// Mode is IngressModePassthrough, IngressModeTerminate or IngressModeACME.\n\tMode string `json:\"mode\"`\n\t// SNIHost is the server name the rule matches on a shared port, exact or\n\t// a wildcard of one left-most label. A rule without it is the only rule on\n\t// its port.\n\tSNIHost string `json:\"sni_host,omitempty\"`\n\t// Targets are the rule's targets, one to eight, in round-robin order, as\n\t// a control plane since plexsphere/plexsphere#1120 sends them. A rule of\n\t// an earlier control plane carries none and marshals without the key; an\n\t// absent, null or empty member decodes to an empty Targets.\n\tTargets []IngressTarget `json:\"targets,omitempty\"`\n\t// TargetNodeID, TargetAddress and TargetPort name the rule's first\n\t// target. They are deprecated: a bridge reads them only when Targets is\n\t// empty, as a control plane before plexsphere/plexsphere#1120 sends a\n\t// rule.\n\tTargetNodeID string `json:\"target_node_id\"`\n\t// TargetAddress is the target node's mesh address, IPv4 or IPv6, without\n\t// brackets. Deprecated: see TargetNodeID.\n\tTargetAddress string `json:\"target_address\"`\n\t// TargetPort is the port on the target. Deprecated: see TargetNodeID.\n\tTargetPort int `json:\"target_port\"`\n\t// CertificateSecretName names the Secret of the bridge's Project that\n\t// holds a terminate rule's certificate chain and key, one PEM document.\n\t// It is empty on every other mode.\n\tCertificateSecretName string `json:\"certificate_secret_name,omitempty\"`\n\t// Conditions are the request conditions of a terminate or acme rule:\n\t// rules with conditions share one listen port and SNI host, and the\n\t// bridge hands each request to the rule they pick. A rule without\n\t// conditions marshals without the key, and an absent, null or empty\n\t// member decodes to a rule without conditions.\n\tConditions IngressConditions `json:\"conditions,omitzero\"`\n\t// StripPathPrefix removes the matched path prefix from the front of the\n\t// path the target receives. Only a rule whose path prefix is present\n\t// and not \"/\" carries it.\n\tStripPathPrefix bool `json:\"strip_path_prefix,omitempty\"`\n\t// ClientAuth requires a client certificate that chains to one of the\n\t// rule's client authorities; only a terminate or acme rule carries it.\n\t// It is a pointer because presence is the requirement: an absent member\n\t// and null decode to nil, which marshals without the key, and {} and\n\t// {\"ca_bundle\": \"\"} decode to a value with an empty bundle, which the\n\t// bridge cannot build its authorities from.\n\tClientAuth *IngressClientAuth `json:\"client_auth,omitempty\"`\n}\n```\nIngressRule is one rule of the block, the control plane's NodeStateBridgeIngressRule. It is not comparable with ==; Equal compares two rules.\n\n```go\nfunc (r IngressRule) Equal(o IngressRule) bool\n```\nEqual reports whether two rules carry the same members. A nil and an empty Conditions.Headers are equal, and so are a nil and an empty Targets; the order of the headers and of the targets counts. reflect.DeepEqual follows the ClientAuth pointer: a nil and a non-nil ClientAuth differ, and two bundles compare by their text, so a bundle that differs in one byte or in the order of its blocks makes another rule.\n\n```go\ntype IngressStatusClientRefusal struct {\n\t// Reason is a reason token: no_certificate, unknown_authority,\n\t// certificate_expired or certificate_invalid.\n\tReason string `json:\"reason\"`\n\t// AgeSeconds is the whole seconds between the refusal and the report, in\n\t// 0..MaxIngressStatusRefusalAgeSeconds. The contract requires the member,\n\t// and 0 is a valid age, so it has no omitempty.\n\tAgeSeconds int64 `json:\"age_seconds\"`\n}\n```\nIngressStatusClientRefusal is one entry of a rule entry's client\\_refusals, the control plane's IngressStatusReportRuleClientRefusal: the last client the bridge refused for Reason. No two entries of one rule name the same Reason.\n\n```go\ntype IngressStatusRequest struct {\n\t// State is one of the IngressState* constants.\n\tState string `json:\"state\"`\n\t// Rules holds one entry per reported rule, in the order of the pull; nil\n\t// omits the member, which the contract reads as no entries.\n\tRules []IngressStatusRule `json:\"rules,omitempty\"`\n}\n```\nIngressStatusRequest is the body of PUT /v1/nodes/{node\\_id}/ingress-status: whether the bridge's local configuration serves public ingress, and how each ingress rule of its pull fares. The control plane keeps the latest state per node and never ages it, and refuses ingress rule creates and updates on the bridge while it reads opted\\_out. Each report replaces the rule entries of the one before it.\n\nA missing, null or unknown state, an unknown member, data after the report, more than MaxIngressStatusRules entries, and an entry with a malformed id or a value outside its member's rule answer 400 malformed\\_ingress\\_status. An opted-out report with entries, an id that repeats an earlier entry, an entry that breaks the presence rules of IngressStatusRule, and a refusal whose reason an earlier refusal of its entry carries answer 400 invalid\\_ingress\\_status.\n\n```go\ntype IngressStatusResponse struct {\n\t// AcceptedAt is the server receive time of the report.\n\tAcceptedAt time.Time `json:\"accepted_at\"`\n}\n```\nIngressStatusResponse is the 200 body of PUT /v1/nodes/{node\\_id}/ingress-status.\n\n```go\ntype IngressStatusRule struct {\n\t// ID is the rule's id from the pull, a UUID other than the zero UUID.\n\tID string `json:\"id\"`\n\t// Listener is one of the IngressListener* constants.\n\tListener       string `json:\"listener\"`\n\tListenerReason string `json:\"listener_reason,omitempty\"`\n\t// Certificate is one of the IngressCertificate* constants.\n\tCertificate       string `json:\"certificate,omitempty\"`\n\tCertificateReason string `json:\"certificate_reason,omitempty\"`\n\t// Dial is one of the IngressDial* constants.\n\tDial       string `json:\"dial,omitempty\"`\n\tDialReason string `json:\"dial_reason,omitempty\"`\n\t// DialAgeSeconds is the whole seconds between the dial and the report, in\n\t// 0..MaxIngressStatusDialAgeSeconds. It is a pointer because 0 is a valid\n\t// age, for a dial less than a second ago.\n\tDialAgeSeconds *int64 `json:\"dial_age_seconds,omitempty\"`\n\t// Targets holds at most MaxIngressStatusTargets entries, one per target\n\t// of the rule, only beside a Listener of listening; nil omits the member,\n\t// which the contract reads as no entries.\n\tTargets []IngressStatusTarget `json:\"targets,omitempty\"`\n\t// ClientAuthEnforced says that the bridge verifies every client of the\n\t// rule against its client authorities, or serves no client of the rule.\n\t// It is sent only for a listening rule whose pull entry carries\n\t// client_auth; false omits the member, which the contract reads as false.\n\tClientAuthEnforced bool `json:\"client_auth_enforced,omitempty\"`\n\t// ClientRefusals holds at most MaxIngressStatusClientRefusals entries,\n\t// one per reason, only beside a ClientAuthEnforced of true; nil omits the\n\t// member, which the contract reads as no entries.\n\tClientRefusals []IngressStatusClientRefusal `json:\"client_refusals,omitempty\"`\n}\n```\nIngressStatusRule is one entry of rules, the control plane's IngressStatusReportRule. Each member after Listener is sent exactly when the facet before it calls for it: ListenerReason when Listener is not\\_listening; Certificate and Dial when it is listening; CertificateReason when Certificate is not\\_ready; DialReason when Dial is failed; DialAgeSeconds when Dial is succeeded or failed. ClientAuthEnforced is true only beside a Listener of listening, and ClientRefusals carries entries only beside a ClientAuthEnforced of true. omitempty drops an empty member, so a caller leaves every member it must not send empty.\n\n```go\ntype IngressStatusTarget struct {\n\t// NodeID is the target's node_id from the pull, a UUID other than the\n\t// zero UUID.\n\tNodeID string `json:\"node_id\"`\n\t// Port is the target's port from the pull, in 1..65535.\n\tPort int `json:\"port\"`\n\t// Dial is one of the IngressDial* constants.\n\tDial       string `json:\"dial\"`\n\tDialReason string `json:\"dial_reason,omitempty\"`\n\t// DialAgeSeconds is the whole seconds between the last dial to the target\n\t// and the report, in 0..MaxIngressStatusDialAgeSeconds.\n\tDialAgeSeconds *int64 `json:\"dial_age_seconds,omitempty\"`\n}\n```\nIngressStatusTarget is one entry of a rule entry's targets, the control plane's IngressStatusReportRuleTarget: the target as the pull names it and the last dial the bridge made to it. DialReason is sent exactly when Dial is failed, and DialAgeSeconds exactly when Dial is succeeded or failed. No two entries of one rule name the same NodeID and Port.\n\n```go\ntype IngressTarget struct {\n\tNodeID  string `json:\"node_id\"`\n\tAddress string `json:\"address\"`\n\tPort    int    `json:\"port\"`\n}\n```\nIngressTarget is one target of an ingress rule, the control plane's NodeStateBridgeIngressRuleTarget: a target node, its mesh address, IPv4 or IPv6 without brackets, and a port on it.\n\n```go\ntype IntegrityDetector string\n```\nIntegrityDetector is the on-node detector that surfaced a violation. Like IntegrityViolationKind the set is closed; a value outside it is refused with 400 integrity\\_violation\\_detected\\_by\\_invalid.\n\n```go\nconst (\n\t// IntegrityDetectorStartupScan is the agent's own sweep of the artifacts it\n\t// holds baselines for. The contract has no value for a periodic re-scan, so\n\t// the interval-driven sweep reports this one too.\n\tIntegrityDetectorStartupScan IntegrityDetector = \"startup_scan\"\n\t// IntegrityDetectorInotify is the hooks-directory watcher reacting to a\n\t// filesystem event.\n\tIntegrityDetectorInotify IntegrityDetector = \"inotify\"\n\t// IntegrityDetectorPreDispatch is the check that runs immediately before a\n\t// hook executes.\n\tIntegrityDetectorPreDispatch IntegrityDetector = \"pre_dispatch\"\n)\n```\n\n```go\ntype IntegrityViolationKind string\n```\nIntegrityViolationKind is the artifact class a violation applies to. The control plane canonicalises every entry through a value-object constructor that refuses anything outside this set with 400 integrity\\_violation\\_kind\\_invalid, so the type exists to keep an unchecked string from reaching the wire in the first place.\n\n```go\nconst (\n\t// IntegrityKindBinaryChecksum reports the agent's own binary.\n\tIntegrityKindBinaryChecksum IntegrityViolationKind = \"binary_checksum\"\n\t// IntegrityKindHookChecksum reports a hook script.\n\tIntegrityKindHookChecksum IntegrityViolationKind = \"hook_checksum\"\n\t// IntegrityKindSSHHostKey reports the mesh SSH host key.\n\tIntegrityKindSSHHostKey IntegrityViolationKind = \"ssh_host_key\"\n)\n```\n\n```go\ntype IntegrityViolationReport struct {\n\tKind       IntegrityViolationKind `json:\"kind\"`\n\tDetectedBy IntegrityDetector      `json:\"detected_by\"`\n\t// ArtifactID identifies the affected artifact — a hook path, the binary\n\t// path, or the host-key file. Non-empty after trimming, at most 4096 bytes.\n\tArtifactID string `json:\"artifact_id\"`\n\t// ObservedChecksum is the SHA-256 the agent computed, as 32 raw bytes in\n\t// standard-padded base64 (see integrity.WireChecksum). Required for the\n\t// checksum kinds; anything that does not decode to exactly 32 bytes is\n\t// refused with 400 integrity_violation_checksum_invalid.\n\tObservedChecksum string `json:\"observed_checksum,omitempty\"`\n\t// ExpectedChecksum is the baseline digest, same encoding as\n\t// ObservedChecksum.\n\tExpectedChecksum string `json:\"expected_checksum,omitempty\"`\n\t// ObservedFingerprint is the OpenSSH host-key fingerprint the agent\n\t// observed, in the canonical `SHA256:\u003cbase64\u003e` form. Required for the\n\t// ssh_host_key kind.\n\tObservedFingerprint string `json:\"observed_fingerprint,omitempty\"`\n\t// ExpectedFingerprint is the baseline fingerprint, same form as\n\t// ObservedFingerprint.\n\tExpectedFingerprint string `json:\"expected_fingerprint,omitempty\"`\n}\n```\nIntegrityViolationReport is one entry of an IntegrityViolationsRequest.\n\nThe handler decodes the envelope with DisallowUnknownFields, so this struct carries the contract's fields and nothing else — in particular there is no timestamp (the control plane stamps its own) and no free-text detail field.\n\nKind decides which digest pair is legal. A binary\\_checksum or hook\\_checksum entry carries the checksums and no fingerprint; an ssh\\_host\\_key entry carries the fingerprints and no checksum. Crossing them is refused with 400 integrity\\_violation\\_kind\\_mismatch, which is why the four digest fields are omitempty: an unset one must be absent from the JSON, not present and empty.\n\n```go\ntype IntegrityViolationsRequest struct {\n\t// Violations carries between 1 and MaxIntegrityViolationsPerBatch entries.\n\tViolations []IntegrityViolationReport `json:\"violations\"`\n}\n```\nIntegrityViolationsRequest is the body of POST /v1/nodes/{node\\_id}/integrity-violations: a batch of the tamper-evidence divergences the agent detected locally. The endpoint takes a batch even when the agent has a single violation to report, so a lone finding travels as a one-entry array rather than as a bare object.\n\n```go\ntype IntegrityViolationsResponse struct {\n\t// AcceptedAt is the server-side commit timestamp.\n\tAcceptedAt time.Time `json:\"accepted_at\"`\n\t// ViolationCount echoes the number of rows persisted, matching the length\n\t// of the violations array on input.\n\tViolationCount int `json:\"violation_count\"`\n}\n```\nIntegrityViolationsResponse is the 200 body of POST /v1/nodes/{node\\_id}/integrity-violations. The work is synchronous — every row and the integrity\\_alert outbox event are committed before the response is written — so the status is 200 rather than 202.\n\n```go\ntype K8sActivity struct {\n\tVerb         string `json:\"verb\"`\n\tResourceKind string `json:\"resource_kind,omitempty\"`\n\tNamespace    string `json:\"namespace,omitempty\"`\n\tName         string `json:\"name,omitempty\"`\n\tStatusCode   int    `json:\"status_code,omitempty\"`\n\tDurationMS   int64  `json:\"duration_ms,omitempty\"`\n}\n```\nK8sActivity records a single Kubernetes API action proxied through the session. Verb is the API verb; the remaining fields describe the target object and the outcome.\n\n```go\ntype KeyRotateRequest struct {\n\tNewPublicKey string `json:\"new_public_key\"`\n}\n```\n\n```go\ntype KeyRotateResponse struct {\n\tRotationID     string `json:\"rotation_id\"`\n\tKID            string `json:\"kid\"`\n\tWrapKeyVersion int    `json:\"wrap_key_version\"`\n}\n```\n\n```go\ntype LocalEndpointConfig struct {\n\t// URL is the HTTPS endpoint URL. Must use the https:// scheme when set.\n\tURL string `yaml:\"url\"`\n\n\t// SecretKey is the authentication credential for the local endpoint.\n\t// Required when URL is non-empty.\n\tSecretKey string `yaml:\"secret_key\"`\n\n\t// TLSInsecureSkipVerify disables TLS certificate verification.\n\tTLSInsecureSkipVerify bool `yaml:\"tls_insecure_skip_verify\"`\n\n\t// TLSCAFile names a PEM file whose certificates are trusted for the\n\t// endpoint in addition to the host's system roots, so an endpoint behind\n\t// a private CA needs neither that CA in the host's trust store nor\n\t// TLSInsecureSkipVerify. TLSClientConfig reads it on each call.\n\tTLSCAFile string `yaml:\"tls_ca_file\"`\n}\n```\nLocalEndpointConfig holds the configuration for a local data-plane endpoint that a pipeline can send data to in addition to the platform. A zero-valued LocalEndpointConfig means \"not configured\" and passes validation.\n\n```go\nfunc (c *LocalEndpointConfig) TLSClientConfig(logger *slog.Logger) (*tls.Config, error)\n```\nTLSClientConfig returns the TLS settings for a client of the endpoint, or nil when the endpoint sets neither TLS option and the transport's defaults apply.\n\n```go\nfunc (c *LocalEndpointConfig) Validate(prefix string) error\n```\nValidate checks that the local endpoint configuration is well-formed. The prefix is prepended to error messages for context (e.g. \"metrics\").\n\n```go\ntype LogBatch = []LogEntry\n```\nLogBatch is the internal pipeline and local-endpoint payload for a batch of log entries. The control-plane leg of POST /v1/nodes/{node\\_id}/logs sends LogLine instead.\n\n```go\ntype LogEntry struct {\n\tTimestamp time.Time `json:\"timestamp\"`\n\tSource    string    `json:\"source\"`\n\tUnit      string    `json:\"unit\"`\n\tMessage   string    `json:\"message\"`\n\tSeverity  string    `json:\"severity\"`\n\tHostname  string    `json:\"hostname\"`\n}\n```\nLogEntry is the internal pipeline and local-endpoint format for a single log record. The control-plane leg sends LogLine instead.\n\n```go\ntype LogLine struct {\n\tSeverity  string    `json:\"severity\"`\n\tUnit      string    `json:\"unit,omitempty\"`\n\tHostname  string    `json:\"hostname,omitempty\"`\n\tMessage   string    `json:\"message\"`\n\tTimestamp time.Time `json:\"timestamp\"`\n}\n```\nLogLine is the control-plane wire format for a single log record in the body of POST /v1/nodes/{node\\_id}/logs. Unit and Hostname are absent when unknown.\n\n```go\ntype MetricBatch = []MetricPoint\n```\nMetricBatch is the internal pipeline and local-endpoint payload for a batch of metric points. The control-plane leg of POST /v1/nodes/{node\\_id}/metrics sends MetricSample instead.\n\n```go\ntype MetricPoint struct {\n\tTimestamp time.Time       `json:\"timestamp\"`\n\tGroup     string          `json:\"group\"`\n\tPeerID    string          `json:\"peer_id,omitempty\"`\n\tData      json.RawMessage `json:\"data\"`\n}\n```\nMetricPoint is the internal pipeline and local-endpoint format for a single metric. The control-plane leg sends MetricSample instead.\n\n```go\ntype MetricSample struct {\n\tGroup     string            `json:\"group\"`\n\tName      string            `json:\"name\"`\n\tValue     float64           `json:\"value\"`\n\tLabels    map[string]string `json:\"labels,omitempty\"`\n\tTimestamp time.Time         `json:\"timestamp\"`\n}\n```\nMetricSample is the control-plane wire format for a single metric in the body of POST /v1/nodes/{node\\_id}/metrics. Group is one of the MetricGroup\\* values; Labels is absent when the sample carries no dimensions.\n\n```go\ntype NoOpVerifier struct{}\n```\nNoOpVerifier is an EventVerifier that accepts all envelopes without verification.\n\n```go\nfunc (NoOpVerifier) Verify(_ context.Context, _ Envelope) error\n```\nVerify always returns nil.\n\n```go\ntype NodeHookVersion struct {\n\tEnvelope     Envelope `json:\"envelope\"`\n\tScriptBase64 string   `json:\"script_base64\"`\n}\n```\nNodeHookVersion is the 200 body of the hook version fetch: the signed envelope that describes one published hook version, and the script itself in standard base64. The script sits outside the envelope, so the signature covers its checksum in the payload rather than its bytes. Nothing here is verified on decode: the envelope's payload decodes into HookVersionPayload, and the installer checks the signature, the pair it fetched, and the script's digest before it writes anything.\n\n```go\ntype NodeStateBlock struct {\n\tMetadata []StateEntry `json:\"metadata\"`\n\tData     []StateEntry `json:\"data\"`\n\tReports  []StateEntry `json:\"reports\"`\n}\n```\nNodeStateBlock is a three-bucket state block. Each bucket is a required array (never null when the block is populated), with entries ordered by key ascending.\n\n```go\ntype NodeStateDNS struct {\n\tSearchDomain string               `json:\"search_domain\"`\n\tZones        []string             `json:\"zones\"`\n\tHosts        []NodeStateDNSHost   `json:\"hosts\"`\n\tRecords      []NodeStateDNSRecord `json:\"records\"`\n\tReverseZones []string             `json:\"reverse_zones\"`\n\t// Forwarding is a pointer because the member is the full setting and its\n\t// absence says something else: a nil value, the wire's null or a key a\n\t// control plane predating forwarding never wrote, means the control plane\n\t// did not say this time, and the node keeps the forwarding it holds. Two\n\t// empty lists say the node forwards nothing. omitempty lets the mock\n\t// control plane, which marshals this type, serve a block without it.\n\tForwarding *NodeStateDNSForwarding `json:\"forwarding,omitempty\"`\n}\n```\nNodeStateDNS is the dns block of the state pull, as the \"Mesh DNS names\" section of plexsphere's agent contract (docs/reference/api/plexd-agent-contract.md) describes it. SearchDomain is the zone of the node's own Project. Zones are the Domain's default domain and every Project zone, ascending. Hosts are every node of the Domain, the pulling node included, ordered by FQDN. Records are the DNS records of the Domain and of every Project, ordered by FQDN, then by type. A nil Records, the wire's null or a key a control plane predating records never wrote, means the Domain has no records: the block is the full set, so it is no signal to keep the records held. ReverseZones are the in-addr.arpa or ip6.arpa zones that cover the Domain's mesh CIDR and nothing wider. Forwarding is the DNS forwarding setting that applies to the pulling node. The control plane sends every name in lower case without a trailing dot, and an empty list as \\[].\n\n```go\ntype NodeStateDNSForwardZone struct {\n\tZone      string   `json:\"zone\"`\n\tResolvers []string `json:\"resolvers\"`\n}\n```\nNodeStateDNSForwardZone is one entry of the forwarding member's forward\\_zones, as the \"Mesh DNS names\" section of plexsphere's agent contract describes it: a zone outside the mesh and the resolvers that answer the names under it, in the order they are asked.\n\n```go\ntype NodeStateDNSForwarding struct {\n\tForwardZones []NodeStateDNSForwardZone `json:\"forward_zones\"`\n\tCatchAll     []string                  `json:\"catch_all\"`\n}\n```\nNodeStateDNSForwarding is the forwarding member of the dns block, as the \"Mesh DNS names\" section of plexsphere's agent contract describes it: the Project's setting when the node's Project holds one, otherwise its Domain's, otherwise two empty lists. ForwardZones are ascending by zone, each with 1 to 3 resolvers. CatchAll holds 0 to 3 resolvers, which answer every name outside the mesh zones, the reverse zones and the forward zones. A resolver is an IPv4 or IPv6 address in text form, asked in list order on port 53 over plain DNS. A nil list, the wire's null or a missing key, is an empty one.\n\n```go\ntype NodeStateDNSHost struct {\n\tNodeID string `json:\"node_id\"`\n\tFQDN   string `json:\"fqdn\"`\n\tMeshIP string `json:\"mesh_ip\"`\n}\n```\nNodeStateDNSHost is one entry of the dns block's hosts, as the \"Mesh DNS names\" section of plexsphere's agent contract describes it: a node of the Domain, its fully qualified name, and its mesh IP, IPv4 or IPv6 by the family of the Domain's mesh CIDR.\n\n```go\ntype NodeStateDNSRecord struct {\n\tFQDN     string   `json:\"fqdn\"`\n\tType     string   `json:\"type\"`\n\tAddress  string   `json:\"address,omitempty\"`\n\tTarget   string   `json:\"target,omitempty\"`\n\tPriority *int     `json:\"priority,omitempty\"`\n\tWeight   *int     `json:\"weight,omitempty\"`\n\tPort     *int     `json:\"port,omitempty\"`\n\tText     []string `json:\"text,omitempty\"`\n}\n```\nNodeStateDNSRecord is one entry of the dns block's records, as the \"Mesh DNS names\" section of plexsphere's agent contract describes it: a record's fully qualified name, its type (A, AAAA, CNAME, TXT, SRV or MX) and the data members of that type, and no other member. Address belongs to A and AAAA, Target to CNAME, SRV and MX, Priority to SRV and MX (the preference of an MX), Weight and Port to SRV, and Text to TXT.\n\nThe numbers are pointers because the contract sends a priority or a weight of 0 as 0 and leaves out every member a type does not take, which the mock control plane marshals this type for. They are int rather than uint16, so a number out of range costs the one record it belongs to, which the resolver skips, rather than the decode of the whole snapshot.\n\n```go\ntype NodeStateExecution struct {\n\tExecutionID       string                     `json:\"execution_id\"`\n\tAction            string                     `json:\"action\"`\n\tType              string                     `json:\"type\"`\n\tParameters        map[string]json.RawMessage `json:\"parameters\"`\n\tStatus            string                     `json:\"status\"`\n\tRequestedAt       time.Time                  `json:\"requested_at\"`\n\tExpiresAt         time.Time                  `json:\"expires_at\"`\n\tCancelRequestedAt *time.Time                 `json:\"cancel_requested_at,omitempty\"`\n}\n```\nNodeStateExecution is one pending action dispatch in the executions block of GET /v1/nodes/{node\\_id}/state. That block is the delivery channel for action dispatches: it is always present (\\[] when empty, never null) and ordered by RequestedAt, then ExecutionID. An entry keeps reappearing on every pull until its execution reaches a terminal status through the execution callback, so a consumer must tolerate re-observing the same ExecutionID.\n\nType is one of the ActionKind\\* values; Status is ExecutionStatusPending, ExecutionStatusAck, or ExecutionStatusStarted. ExpiresAt is an absolute UTC deadline, not a relative timeout. Parameters is nullable: a JSON null decodes to a nil map. The entry carries no callback URL and no hook checksum.\n\nA parameter value is held as raw JSON, not decoded into any: the state response is decoded with a plain decoder, so a JSON number would land in an any as a float64 and every integer beyond 2^53 would reach the action rewritten. The raw form hands the value to the action exactly as the control plane sent it.\n\nCancelRequestedAt is present only on a started entry, once an operator cancelled the Execution: the control plane ends a pending or ack target at once, and such an entry leaves the block. Its presence is the signal to stop the run; plexd never compares its value with its own clock. A JSON null and an absent key both decode to nil. A value that is not an RFC 3339 string fails the decode of the whole state response, as a malformed expires\\_at does.\n\n```go\ntype NodeStateFailureDetection struct {\n\tDetectAfterSeconds int64 `json:\"detect_after_seconds\"`\n}\n```\nNodeStateFailureDetection is the failure\\_detection block of the state pull, as the \"Failure detection\" section of plexsphere's agent contract (docs/reference/api/plexd-agent-contract.md) describes it. DetectAfterSeconds is how long a path the node watches on its own, today a relay, may stay silent before the node moves: a whole number of seconds from 5 to 180, and 15 for a Domain that never set it. It is int64 rather than int so a value out of range decodes on 32-bit builds too, and is clamped rather than refused as malformed.\n\n```go\ntype NodeStateHook struct {\n\tName     string `json:\"name\"`\n\tVersion  int    `json:\"version\"`\n\tChecksum string `json:\"checksum\"`\n}\n```\nNodeStateHook is one entry of the hooks block of the state pull, a published hook version a rollout assigns the node, as the \"Published hooks\" section of plexsphere's agent contract (docs/reference/api/plexd-agent-contract.md) describes it. It never carries the script, which the node fetches through GET /v1/nodes/{node\\_id}/hooks/{name}/versions/{version}. Checksum is the SHA-256 of that script as 32 raw bytes in standard-padded base64, the encoding of a DeclaredHook's Checksum, so the fetched version is checked against the digest the pull named.\n\n```go\ntype NodeStateReportRequest struct {\n\tValue       string `json:\"value\"`\n\tWorkloadTag string `json:\"workload_tag,omitempty\"`\n}\n```\nNodeStateReportRequest is the control-plane wire format for the body of PUT /v1/nodes/{id}/state/reports/{key}. Value is the opaque report payload; WorkloadTag attributes the report to a workload and is absent when the report is unattributed.\n\n```go\ntype NodeStateReportResponse struct {\n\tAcceptedAt time.Time `json:\"accepted_at\"`\n\tKey        string    `json:\"key\"`\n}\n```\nNodeStateReportResponse is the control-plane wire format for the 200 body of PUT /v1/nodes/{id}/state/reports/{key} (and DELETE /v1/nodes/{id}/state/ reports/{key}). Key echoes the report key the operation addressed.\n\n```go\ntype NodeStateSecret struct {\n\tName    string `json:\"name\"`\n\tVersion int    `json:\"version\"`\n}\n```\nNodeStateSecret is one entry of the secrets block of the state pull, a Secret the node may read as the \"Secret inventory\" section of plexsphere's agent contract (docs/reference/api/plexd-agent-contract.md) describes it: its name and current version, never its value, which the node fetches through GET /v1/nodes/{node\\_id}/secrets/{name}. The node API maps Name onto the key of its secret index (SecretRef.Key).\n\n```go\ntype NodeStateSession struct {\n\tSessionID          string        `json:\"session_id\"`\n\tJTI                string        `json:\"jti\"`\n\tKind               string        `json:\"kind\"`\n\tTarget             SessionTarget `json:\"target\"`\n\tExpiresAt          time.Time     `json:\"expires_at\"`\n\tIdleTimeoutSeconds int           `json:\"idle_timeout_seconds,omitempty\"`\n}\n```\nNodeStateSession is one live mediated-access session in the sessions block of GET /v1/nodes/{node\\_id}/state. That block is desired state, not a queue: it is always present on the wire (\\[] when empty, never null). An entry appears when the control plane issues the session and disappears on revocation or hard expiry — the disappearance is the teardown signal, there is no separate teardown event. A response that violates the contract by omitting or nulling the block decodes to a nil NodeStateSnapshot.Sessions and is not read as an empty block.\n\nKind is one of the SessionKind\\* values and selects which member of Target is set. JTI equals the session id: it is carried as an opaque value and never evaluated. ExpiresAt is an absolute UTC timestamp, not a relative timeout. IdleTimeoutSeconds 0 or absent means the session has no idle window.\n\n```go\ntype NodeStateSharedSubnet struct {\n\tSubnet  string   `json:\"subnet\"`\n\tBridges []string `json:\"bridges\"`\n}\n```\nNodeStateSharedSubnet is one entry of the shared\\_subnets block of the state pull, as the \"Shared site subnets\" section of plexsphere's agent contract (docs/reference/api/plexd-agent-contract.md) describes it. Subnet is a CIDR. Bridges are node IDs, each the node\\_id of a peer of the same pull: the carrier first, then the standbys in the order the node fails over through. The carrier's peer entry lists the subnet in its routed\\_subnets as well.\n\n```go\ntype NodeStateSigningKey struct {\n\tKeyID     string `json:\"key_id\"`\n\tPublicKey string `json:\"public_key\"`\n}\n```\nNodeStateSigningKey is the signing\\_key block of the state pull, the Domain signing key as the \"Domain signing key\" section of plexsphere's agent contract (docs/reference/api/plexd-agent-contract.md) describes it: the id the key signs under and its 32-byte Ed25519 public key in standard base64, the same encodings POST /v1/register uses.\n\n```go\ntype NodeStateSnapshot struct {\n\t// MeshIP is the mesh address the node must use, read from the Node row on\n\t// every pull. A control plane that predates the member leaves the key out,\n\t// which decodes to the empty string, and the node keeps its address. A\n\t// value of another JSON type fails the pull's decode, as it does for Peers.\n\tMeshIP       string               `json:\"mesh_ip\"`\n\tPeers        []SnapshotPeer       `json:\"peers\"`\n\tReachability json.RawMessage      `json:\"reachability\"`\n\tPolicy       *PolicySnapshot      `json:\"policy\"`\n\tBridge       *BridgeSnapshot      `json:\"bridge\"`\n\tState        *NodeStateBlock      `json:\"state\"`\n\tReports      *NodeStateBlock      `json:\"reports\"`\n\tExecutions   []NodeStateExecution `json:\"executions\"`\n\t// Sessions is a pointer for the same reason the block fields above are: the\n\t// sessions block is desired state whose emptiness is destructive — an empty\n\t// block tears every live session down — so \"the control plane says you have\n\t// no sessions\" ([]) has to stay distinguishable from \"the control plane did\n\t// not populate the block\" (null, or a key a build predating the block never\n\t// wrote). A nil pointer is the second case and is not a teardown signal.\n\tSessions *[]NodeStateSession `json:\"sessions\"`\n\t// Secrets is the node's secret inventory, ordered by name. It is a pointer\n\t// for the reason Sessions is: [] says the node may read nothing and empties\n\t// the node API's secret index, while a nil value, the wire's null or a key a\n\t// control plane predating the block never wrote, means the control plane did\n\t// not say this time, and the index is kept.\n\tSecrets *[]NodeStateSecret `json:\"secrets\"`\n\t// SigningKey is the key the node's Domain signs envelopes and session\n\t// tokens with. A nil value, the wire's null or a key a control plane\n\t// predating the block never wrote, means the control plane could not say\n\t// this time: the node keeps the key it holds, and never drops it.\n\tSigningKey *NodeStateSigningKey `json:\"signing_key\"`\n\t// Hooks is the node's desired set of published hook versions, ordered by\n\t// name. It is a pointer for the reason Secrets is: [] says the node should\n\t// run no rolled-out hook and removes every one it installed, while a nil\n\t// value, the wire's null or a key a control plane predating the block\n\t// never wrote, means the control plane could not compute the set this\n\t// time, and every rolled-out hook is kept.\n\tHooks *[]NodeStateHook `json:\"hooks\"`\n\t// DNS is the mesh DNS names of the node's Domain. A block is the full set,\n\t// never a delta: it replaces the names the node answers. A nil value, the\n\t// wire's null or a key a control plane predating the block never wrote,\n\t// means the control plane did not say this time, and the node keeps the\n\t// names it holds.\n\tDNS *NodeStateDNS `json:\"dns\"`\n\t// FailureDetection is the Domain's failure-detection time, a\n\t// NodeStateFailureDetection. It is carried raw, as Reachability is, so\n\t// its consumer decodes it leniently and a malformed tuning value never\n\t// fails the pull that carries the peers and the policy. A nil value, the\n\t// wire's null or a key a control plane predating the block never wrote,\n\t// means the control plane did not say this time, and the node keeps the\n\t// value it holds.\n\tFailureDetection json.RawMessage `json:\"failure_detection\"`\n\t// SharedSubnets is the order of the bridges each shared site subnet of\n\t// the node's Project may be routed through, one entry per subnet. A nil\n\t// value, the wire's null or a key a control plane predating the block\n\t// never wrote, and [] all mean no shared subnet: only such a control\n\t// plane leaves the key out, and it has none. The member is typed, as\n\t// Peers is, so a value of another JSON type fails the pull's decode; the\n\t// WireGuard manager validates the entries.\n\tSharedSubnets []NodeStateSharedSubnet `json:\"shared_subnets\"`\n}\n```\nNodeStateSnapshot is the desired-state envelope returned by GET /v1/nodes/{node\\_id}/state. Every block key is always present on the wire: a null value means \"block not populated\", never \"field absent\". The differ therefore distinguishes a nil pointer from a populated block, so none of the fifteen fields carry omitempty.\n\n```go\ntype Peer struct {\n\tID        string `json:\"id\"`\n\tPublicKey string `json:\"public_key\"`\n\tMeshIP    string `json:\"mesh_ip\"`\n\t// Endpoint is the first entry of Endpoints, or empty when the peer has no\n\t// endpoint to dial.\n\tEndpoint string `json:\"endpoint\"`\n\t// Endpoints is the peer's dial order: the endpoints the WireGuard manager\n\t// tries one after another until a handshake completes.\n\tEndpoints []string `json:\"endpoints,omitempty\"`\n\t// Fallbacks is the peer's relay set as it ends Endpoints, in dial order:\n\t// the relay of its assigned bridge first, then its standby relays, and nil\n\t// when the peer has no relay. Endpoint selection holds each relay as long\n\t// as the entries before the first one took together, and only a peer that\n\t// connected over a relay dials the standbys.\n\tFallbacks []string `json:\"fallbacks,omitempty\"`\n\t// AllowedIPs is the peer's mesh address as a /32 followed by\n\t// RoutedSubnets.\n\tAllowedIPs []string `json:\"allowed_ips\"`\n\tPSK        string   `json:\"psk\"`\n\t// RoutedSubnets are the subnets of the peer's routed_subnets this node\n\t// accepted that are no shared subnet, in the list's order, followed by\n\t// the shared subnets the peer holds, sorted by address and then by\n\t// prefix length, and nil when there are none. The WireGuard manager\n\t// routes each of them through the mesh interface.\n\tRoutedSubnets []string `json:\"routed_subnets,omitempty\"`\n}\n```\nPeer is the internal WireGuard programming shape built by peerFromSnapshot.\n\n```go\ntype PolicyRevisionRef struct {\n\tPolicyID   string `json:\"policy_id\"`\n\tRevisionID string `json:\"revision_id\"`\n}\n```\nPolicyRevisionRef names one revision of one Policy. Both ids are UUIDs that plexd passes through as strings.\n\n```go\ntype PolicyRule struct {\n\tProtocol        string     `json:\"protocol\"`\n\tSourceCIDR      string     `json:\"source_cidr\"`\n\tDestinationCIDR string     `json:\"destination_cidr\"`\n\tPorts           *PortRange `json:\"ports,omitempty\"`\n\tLog             bool       `json:\"log,omitempty\"`\n\t// LegacyAction is the action key of the format before\n\t// plexsphere/plexsphere#1058; nil when the key is absent. The engine reads\n\t// a rule carrying \"allow\" as an allow and rejects any other value, so a\n\t// control plane that still sends deny rules cannot have them enforced as\n\t// allows.\n\tLegacyAction *string `json:\"action,omitempty\"`\n}\n```\nPolicyRule allows the traffic from SourceCIDR to DestinationCIDR that its protocol and port range match. Both prefixes are IPv4 or both IPv6. Ports is present iff Protocol is tcp or udp and is absent for icmp/any. Log asks for the rule's traffic to be logged.\n\n```go\ntype PolicySnapshot struct {\n\tRevisionID  string       `json:\"revision_id\"`\n\tFingerprint string       `json:\"fingerprint\"`\n\tRules       []PolicyRule `json:\"rules\"`\n\t// Revisions names the (Policy, revision) pair of every compiled row the\n\t// block merges, in ascending policy_id, the order Fingerprint covers. A\n\t// control plane before plexsphere/plexsphere#1059 sends none. plexd echoes\n\t// the pairs in its policy status report and never parses them.\n\tRevisions []PolicyRevisionRef `json:\"revisions,omitempty\"`\n}\n```\nPolicySnapshot is the single merged policy block. Every rule is an allow and rule order carries no meaning: traffic no rule allows is dropped. Fingerprint is a 44-char base64 SHA-256 over the server's canonical rule byte stream; plexd treats it as an opaque comparison key and never re-derives it from Rules.\n\n```go\nfunc (p *PolicySnapshot) Clone() *PolicySnapshot\n```\nClone returns a deep copy of p: its Rules, each rule's Ports and LegacyAction, and its Revisions share no memory with p. A nil p yields nil.\n\n```go\ntype PolicyStatusApplied struct {\n\tFingerprint string              `json:\"fingerprint,omitempty\"`\n\tRevisions   []PolicyRevisionRef `json:\"revisions\"`\n}\n```\nPolicyStatusApplied echoes the policy block a node applied. Fingerprint is empty, and so absent on the wire, when the pull carried policy: null. Revisions is required; ReportPolicyStatus sends a nil one as \\[].\n\n```go\ntype PolicyStatusDrops struct {\n\tPackets int64 `json:\"packets\"`\n\tBytes   int64 `json:\"bytes\"`\n}\n```\nPolicyStatusDrops counts what the node's default deny dropped since its agent last installed the ruleset. A counter below its previous report tells the control plane that the count restarted.\n\n```go\ntype PolicyStatusRejected struct {\n\tFingerprint string              `json:\"fingerprint\"`\n\tRevisions   []PolicyRevisionRef `json:\"revisions\"`\n\tReason      string              `json:\"reason\"`\n}\n```\nPolicyStatusRejected echoes the policy block a node's latest apply failed on, and why. Every member is required; ReportPolicyStatus sends a nil Revisions as \\[]. Reason holds 1 to 1024 bytes of UTF-8 without control characters.\n\n```go\ntype PolicyStatusRequest struct {\n\t// Enforcement is one of the PolicyEnforcement* constants.\n\tEnforcement string `json:\"enforcement\"`\n\t// Applied is the ruleset the node applied last; nil when it applied none\n\t// since its agent started.\n\tApplied *PolicyStatusApplied `json:\"applied,omitempty\"`\n\t// Rejected is the ruleset the node's latest apply failed on; nil when the\n\t// latest apply did not fail.\n\tRejected *PolicyStatusRejected `json:\"rejected,omitempty\"`\n\t// Drops are the default deny's counters; nil when the firewall backend\n\t// does not count drops.\n\tDrops *PolicyStatusDrops `json:\"drops,omitempty\"`\n}\n```\nPolicyStatusRequest is the body of PUT /v1/nodes/{node\\_id}/policy-status: what the node did with the policy block of its pulls. The control plane decodes it with unknown members refused, refuses a missing or null required member with 400 invalid\\_policy\\_status, and a member of the wrong JSON type with 400 malformed\\_policy\\_status.\n\n```go\ntype PolicyStatusResponse struct {\n\t// AcceptedAt is the server receive time the report is stored with.\n\tAcceptedAt time.Time `json:\"accepted_at\"`\n\t// Status is the policy status the report derives against the ruleset the\n\t// pull serves: applied, pending, rejected or not_enforced.\n\tStatus string `json:\"status\"`\n}\n```\nPolicyStatusResponse is the 200 body of PUT /v1/nodes/{node\\_id}/policy-status.\n\n```go\ntype PollFunc func(ctx context.Context) error\n```\nPollFunc is called during polling fallback to fetch full state.\n\n```go\ntype PortRange struct {\n\tFrom int `json:\"from\"`\n\tTo   int `json:\"to\"`\n}\n```\nPortRange is a single inclusive destination port range (from \\\u003c= to).\n\n```go\ntype ReachabilitySnapshot struct {\n\tState           string     `json:\"state\"`\n\tLastHeartbeatAt *time.Time `json:\"last_heartbeat_at,omitempty\"`\n\tChangedAt       time.Time  `json:\"changed_at\"`\n}\n```\nReachabilitySnapshot is the interior of the snapshot's reachability block: the control plane's own verdict about this node, derived from the heartbeats it has admitted. It is a diagnostic projection, never desired state.\n\nState is a plain string and is never validated against the constants below. The verdict vocabulary belongs to the control plane and grows there — never\\_reported was added after plexd shipped — so a value this build does not know must keep flowing to the log rather than be rejected. LastHeartbeatAt is absent until the first heartbeat is accepted; ChangedAt is always present.\n\n```go\ntype ReconcileTrigger interface {\n\tTriggerReconcile()\n}\n```\nReconcileTrigger requests a full state reconcile. \\*reconcile.Reconciler satisfies it.\n\n```go\ntype ReconnectEngine struct {\n\t// contains filtered or unexported fields\n}\n```\nReconnectEngine manages SSE reconnection with backoff and polling fallback.\n\n```go\nfunc NewReconnectEngine(logger *slog.Logger) *ReconnectEngine\n```\nNewReconnectEngine creates a new ReconnectEngine with default settings.\n\n```go\nfunc (r *ReconnectEngine) Mode() DeliveryMode\n```\nMode returns the delivery mode currently reported by the engine.\n\n```go\nfunc (r *ReconnectEngine) Run(ctx context.Context, connectFn ConnectFunc, pollFn PollFunc) error\n```\nRun is the main state machine loop that manages SSE reconnection.\n\nStates: Connecting -\u003e Connected | Backoff\n\n\tBackoff -\u003e Connecting | Polling\n\tPolling -\u003e Connecting (periodic SSE retry)\n\nContext cancellation exits from any state.\n\n```go\nfunc (r *ReconnectEngine) SetBaseInterval(d time.Duration)\n```\nSetBaseInterval updates the base backoff interval. This is called when the SSE retry: field is received from the server.\n\n```go\nfunc (r *ReconnectEngine) SetClock(c Clock)\n```\nSetClock sets a custom clock implementation for testing.\n\n```go\nfunc (r *ReconnectEngine) SetIntervals(base, max time.Duration)\n```\nSetIntervals configures the base and max backoff intervals and resets the current interval to the new base. Useful for testing with fast intervals.\n\n```go\nfunc (r *ReconnectEngine) SetOnModeChange(fn func(DeliveryMode))\n```\nSetOnModeChange sets the callback invoked on every delivery-mode transition. The callback is fired outside the engine's lock and may be nil.\n\n```go\nfunc (r *ReconnectEngine) SetPollInterval(d time.Duration)\n```\nSetPollInterval sets how often to poll during polling fallback mode.\n\n```go\nfunc (r *ReconnectEngine) SetPollingFallbackConfig(fallbackAfter, pollInterval time.Duration)\n```\nSetPollingFallbackConfig configures when to enter polling mode and how often to poll.\n\n```go\nfunc (r *ReconnectEngine) SetReprobeInterval(d time.Duration)\n```\nSetReprobeInterval sets how often pull-only mode re-probes the SSE endpoint. A non-positive duration is ignored.\n\n```go\ntype RegisterPeer struct {\n\tNodeID           string `json:\"node_id\"`\n\tMeshIP           string `json:\"mesh_ip\"`\n\tPublicKey        string `json:\"public_key\"`\n\tFallbackEndpoint string `json:\"fallback_endpoint,omitempty\"`\n}\n```\nRegisterPeer is the initial peer snapshot entry returned by POST /v1/register. It is deliberately narrow: it carries NO psk, allowed\\_ips, or endpoint. The reconciliation peer shape is SnapshotPeer.\n\n```go\ntype RegisterRequest struct {\n\tProjectID           string `json:\"project_id\"`\n\tResourceHandle      string `json:\"resource_handle\"`\n\tBootstrapToken      string `json:\"bootstrap_token\"`\n\tNonce               string `json:\"nonce\"`\n\tPublicKey           string `json:\"public_key\"`\n\tRequestedResourceID string `json:\"requested_resource_id,omitempty\"`\n}\n```\n\n```go\ntype RegisterResponse struct {\n\tNodeID           string         `json:\"node_id\"`\n\tMeshIP           string         `json:\"mesh_ip\"`\n\tSigningPublicKey string         `json:\"signing_public_key\"`\n\tSigningKeyID     string         `json:\"signing_key_id\"`\n\tNSK              string         `json:\"nsk\"`\n\tPeerSnapshot     []RegisterPeer `json:\"peer_snapshot\"`\n\tDomainMeshCIDR   string         `json:\"domain_mesh_cidr\"`\n}\n```\n\n```go\ntype RelayAssignment struct {\n\tPeerNodeID           string `json:\"peer_node_id\"`\n\tFallbackEndpoint     string `json:\"fallback_endpoint\"`\n\tFallbackEndpointPort int    `json:\"fallback_endpoint_port\"`\n}\n```\nRelayAssignment is one entry of RelayConfig.Assignments: a peer whose fallback names this bridge, and the fallback that peer dials.\n\n```go\ntype RelayConfig struct {\n\tEnabled     bool              `json:\"enabled\"`\n\tListenPort  int               `json:\"listen_port\"`\n\tAssignments []RelayAssignment `json:\"assignments\"`\n}\n```\nRelayConfig is the bridge.relay block of the state pull, the control plane's NodeStateBridgeRelay. When Enabled is true and local consent (bridge.relay\\_enabled) allows it, the bridge relays WireGuard on UDP ListenPort among the peers the same pull lists. Assignments is carried as the control plane sends it, and the relay does not read it.\n\n```go\ntype RelayStatusRequest struct {\n\t// State is one of the RelayState* constants.\n\tState string `json:\"state\"`\n\t// ListenPort is the relay's UDP port, in 1..65535. It stays a plain int:\n\t// 0 is never a valid port, and the two states that forbid the member leave\n\t// it 0, so omitempty drops it exactly where it must be absent.\n\tListenPort int `json:\"listen_port,omitempty\"`\n\t// BoundSeconds is the whole seconds since the relay socket was bound, in\n\t// 0..MaxRelayStatusBoundSeconds. It is a pointer because 0 is a valid\n\t// value, for a socket bound less than a second ago: a plain int64 with\n\t// omitempty would drop it, and the control plane would refuse the running\n\t// report with 400 invalid_relay_status. nil omits the member, as every\n\t// state but running requires.\n\tBoundSeconds *int64 `json:\"bound_seconds,omitempty\"`\n}\n```\nRelayStatusRequest is the body of PUT /v1/nodes/{node\\_id}/relay-status: the state of the bridge's relay as the node reports it. ListenPort accompanies running and bind\\_failed, BoundSeconds only running. A member the state requires or forbids is refused with 400 invalid\\_relay\\_status, and an out-of-range value or a null member with 400 malformed\\_relay\\_status. The handler decodes with DisallowUnknownFields, so the struct carries the contract's fields and nothing else.\n\nThe control plane anchors BoundSeconds on its own receive time, so a body is only true for the attempt it was assembled for, and the agent builds a fresh one for every attempt.\n\n```go\ntype RelayStatusResponse struct {\n\t// AcceptedAt is the server receive time BoundSeconds was anchored on.\n\tAcceptedAt time.Time `json:\"accepted_at\"`\n}\n```\nRelayStatusResponse is the 200 body of PUT /v1/nodes/{node\\_id}/relay-status.\n\n```go\ntype RetryCallback func(interval time.Duration)\n```\nRetryCallback is called when the SSE server sends a retry: field.\n\n```go\ntype SSEEvent struct {\n\tType string // from \"event:\" field, defaults to \"message\"\n\tData string // concatenated data fields\n\tID   string // from \"id:\" field\n}\n```\nSSEEvent represents a single parsed SSE event.\n\n```go\ntype SSEManager struct {\n\t// contains filtered or unexported fields\n}\n```\nSSEManager is the top-level orchestrator that wires SSEStream, ReconnectEngine, EventVerifier, and EventDispatcher together.\n\n```go\nfunc NewSSEManager(client *ControlPlane, verifier EventVerifier, logger *slog.Logger) *SSEManager\n```\nNewSSEManager creates a new SSEManager. If verifier is nil, NoOpVerifier is used.\n\n```go\nfunc (m *SSEManager) Mode() DeliveryMode\n```\nMode returns the delivery mode currently reported by the reconnect engine.\n\n```go\nfunc (m *SSEManager) RegisterHandler(eventType string, handler EventHandler)\n```\nRegisterHandler adds a handler for the given event type. Must be called before Start.\n\n```go\nfunc (m *SSEManager) SetIdleTimeout(d time.Duration)\n```\nSetIdleTimeout sets the SSE idle timeout used for connections opened by Start. A zero duration falls back to DefaultSSEIdleTimeout.\n\n```go\nfunc (m *SSEManager) SetOnModeChange(fn func(DeliveryMode))\n```\nSetOnModeChange registers a callback invoked on every delivery-mode transition. The callback may be nil.\n\n```go\nfunc (m *SSEManager) SetPollFunc(fn PollFunc)\n```\nSetPollFunc sets the function called during polling fallback to fetch full state.\n\n```go\nfunc (m *SSEManager) SetPollingFallback(fallbackAfter, pollInterval time.Duration)\n```\nSetPollingFallback configures when to enter polling mode and how often to poll.\n\n```go\nfunc (m *SSEManager) SetReconcileTrigger(t ReconcileTrigger)\n```\nSetReconcileTrigger sets the trigger fired once after every successful SSE connect so the client covers replay gaps with a full reconcile pull. A nil trigger disables the pull.\n\n```go\nfunc (m *SSEManager) SetReconnectIntervals(base, max time.Duration)\n```\nSetReconnectIntervals configures the base and max backoff intervals. Useful for testing with fast intervals.\n\n```go\nfunc (m *SSEManager) SetReprobeInterval(d time.Duration)\n```\nSetReprobeInterval sets how often pull-only mode re-probes the SSE endpoint. It delegates to the reconnect engine.\n\n```go\nfunc (m *SSEManager) Shutdown()\n```\nShutdown gracefully stops the manager by cancelling its context.\n\n```go\nfunc (m *SSEManager) Start(ctx context.Context, nodeID string) error\n```\nStart begins the SSE connection loop with automatic reconnection. It blocks until the context is cancelled, Shutdown is called, or a permanent error occurs.\n\n```go\ntype SSEParser struct {\n\t// contains filtered or unexported fields\n}\n```\nSSEParser reads from an io.Reader and emits parsed SSE events.\n\n```go\nfunc NewSSEParser(r io.Reader) *SSEParser\n```\nNewSSEParser creates a parser reading from the given reader.\n\n```go\nfunc (p *SSEParser) LastEventID() string\n```\nLastEventID returns the most recently received event ID.\n\n```go\nfunc (p *SSEParser) Next() (SSEEvent, bool)\n```\nNext reads lines until a complete event is found. Returns the event and true, or a zero event and false when the reader is exhausted.\n\n```go\nfunc (p *SSEParser) SetRetryCallback(cb RetryCallback)\n```\nSetRetryCallback sets the function called when a retry: field is received.\n\n```go\ntype SSEStream struct {\n\t// contains filtered or unexported fields\n}\n```\nSSEStream connects to the SSE endpoint, parses events, verifies envelopes, and dispatches them to registered handlers.\n\n```go\nfunc NewSSEStream(client *ControlPlane, verifier EventVerifier, dispatcher *EventDispatcher, idleTimeout time.Duration, logger *slog.Logger) *SSEStream\n```\nNewSSEStream creates a new SSEStream.\n\n```go\nfunc (s *SSEStream) Connect(ctx context.Context, nodeID string) error\n```\nConnect establishes the SSE connection and processes events until the connection drops or context is cancelled. Returns nil when the connection closes cleanly, or an error.\n\n```go\nfunc (s *SSEStream) LastEventID() string\n```\nLastEventID returns the last received event ID (for reconnection).\n\n```go\nfunc (s *SSEStream) SetOnConnected(fn func())\n```\nSetOnConnected registers a hook invoked once after every ConnectSSE that returns HTTP 200, before the parse loop begins.\n\n```go\ntype SSHActivity struct {\n\tCommand          string     `json:\"command,omitempty\"`\n\tExitCode         *int       `json:\"exit_code,omitempty\"`\n\tStartedAt        *time.Time `json:\"started_at,omitempty\"`\n\tCompletedAt      *time.Time `json:\"completed_at,omitempty\"`\n\tPhase            string     `json:\"phase,omitempty\"`\n\tListenerEndpoint string     `json:\"listener_endpoint,omitempty\"`\n\tTerminatedBy     string     `json:\"terminated_by,omitempty\"`\n}\n```\nSSHActivity records one row of an SSH session. It takes one of two shapes.\n\nA command row carries Command, the command line of an exec request, capped at 1 KiB, optionally with ExitCode, StartedAt and CompletedAt (RFC 3339 timestamps). plexd posts it twice per command: once with StartedAt before the command runs, and once with ExitCode and CompletedAt after it exited.\n\nA lifecycle row carries Phase, one of the SSHPhase\\* values, plus TerminatedBy (one of the TerminatedBy\\* values) on session\\_ended, and no command fields. An ssh session binds no listener, so plexd sends no ListenerEndpoint; the field stays for the session\\_started rows older agents post with one, which the control plane still admits.\n\nplexd never posts an empty Command; the control plane refuses a row that mixes the two shapes.\n\n```go\ntype SecretEnvelope struct {\n\tData    []byte\n\tVersion int\n\tKID     string\n}\n```\nSecretEnvelope is the raw AES-256-GCM envelope served by GET /v1/nodes/{id}/secrets/{name}: Data is \\\u003c12-byte nonce\u003e || \\\u003cciphertext + 16-byte GCM tag\u003e, Version and KID come from the X-Plexsphere-Secret-Version and X-Plexsphere-Secret-KID headers. It is parsed from headers and body, never from JSON.\n\n```go\ntype SecretRef struct {\n\tKey     string `json:\"key\"`\n\tVersion int    `json:\"version\"`\n}\n```\nSecretRef is one entry of the local node API's secret index, the list GET /v1/state/secrets serves. It is fed from the NodeStateSecret entries of the state pull, whose name becomes Key.\n\n```go\ntype SessionActivityRequest struct {\n\tSSH *SSHActivity `json:\"ssh,omitempty\"`\n\tK8s *K8sActivity `json:\"k8s,omitempty\"`\n\tTCP *TCPActivity `json:\"tcp,omitempty\"`\n}\n```\nSessionActivityRequest is the one-of activity record a node posts to POST /v1/nodes/{node\\_id}/sessions/{session\\_id}. Exactly one member is set, selecting the session kind: SSH, K8s, or TCP.\n\n```go\ntype SessionConnectRequest struct {\n\tSessionID    string    `json:\"session_id\"`\n\tConnectionID string    `json:\"connection_id\"`\n\tExpiresAt    time.Time `json:\"expires_at\"`\n}\n```\nSessionConnectRequest is the payload of the session\\_connect event: the ssh session a client attached to, the one-time id of the connection the node is asked to open for it, and the instant after which the control plane no longer accepts that connection. Its shape is the control plane's access.SessionConnectRequested event, whose event\\_id and occurred\\_at header members plexd does not read.\n\n```go\ntype SessionRevocation struct {\n\tSessionID    string    `json:\"session_id\"`\n\tJTI          string    `json:\"jti\"`\n\tRevokedAt    time.Time `json:\"revoked_at\"`\n\tRevokeReason string    `json:\"revoke_reason\"`\n}\n```\nSessionRevocation is the payload of the session\\_revoked event: the revoked session, the revoked token's jti (equal to the session id), and when and why the control plane revoked it. Its shape is the control plane's SSEEventSessionRevoked schema.\n\n```go\ntype SessionTarget struct {\n\tSSH *SessionTargetSSH `json:\"ssh,omitempty\"`\n\tK8s *SessionTargetK8s `json:\"k8s,omitempty\"`\n\tTCP *SessionTargetTCP `json:\"tcp,omitempty\"`\n}\n```\nSessionTarget is the target of a NodeStateSession. Exactly one member is set, selecting the session kind: SSH, K8s, or TCP.\n\n```go\ntype SessionTargetK8s struct {\n\tUser              string   `json:\"user\"`\n\tImpersonateGroups []string `json:\"impersonate_groups,omitempty\"`\n}\n```\nSessionTargetK8s is the target of a k8s session. User is the impersonated Kubernetes user; ImpersonateGroups are the groups impersonated alongside it.\n\n```go\ntype SessionTargetSSH struct {\n\tUser            string   `json:\"user\"`\n\tAllowedCommands []string `json:\"allowed_commands,omitempty\"`\n}\n```\nSessionTargetSSH is the target of an ssh session. User is the local account the session logs in as; AllowedCommands, when set, is the closed set of command lines the session may run.\n\n```go\ntype SessionTargetTCP struct {\n\tHost string `json:\"host\"`\n\tPort int    `json:\"port\"`\n}\n```\nSessionTargetTCP is the target of a tcp session: the host and port the node forwards the session's connections to.\n\n```go\ntype SigningKeyRotation struct {\n\tKeyID             string    `json:\"key_id\"`\n\tPublicKey         string    `json:\"public_key\"`\n\tPreviousKeyID     string    `json:\"previous_key_id\"`\n\tTransitionExpires time.Time `json:\"transition_expires\"`\n}\n```\nSigningKeyRotation is the payload of the signing\\_key\\_rotated event: the new current signing key and, optionally, the previous key id kept valid until a transition deadline. Its shape is an author-approved assumption until the platform taxonomy documents it.\n\n```go\ntype SiteToSiteConfig struct {\n\tEnabled bool               `json:\"enabled\"`\n\tTunnels []SiteToSiteTunnel `json:\"tunnels\"`\n}\n```\nSiteToSiteConfig is the bridge.site\\_to\\_site block of the state pull, the control plane's NodeStateBridgeSiteToSite: every site-to-site tunnel of the bridge Resource, ordered by slug. A bridge serves Tunnels only when Enabled is true and its local configuration does not opt out; a block with Enabled false, and an absent or null block, serve no tunnel. The block is whole: a tunnel a later pull no longer lists is torn down. A block in the shape before plexsphere/plexsphere#1107 (tunnel\\_id, remote\\_endpoint, local\\_subnets, remote\\_subnets, psk, interface\\_name, provider\\_type) decodes to tunnels without an id, which a bridge neither serves nor reports.\n\n```go\ntype SiteToSiteInfo struct {\n\tEnabled bool                   `json:\"enabled\"`\n\tTunnels []SiteToSiteTunnelInfo `json:\"tunnels,omitempty\"`\n}\n```\nSiteToSiteInfo is the site-to-site status a node publishes under the node API report key status.site-to-site: whether the last applied block enabled site-to-site tunnels, and one entry per tunnel the bridge holds, in block order.\n\n```go\ntype SiteToSiteStatusRequest struct {\n\t// State is one of the SiteToSiteState* constants.\n\tState string `json:\"state\"`\n\t// Tunnels holds one entry per reported tunnel, in the order of the pull;\n\t// nil omits the member, which the contract reads as no entries.\n\tTunnels []SiteToSiteStatusTunnel `json:\"tunnels,omitempty\"`\n}\n```\nSiteToSiteStatusRequest is the body of PUT /v1/nodes/{node\\_id}/site-to-site-status: whether the bridge's local configuration serves site-to-site tunnels, and whether each tunnel of its pull is up and answered by its remote site. The control plane keeps the latest state per node and never ages it, and refuses tunnel creates and updates on the bridge while it reads opted\\_out. The tunnel entries age after three heartbeat intervals. Each report replaces the tunnel entries of the one before it.\n\nA missing, null or unknown state, an unknown member, data after the report, more than MaxSiteToSiteStatusTunnels entries, and an entry with a malformed id or a value outside its member's rule answer 400 malformed\\_site\\_to\\_site\\_status, and so does an entry that breaks the presence rules of SiteToSiteStatusTunnel. An opted-out report with entries and an id that repeats an earlier entry answer 400 invalid\\_site\\_to\\_site\\_status. A body over 64 KiB answers 413 site\\_to\\_site\\_status\\_body\\_too\\_large.\n\n```go\ntype SiteToSiteStatusResponse struct {\n\t// AcceptedAt is the server receive time of the report.\n\tAcceptedAt time.Time `json:\"accepted_at\"`\n}\n```\nSiteToSiteStatusResponse is the 200 body of PUT /v1/nodes/{node\\_id}/site-to-site-status.\n\n```go\ntype SiteToSiteStatusTunnel struct {\n\t// ID is the tunnel's id from the pull, a UUID other than the zero UUID.\n\tID string `json:\"id\"`\n\t// Health is one of the SiteToSiteHealth* constants.\n\tHealth string `json:\"health\"`\n\t// Reason is a token of the grammar ^[a-z][a-z0-9_]{0,62}$.\n\tReason string `json:\"reason,omitempty\"`\n\t// Established says whether the remote site answers: for a wireguard\n\t// tunnel the latest handshake with the remote peer is at most 180\n\t// seconds old, for an ipsec tunnel the IKE and child security\n\t// associations stand, and for an openvpn tunnel the peer is connected.\n\t// It is a pointer because false is a value the contract requires on a\n\t// tunnel that is up, and an entry that is down must not carry it.\n\tEstablished *bool `json:\"established,omitempty\"`\n\t// PublicKey is the public half of the key of a wireguard tunnel's\n\t// interface: 44 characters of standard base64 that decode to 32 bytes.\n\tPublicKey string `json:\"public_key,omitempty\"`\n}\n```\nSiteToSiteStatusTunnel is one entry of tunnels, the control plane's SiteToSiteStatusReportTunnel. Reason is sent exactly when Health is down, Established exactly when it is up, and PublicKey only when it is up: the bridge sends it for a wireguard tunnel that is up and never for an ipsec or openvpn one. omitempty drops an empty member, so a caller leaves every member it must not send empty, and Established nil.\n\n```go\ntype SiteToSiteTunnel struct {\n\t// ID is a UUID; ValidSiteToSiteTunnelID checks it.\n\tID   string `json:\"id\"`\n\tSlug string `json:\"slug\"`\n\t// Kind is one of the SiteToSiteKind* constants.\n\tKind string `json:\"kind\"`\n\t// RemoteHost is the remote site's host name of at most 253 characters\n\t// or its IP address.\n\tRemoteHost string `json:\"remote_host\"`\n\t// RemotePort is the remote site's port, 1 to 65535.\n\tRemotePort int `json:\"remote_port\"`\n\t// AllowedSubnets are the 1 to 64 networks behind the remote site, in\n\t// CIDR notation and in the order the operator wrote them.\n\tAllowedSubnets []string `json:\"allowed_subnets\"`\n\t// ListenPort is the UDP port of a wireguard tunnel's interface.\n\tListenPort int `json:\"listen_port,omitempty\"`\n\t// RemotePublicKey is the remote site's WireGuard public key of a\n\t// wireguard tunnel: 44 characters of standard base64 that decode to 32\n\t// bytes.\n\tRemotePublicKey string `json:\"remote_public_key,omitempty\"`\n\t// AuthSecretName names the Secret that holds the tunnel's key as plain\n\t// text: the preshared key of a wireguard tunnel, absent when it uses\n\t// none, the IKE pre-shared key of an ipsec tunnel, or the static key of\n\t// an openvpn tunnel.\n\tAuthSecretName string `json:\"auth_secret_name,omitempty\"`\n}\n```\nSiteToSiteTunnel is one tunnel of the block, the control plane's NodeStateBridgeSiteToSiteTunnel. Every tunnel carries ID, Slug, Kind, RemoteHost, RemotePort and AllowedSubnets; the other members follow from its Kind: ListenPort, RemotePublicKey and an optional AuthSecretName for wireguard, AuthSecretName alone for ipsec and openvpn. No member is a private key or the value of a Secret.\n\n```go\ntype SiteToSiteTunnelInfo struct {\n\tID   string `json:\"id\"`\n\tSlug string `json:\"slug\"`\n\tKind string `json:\"kind\"`\n\t// Interface is the tunnel's link; empty while it has none.\n\tInterface string `json:\"interface,omitempty\"`\n\t// Health is one of the SiteToSiteHealth* constants.\n\tHealth string `json:\"health\"`\n\t// Reason says why a tunnel is down; empty while it is up.\n\tReason string `json:\"reason,omitempty\"`\n\t// Established says whether the remote site of a tunnel that is up\n\t// answers; it is false for a tunnel that is down.\n\tEstablished bool `json:\"established\"`\n\t// ListenPort is a wireguard tunnel's UDP port.\n\tListenPort     int      `json:\"listen_port,omitempty\"`\n\tRemoteHost     string   `json:\"remote_host\"`\n\tRemotePort     int      `json:\"remote_port\"`\n\tAllowedSubnets []string `json:\"allowed_subnets\"`\n}\n```\nSiteToSiteTunnelInfo is one tunnel of a SiteToSiteInfo.\n\n```go\ntype SnapshotPeer struct {\n\tNodeID    string `json:\"node_id\"`\n\tMeshIP    string `json:\"mesh_ip\"`\n\tPublicKey string `json:\"public_key\"`\n\t// Endpoint is the peer's direct WireGuard endpoint as host:port (an IPv6\n\t// host in brackets), the address it last reported through PUT\n\t// /v1/nodes/{node_id}/endpoint. It is absent while the peer has no fresh\n\t// observation.\n\t//\n\t// FallbackEndpoints is the peer's relays as host:port in dial order, at\n\t// most 4 by the contract: the relay of the peer's assigned bridge first,\n\t// then its standby relays. They end the dial order the WireGuard manager\n\t// tries. FallbackEndpoint is the first entry, and the only relay a\n\t// control plane that predates the set sends. Both are absent while the\n\t// peer has no relay, and the list never names this node.\n\tEndpoint          string   `json:\"endpoint,omitempty\"`\n\tFallbackEndpoint  string   `json:\"fallback_endpoint,omitempty\"`\n\tFallbackEndpoints []string `json:\"fallback_endpoints,omitempty\"`\n\t// EndpointCandidates are the peer's endpoint candidates as host:port\n\t// strings, at most MaxEndpointCandidates. The control plane lists first\n\t// the peer's peer-observed endpoints: each address and port at which at\n\t// least two live nodes of the Domain reported, through\n\t// POST /v1/nodes/{node_id}/handshakes, a direct handshake with the peer\n\t// within the Domain's endpoint TTL. The peer's last accepted, unexpired\n\t// local candidates (PUT /v1/nodes/{node_id}/endpoint-candidates) follow,\n\t// in the order the peer sent them. The wire does not mark which entry is\n\t// which, and plexd orders them alike. The field is absent when the peer\n\t// has none, and on every control plane that does not deliver them.\n\tEndpointCandidates []string `json:\"endpoint_candidates,omitempty\"`\n\t// RoutedSubnets are the IPv4 networks the control plane routes through\n\t// the peer as CIDRs: the networks behind the site-to-site tunnels of a\n\t// peer that is a bridge. A node adds the ones it accepts to the peer's\n\t// allowed IPs and routes them through the mesh interface, except a\n\t// subnet the pull's shared_subnets names, which the node takes from\n\t// that block and routes through one of its bridges. The field is\n\t// absent for a peer that routes no network, and the registration\n\t// response never carries it.\n\tRoutedSubnets []string `json:\"routed_subnets,omitempty\"`\n}\n```\nSnapshotPeer is a reconciliation peer entry in NodeStateSnapshot. It is a separate type from RegisterPeer (one Go type per contract schema) and carries the peer's direct endpoint but NO psk or allowed\\_ips: AllowedIPs are derived locally as mesh\\_ip/32 followed by the entries of RoutedSubnets the node accepts, and the pairwise edge PSK is fetched per edge from GET /v1/nodes/{node\\_id}/peers/{peer\\_node\\_id}/psk, never projected.\n\n```go\ntype StateEntry struct {\n\tKey         string `json:\"key\"`\n\tValue       string `json:\"value\"`\n\tWorkloadTag string `json:\"workload_tag,omitempty\"`\n}\n```\nStateEntry is a single state entry. Value is an opaque string; WorkloadTag is absent/empty when the entry is unattributed.\n\n```go\ntype TCPActivity struct {\n\tPhase            string `json:\"phase\"`\n\tTargetHost       string `json:\"target_host,omitempty\"`\n\tTargetPort       int    `json:\"target_port,omitempty\"`\n\tListenerEndpoint string `json:\"listener_endpoint,omitempty\"`\n\tBytesIn          *int64 `json:\"bytes_in,omitempty\"`\n\tBytesOut         *int64 `json:\"bytes_out,omitempty\"`\n\tTerminatedBy     string `json:\"terminated_by,omitempty\"`\n}\n```\nTCPActivity records a TCP session lifecycle event. Phase is one of the TCPPhase\\* values. ListenerEndpoint is the node's bound listener address and is set only on session\\_started rows. BytesIn (operator to target) and BytesOut (target to operator) are pointers so a session\\_ended row carries explicit zeros while a session\\_started row omits the byte counters. TerminatedBy, when set, is one of the TerminatedBy\\* values. A session\\_active row carries Phase alone.\n\n```go\ntype UserAccessConfig struct {\n\tEnabled   bool                 `json:\"enabled\"`\n\tProviders []UserAccessProvider `json:\"providers\"`\n}\n```\nUserAccessConfig is the bridge.user\\_access block of the state pull, the control plane's NodeStateBridgeUserAccess: every user access provider of the bridge Resource, ordered by slug. A bridge serves Providers only when Enabled is true and its local configuration does not opt out; a block with Enabled false, and an absent or null block, serve no provider. The block is whole: a provider a later pull no longer lists is torn down. A block in the shape before plexsphere/plexsphere#1108 (interface\\_name, listen\\_port, peers) decodes to no providers.\n\n```go\ntype UserAccessDevice struct {\n\tID        string `json:\"id\"`\n\tSlug      string `json:\"slug\"`\n\tPublicKey string `json:\"public_key\"`\n\tAddress   string `json:\"address\"`\n}\n```\nUserAccessDevice is one device of a wireguard provider, the control plane's NodeStateBridgeUserAccessDevice: a WireGuard peer of the provider's interface with PublicKey, and Address as its one allowed IP, a /32.\n\n```go\ntype UserAccessInfo struct {\n\tEnabled   bool                     `json:\"enabled\"`\n\tProviders []UserAccessProviderInfo `json:\"providers,omitempty\"`\n}\n```\nUserAccessInfo is the user access status a node publishes under the node API report key status.user-access: whether the last applied block enabled user access, and one entry per provider the bridge holds, in block order.\n\n```go\ntype UserAccessProvider struct {\n\t// ID is a UUID; ValidUserAccessProviderID checks it.\n\tID   string `json:\"id\"`\n\tSlug string `json:\"slug\"`\n\t// Kind is one of the UserAccessKind* constants.\n\tKind string `json:\"kind\"`\n\t// ListenPort is the UDP port of a wireguard provider's interface.\n\tListenPort int `json:\"listen_port,omitempty\"`\n\t// AddressPool is the IPv4 network, in CIDR notation, a wireguard\n\t// provider's interface and devices take their addresses from. The\n\t// interface takes the first host address with the pool's prefix length.\n\tAddressPool string `json:\"address_pool,omitempty\"`\n\t// MaxDevices is the most devices a wireguard provider admits. The control\n\t// plane holds the ceiling; the bridge does not enforce it.\n\tMaxDevices int `json:\"max_devices,omitempty\"`\n\t// Devices are the devices a wireguard provider admits.\n\tDevices []UserAccessDevice `json:\"devices,omitempty\"`\n\t// AuthSecretName names the Secret that holds the key a tailscale or\n\t// netbird provider joins with, a Tailscale auth key or a NetBird setup\n\t// key as plain text.\n\tAuthSecretName string `json:\"auth_secret_name,omitempty\"`\n}\n```\nUserAccessProvider is one provider of the block, the control plane's NodeStateBridgeUserAccessProvider. It carries the members of its Kind and no others: ListenPort, AddressPool, MaxDevices and Devices for wireguard, AuthSecretName for tailscale and netbird.\n\n```go\ntype UserAccessProviderInfo struct {\n\tID   string `json:\"id\"`\n\tSlug string `json:\"slug\"`\n\tKind string `json:\"kind\"`\n\t// Interface is the provider's network interface; empty while it has none.\n\tInterface string `json:\"interface,omitempty\"`\n\t// Health is one of the UserAccessHealth* constants.\n\tHealth string `json:\"health\"`\n\t// Reason says why a provider is down; empty while it is up.\n\tReason string `json:\"reason,omitempty\"`\n\t// ListenPort is a wireguard provider's UDP port.\n\tListenPort int `json:\"listen_port,omitempty\"`\n\t// Devices counts the devices configured on a wireguard provider's\n\t// interface.\n\tDevices int `json:\"devices\"`\n\t// ConnectedDevices counts those of them with a recent handshake.\n\tConnectedDevices int `json:\"connected_devices\"`\n}\n```\nUserAccessProviderInfo is one provider of a UserAccessInfo.\n\n```go\ntype UserAccessStatusProvider struct {\n\t// ID is the provider's id from the pull, a UUID other than the zero UUID.\n\tID string `json:\"id\"`\n\t// Health is one of the UserAccessHealth* constants.\n\tHealth string `json:\"health\"`\n\t// Reason is a token of the grammar ^[a-z][a-z0-9_]{0,62}$.\n\tReason string `json:\"reason,omitempty\"`\n\t// PublicKey is the public half of the key of a wireguard provider's\n\t// interface: 44 characters of standard base64 that decode to 32 bytes.\n\tPublicKey string `json:\"public_key,omitempty\"`\n\t// ConnectedDevices is the number of the provider's devices whose latest\n\t// WireGuard handshake is at most 180 seconds old, in 0..1024. It is a\n\t// pointer because 0 is a valid count, for a provider no device reaches.\n\tConnectedDevices *int `json:\"connected_devices,omitempty\"`\n}\n```\nUserAccessStatusProvider is one entry of providers, the control plane's UserAccessStatusReportProvider. Reason is sent exactly when Health is down; PublicKey and ConnectedDevices only when it is up, and the bridge sends both for a wireguard provider that is up and neither for a vendor one. omitempty drops an empty member, so a caller leaves every member it must not send empty.\n\n```go\ntype UserAccessStatusRequest struct {\n\t// State is one of the UserAccessState* constants.\n\tState string `json:\"state\"`\n\t// Providers holds one entry per reported provider, in the order of the\n\t// pull; nil omits the member, which the contract reads as no entries.\n\tProviders []UserAccessStatusProvider `json:\"providers,omitempty\"`\n}\n```\nUserAccessStatusRequest is the body of PUT /v1/nodes/{node\\_id}/user-access-status: whether the bridge's local configuration serves user access, and whether each user access provider of its pull is up. The control plane keeps the latest state per node and never ages it, and refuses provider creates and updates and device admissions on the bridge while it reads opted\\_out. The provider entries age after three heartbeat intervals. Each report replaces the provider entries of the one before it.\n\nA missing, null or unknown state, an unknown member, data after the report, more than MaxUserAccessStatusProviders entries, and an entry with a malformed id or a value outside its member's rule answer 400 malformed\\_user\\_access\\_status, and so does an entry that breaks the presence rules of UserAccessStatusProvider. An opted-out report with entries and an id that repeats an earlier entry answer 400 invalid\\_user\\_access\\_status. A body over 64 KiB answers 413 user\\_access\\_status\\_body\\_too\\_large.\n\n```go\ntype UserAccessStatusResponse struct {\n\t// AcceptedAt is the server receive time of the report.\n\tAcceptedAt time.Time `json:\"accepted_at\"`\n}\n```\nUserAccessStatusResponse is the 200 body of PUT /v1/nodes/{node\\_id}/user-access-status.\n\n","path":"github.com/plexsphere/plexd/internal/api","name":"api","synopsis":"","isRedistributable":true}
