{"modulePath":"github.com/plexsphere/plexd","version":"v0.41.0","isLatest":true,"isStandardLibrary":false,"goos":"linux","goarch":"amd64","docs":"# package nodeapi\n\n## Constants\n\n```go\nconst DefaultDebouncePeriod = 5 * time.Second\n```\nDefaultDebouncePeriod is the default debounce period.\n\n```go\nconst DefaultHTTPListen = \"127.0.0.1:9100\"\n```\nDefaultHTTPListen is the default HTTP listen address.\n\n```go\nconst DefaultShutdownTimeout = 5 * time.Second\n```\nDefaultShutdownTimeout is the default graceful shutdown timeout.\n\n## Variables\n\n```go\nvar (\n\t// ErrVersionConflict is returned when an optimistic locking check fails.\n\tErrVersionConflict = errors.New(\"nodeapi: version conflict\")\n\t// ErrNotFound is returned when the requested entry does not exist.\n\tErrNotFound = errors.New(\"nodeapi: not found\")\n)\n```\n\n```go\nvar DefaultSocketPath = paths.SocketPath()\n```\nDefaultSocketPath is the default address of the local API listener. It is resolved per platform (a Unix socket path, or the named pipe \\`\\\\\\\\.\\\\pipe\\\\plexd\\` on Windows), which is why it is a var rather than a const.\n\n## Functions\n\n```go\nfunc BearerAuthMiddleware(token string) func(http.Handler) http.Handler\n```\nBearerAuthMiddleware returns middleware that validates Bearer token authentication. Requests without a valid token receive 401 Unauthorized. Unix socket requests bypass this middleware (it is only applied to the TCP listener).\n\n```go\nfunc DecryptSecret(nsk []byte, envelope []byte) (string, error)\n```\nDecryptSecret opens the raw AES-256-GCM envelope \\\u003c12-byte nonce\u003e || \\\u003cciphertext + 16-byte GCM tag\u003e under the NSK. The NSK (node secret key) must be exactly 32 bytes. Returns a generic error on every failure to avoid leaking cryptographic details.\n\n```go\nfunc DialLocal(ctx context.Context, path string) (net.Conn, error)\n```\nDialLocal connects to the local node API listener at path.\n\n```go\nfunc ListenLocal(path string, logger *slog.Logger) (net.Listener, error)\n```\nListenLocal opens the local node API listener: a Unix domain socket at path. It drops a socket file an earlier run left behind, creates the socket directory, and applies the platform's socket ownership and mode.\n\n```go\nfunc SecretAuthMiddleware(policy SecretPolicy, getter PeerCredGetter, logger *slog.Logger) func(http.Handler) http.Handler\n```\nSecretAuthMiddleware returns HTTP middleware that restricts the secret endpoints to the peers the platform's SecretPolicy admits. A peer whose credentials cannot be read is denied.\n\nThe middleware takes the peer credentials of the request's underlying connection from a PeerCredGetter: contextPeerCredGetter in production, a mock in tests.\n\n```go\nfunc SetSocketPermissions(socketPath string, logger *slog.Logger) error\n```\nSetSocketPermissions sets ownership and permissions on the Unix socket file. If the plexd group exists and the daemon may hand the socket to it, the socket is chowned to root:plexd with mode 0660. Otherwise the socket is narrowed to mode 0600 and a warning is logged.\n\nThe fallback narrows rather than widens because opening the socket is the whole authorization for every route but the secret ones: the mux serves POST /v1/actions/run, POST /v1/hooks/reload and the report writes to any peer that connects, and the daemon runs those as root. Only deploy/install.sh creates the group, and only on Linux, so the fallback is the default state on every other install path.\n\n## Types\n\n```go\ntype ActionProvider interface {\n\tCapabilities() ([]api.ActionInfo, []api.HookInfo)\n}\n```\nActionProvider supplies action and hook information to the local API.\n\n```go\ntype Config struct {\n\t// SocketPath is the address of the local API listener: a Unix socket\n\t// path, or on Windows a named pipe name (`\\\\.\\pipe\\plexd` by default).\n\t// Default: paths.SocketPath()\n\tSocketPath string `yaml:\"socket_path\"`\n\n\t// HTTPEnabled enables the optional HTTP listener.\n\t// Default: false\n\tHTTPEnabled bool `yaml:\"http_enabled\"`\n\n\t// HTTPListen is the HTTP listen address.\n\t// Default: 127.0.0.1:9100\n\tHTTPListen string `yaml:\"http_listen\"`\n\n\t// HTTPTokenFile is the path to the HTTP bearer token file.\n\tHTTPTokenFile string `yaml:\"http_token_file\"`\n\n\t// DebouncePeriod is the debounce period for coalescing events.\n\t// Default: 5s\n\tDebouncePeriod time.Duration `yaml:\"debounce_period\"`\n\n\t// ShutdownTimeout is the maximum time to wait for a graceful shutdown.\n\t// Default: 5s\n\tShutdownTimeout time.Duration `yaml:\"shutdown_timeout\"`\n\n\t// DataDir is the path to the data directory (required). It is propagated\n\t// from the top-level data_dir by AgentConfig.ApplyDefaults, not from YAML.\n\tDataDir string `yaml:\"-\"`\n\n\t// SecretAuthEnabled enables peer-credential authentication for\n\t// /v1/state/secrets/* on the local listener: SO_PEERCRED on Linux,\n\t// LOCAL_PEERCRED on macOS, the pipe client's process token on Windows.\n\t// When enabled, only a privileged local peer (root or a plexd-secrets\n\t// member on Linux and macOS; an elevated Administrator or LocalSystem on\n\t// Windows) may read secrets.\n\t// Default: false (enabled by cmd/plexd/cmd/up.go in production).\n\tSecretAuthEnabled bool `yaml:\"secret_auth_enabled\"`\n}\n```\nConfig holds the configuration for the local node API server. Config is passed as a constructor argument — no file I/O in this package.\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 and values are acceptable.\n\n```go\ntype ForwarderStatus struct {\n\tEnabled      bool   `json:\"enabled\"`\n\tBufferSize   int    `json:\"buffer_size\"`\n\tSourceCount  int    `json:\"source_count\"`\n\tErrorCount   int    `json:\"error_count\"`\n\tLastReportAt string `json:\"last_report_at,omitempty\"`\n}\n```\nForwarderStatus describes the operational status of a log or audit forwarder.\n\n```go\ntype ForwarderStatusProvider interface {\n\tForwarderStatus() ForwarderStatus\n}\n```\nForwarderStatusProvider supplies forwarder status information.\n\n```go\ntype GroupChecker interface {\n\t// IsInGroup reports whether the user identified by uid belongs to the\n\t// named group, or if the user's primary group (gid) matches the group.\n\tIsInGroup(uid, gid uint32, groupName string) bool\n}\n```\nGroupChecker checks group membership for a given user.\n\n```go\ntype Handler struct {\n\t// contains filtered or unexported fields\n}\n```\nHandler provides HTTP handlers for the local node API.\n\n```go\nfunc NewHandler(cache *StateCache, secretFetcher SecretFetcher, nodeID string, nsk []byte, logger *slog.Logger) *Handler\n```\nNewHandler creates a new Handler.\n\n```go\nfunc (h *Handler) Mux() *http.ServeMux\n```\nMux returns a configured ServeMux with all local node API routes.\n\n```go\nfunc (h *Handler) SetActionProvider(provider ActionProvider)\n```\nSetActionProvider sets the action provider for action/hook endpoints.\n\n```go\nfunc (h *Handler) SetAuditStatus(p ForwarderStatusProvider)\n```\nSetAuditStatus sets the audit forwarder status provider.\n\n```go\nfunc (h *Handler) SetHookReloader(reloader HookReloader)\n```\nSetHookReloader sets the hook reloader for the reload endpoint.\n\n```go\nfunc (h *Handler) SetLogStatus(p ForwarderStatusProvider)\n```\nSetLogStatus sets the log forwarder status provider.\n\n```go\nfunc (h *Handler) SetPeerProvider(p PeerProvider)\n```\nSetPeerProvider sets the peer status provider.\n\n```go\nfunc (h *Handler) SetPolicyProvider(p PolicyProvider)\n```\nSetPolicyProvider sets the policy provider.\n\n```go\ntype HookReloader interface {\n\tReload() ([]api.HookInfo, error)\n}\n```\nHookReloader re-scans the hooks on the filesystem and returns the result.\n\n```go\ntype LocalActionRunner interface {\n\tRunLocal(ctx context.Context, action string, params map[string]string) (stdout, stderr string, exitCode int, err error)\n}\n```\nLocalActionRunner runs a built-in action synchronously and returns output.\n\n```go\ntype NodeAPIClient interface {\n\tSecretFetcher\n\tReportSyncClient\n}\n```\nNodeAPIClient combines the control plane methods needed by the node API server.\n\n```go\ntype OSGroupChecker struct{}\n```\nOSGroupChecker checks group membership using the OS user/group database.\n\n```go\nfunc (OSGroupChecker) IsInGroup(uid, gid uint32, groupName string) bool\n```\n\n```go\ntype PeerCredGetter interface {\n\tGetPeerCredentials(r *http.Request) (*PeerCredentials, error)\n}\n```\nPeerCredGetter extracts peer credentials from an HTTP request's underlying connection.\n\n```go\ntype PeerCredentials struct {\n\tPID uint32\n\tUID uint32\n\tGID uint32\n}\n```\nPeerCredentials holds the peer credentials extracted from a Unix socket connection.\n\n```go\nfunc GetPeerCredentials(conn net.Conn) (*PeerCredentials, error)\n```\nGetPeerCredentials extracts peer credentials from a Unix socket connection using the SO\\_PEERCRED socket option. Returns an error if the connection is not a Unix socket or the credentials cannot be retrieved.\n\n```go\ntype PeerProvider interface {\n\tPeerStatuses() []PeerStatus\n}\n```\nPeerProvider supplies mesh peer information.\n\n```go\ntype PeerStatus struct {\n\tID        string `json:\"id\"`\n\tPublicKey string `json:\"public_key\"`\n\tMeshIP    string `json:\"mesh_ip\"`\n\tEndpoint  string `json:\"endpoint\"`\n}\n```\nPeerStatus describes a single mesh peer's status.\n\n```go\ntype PolicyProvider interface {\n\tPolicyView() PolicyView\n}\n```\nPolicyProvider supplies what plexd did with the policy blocks it pulled.\n\n```go\ntype PolicyView struct {\n\tRevisionID  string                  `json:\"revision_id,omitempty\"`\n\tFingerprint string                  `json:\"fingerprint,omitempty\"`\n\tRules       []api.PolicyRule        `json:\"rules,omitempty\"`\n\tRevisions   []api.PolicyRevisionRef `json:\"revisions,omitempty\"`\n\tEnforcement string                  `json:\"enforcement\"`\n\tApplied     bool                    `json:\"applied\"`\n\tInSync      bool                    `json:\"in_sync\"`\n\tReceived    *PolicyViewReceived     `json:\"received,omitempty\"`\n\tRejected    *PolicyViewRejected     `json:\"rejected,omitempty\"`\n}\n```\nPolicyView is the body of GET /v1/policies: the ruleset plexd applied and how it relates to the block of the latest pull.\n\nRevisionID, Fingerprint, Rules and Revisions keep the names of the body that served the pulled block before, so a reader of that body still decodes it. They hold the applied block now, and are absent when no pull's block is applied or the applied pull carried policy: null.\n\nEnforcement is one of the api.PolicyEnforcement\\* constants, or empty before the first pull. Applied tells whether a pull's block is applied. InSync tells whether the applied block is the block of the latest pull: both null, or both with the same non-empty fingerprint. Received names the block of the latest pull and is nil when that pull carried policy: null. Rejected names the block the latest apply failed on and is nil when it did not fail.\n\n```go\ntype PolicyViewReceived struct {\n\tRevisionID  string                  `json:\"revision_id\"`\n\tFingerprint string                  `json:\"fingerprint\"`\n\tRevisions   []api.PolicyRevisionRef `json:\"revisions,omitempty\"`\n}\n```\nPolicyViewReceived names the policy block of the latest pull.\n\n```go\ntype PolicyViewRejected struct {\n\tRevisionID  string `json:\"revision_id\"`\n\tFingerprint string `json:\"fingerprint\"`\n\tReason      string `json:\"reason\"`\n\tAttempts    int    `json:\"attempts\"`\n}\n```\nPolicyViewRejected names the policy block the latest apply failed on, why it failed, and how many applies of it failed in a row.\n\n```go\ntype ReportEntry 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```\nReportEntry represents a locally-managed report entry.\n\n```go\ntype ReportSyncClient interface {\n\tPutStateReport(ctx context.Context, nodeID, key string, req api.NodeStateReportRequest) (*api.NodeStateReportResponse, error)\n\tDeleteStateReport(ctx context.Context, nodeID, key string) error\n}\n```\nReportSyncClient publishes per-key node state reports to the control plane.\n\n```go\ntype ReportSyncer struct {\n\t// contains filtered or unexported fields\n}\n```\nReportSyncer reconciles per-key report changes to the control plane. Changes are held in a dirty map keyed by report key; a nil value marks a pending delete. NotifyChange debounces to coalesce bursts, flush walks the dirty keys in ascending order publishing one at a time, and keys left dirty by a retryable failure are re-flushed on a timer so state converges without a new local mutation.\n\n```go\nfunc NewReportSyncer(client ReportSyncClient, debouncePeriod time.Duration, logger *slog.Logger) *ReportSyncer\n```\nNewReportSyncer creates a ReportSyncer. The node ID is supplied later to Run because the syncer is constructed in NewServer, before the node has registered and its ID is known.\n\n```go\nfunc (s *ReportSyncer) NotifyChange(entries []ReportEntry, deleted []string)\n```\nNotifyChange merges report changes into the dirty map and wakes the run loop. entries are pending PUTs and deleted keys are pending deletes; the last change to a given key wins.\n\n```go\nfunc (s *ReportSyncer) Run(ctx context.Context, nodeID string) error\n```\nRun reconciles report changes to the control plane for nodeID until ctx is cancelled, at which point it returns ctx.Err(). Dirty state is preserved in memory across the return so a subsequent Run resumes where this one left off.\n\n```go\ntype SecretFetcher interface {\n\tFetchSecret(ctx context.Context, nodeID, name string, version int) (*api.SecretEnvelope, error)\n}\n```\nSecretFetcher abstracts the control plane client for secret retrieval.\n\n```go\ntype SecretPolicy interface {\n\tAllowSecrets(cred *PeerCredentials) bool\n}\n```\nSecretPolicy decides whether an identified local peer may read secret values.\n\n```go\ntype Server struct {\n\t// contains filtered or unexported fields\n}\n```\nServer is the local node API server. It serves HTTP over the local listener (a Unix socket, or a named pipe on Windows) and optionally over TCP with bearer token authentication.\n\n```go\nfunc NewServer(cfg Config, client NodeAPIClient, nsk []byte, logger *slog.Logger) *Server\n```\nNewServer creates a new Server. Config defaults are applied automatically. The cache is initialized eagerly so that ReconcileHandler can be called before Start.\n\n```go\nfunc (s *Server) Cache() *StateCache\n```\nCache returns the server's state cache for use by SSE event handlers.\n\n```go\nfunc (s *Server) PublishReport(key, contentType string, payload json.RawMessage) error\n```\nPublishReport writes a report entry through the cache and notifies the syncer so it converges to the control plane. It is the seam through which internal producers publish status blocks, and it holds key and payload to the same grammar and 4096-byte value cap as the local HTTP API. content\\_type and the resulting version stay local-only; the syncer ships only the payload value.\n\n```go\nfunc (s *Server) ReconcileHandler() reconcile.ReconcileHandler\n```\nReconcileHandler returns a reconcile.ReconcileHandler that refreshes the cache from the desired state block whenever it changes. The block's metadata bucket becomes the cache metadata map, and its opaque data bucket feeds the versioned data store (GET /v1/state/data): each api.StateEntry value is JSON-encoded into an api.DataEntry payload under dataStateContentType. A nil state block authoritatively clears both buckets.\n\nThe secret index is not fed here: SecretIndexDispatchHandler replaces it from the pull's secrets block on every successful pull, drift or not.\n\n```go\nfunc (s *Server) ReportPayload(key string) (json.RawMessage, bool)\n```\nReportPayload returns the payload currently stored under key, and whether the key exists. Internal producers use it to compare what is actually published against what they would publish, so a report another local caller overwrote or deleted is re-asserted rather than assumed to still hold their last value.\n\n```go\nfunc (s *Server) SecretIndexDispatchHandler() reconcile.DispatchHandler\n```\nSecretIndexDispatchHandler returns a reconcile.DispatchHandler that feeds the secret index from the secrets block of every successful state pull, drift or not, so GET /v1/state/secrets lists the Secrets the node may read. It compares the pulled inventory with the index the cache holds, not with the last pull, so an index loaded from a file an older release wrote converges on the first pull. A nil block, which a control plane that predates it sends, keeps the index. An entry the index cannot carry is dropped and logged at Warn, once until the set of dropped entries changes. The reconcile goroutine is the only caller, one cycle at a time, so the closure's state needs no mutex.\n\n```go\nfunc (s *Server) SetActionProvider(provider ActionProvider)\n```\nSetActionProvider sets the action provider for action/hook endpoints. Must be called before Start.\n\n```go\nfunc (s *Server) SetAuditStatus(p ForwarderStatusProvider)\n```\nSetAuditStatus sets the audit forwarder status provider. Must be called before Start.\n\n```go\nfunc (s *Server) SetHookReloader(reloader HookReloader)\n```\nSetHookReloader sets the hook reloader for the reload endpoint. Must be called before Start.\n\n```go\nfunc (s *Server) SetLogStatus(p ForwarderStatusProvider)\n```\nSetLogStatus sets the log forwarder status provider. Must be called before Start.\n\n```go\nfunc (s *Server) SetPeerProvider(p PeerProvider)\n```\nSetPeerProvider sets the peer status provider. Must be called before Start.\n\n```go\nfunc (s *Server) SetPolicyProvider(p PolicyProvider)\n```\nSetPolicyProvider sets the provider of the policy view GET /v1/policies serves. Without one the route answers {}. Must be called before Start.\n\n```go\nfunc (s *Server) Start(ctx context.Context, nodeID string) error\n```\nStart initializes and runs the server. It blocks until ctx is cancelled.\n\n```go\ntype StateCache struct {\n\t// contains filtered or unexported fields\n}\n```\nStateCache holds node state in memory with file persistence.\n\n```go\nfunc NewStateCache(dataDir string, logger *slog.Logger) *StateCache\n```\nNewStateCache creates a new StateCache with empty maps. dataDir is the base path; the state subdirectory tree will be created under dataDir/state/.\n\n```go\nfunc (sc *StateCache) DeleteReport(key string) error\n```\nDeleteReport removes a report entry and its file. Returns ErrNotFound if the key does not exist.\n\n```go\nfunc (sc *StateCache) GetData() map[string]api.DataEntry\n```\nGetData returns a copy of the data map.\n\n```go\nfunc (sc *StateCache) GetDataEntry(key string) (api.DataEntry, bool)\n```\nGetDataEntry returns a data entry by key and whether it exists.\n\n```go\nfunc (sc *StateCache) GetMetadata() map[string]string\n```\nGetMetadata returns a copy of the metadata map, with the delivery-mode diagnostic overlaid as the delivery\\_mode key when a mode is set, and the control\\_plane\\_credential key overlaid as \"refused\" while the control plane refuses the node credential.\n\n```go\nfunc (sc *StateCache) GetMetadataKey(key string) (string, bool)\n```\nGetMetadataKey returns the value for a metadata key and whether it exists. The delivery\\_mode key resolves to the delivery-mode diagnostic, and the control\\_plane\\_credential key to \"refused\" while the control plane refuses the node credential.\n\n```go\nfunc (sc *StateCache) GetReport(key string) (ReportEntry, bool)\n```\nGetReport returns a report entry by key and whether it exists.\n\n```go\nfunc (sc *StateCache) GetReports() map[string]ReportEntry\n```\nGetReports returns a copy of the reports map.\n\n```go\nfunc (sc *StateCache) GetSecretIndex() []api.SecretRef\n```\nGetSecretIndex returns a copy of the secret index.\n\n```go\nfunc (sc *StateCache) Load() error\n```\nLoad reads persisted state from disk. Missing files or directories are treated as fresh (empty) state. The directory tree is created if absent.\n\n```go\nfunc (sc *StateCache) OrphanedReportKeys() []string\n```\nOrphanedReportKeys returns the keys of the persisted reports the last Load rejected as outside the current key grammar. A previous release may have synced them to the control plane, where nothing local can reach them any more, so the caller queues a delete for each.\n\n```go\nfunc (sc *StateCache) PutReport(key, contentType string, payload json.RawMessage, ifMatch *int) (ReportEntry, error)\n```\nPutReport creates or updates a report entry. If the entry exists and ifMatch is non-nil, it must equal the current version or ErrVersionConflict is returned. Version starts at 1 for new entries and increments on update.\n\n```go\nfunc (sc *StateCache) SetCredentialRefused(refused bool)\n```\nSetCredentialRefused records whether the control plane refuses the node credential. It is stored separately from the snapshot-owned metadata map and is intentionally not persisted: the heartbeat detects a refused credential again within three heartbeats of a restart, and a persisted mark would outlive a control plane that was fixed meanwhile.\n\n```go\nfunc (sc *StateCache) SetDeliveryMode(mode string)\n```\nSetDeliveryMode records the SSE delivery channel diagnostic. It is stored separately from the snapshot-owned metadata map and is intentionally not persisted: the value is re-seeded from the live SSE manager on every startup.\n\n```go\nfunc (sc *StateCache) UpdateData(entries []api.DataEntry)\n```\nUpdateData replaces data entries in memory and persists each to data/{key}.json. Files for entries no longer present are removed.\n\n```go\nfunc (sc *StateCache) UpdateMetadata(m map[string]string)\n```\nUpdateMetadata replaces the metadata in memory and persists to metadata.json.\n\n```go\nfunc (sc *StateCache) UpdateSecretIndex(refs []api.SecretRef) bool\n```\nUpdateSecretIndex replaces the secret index in memory and persists it to secrets.json, and reports whether the index changed. An index equal to the one held, with nil and empty counting as equal, changes nothing and is not written again. A failed write is logged, and the index in memory is replaced all the same.\n\n```go\ntype StateSummary struct {\n\tMetadata   map[string]string  `json:\"metadata\"`\n\tDataKeys   []dataKeySummary   `json:\"data_keys\"`\n\tSecretKeys []secretKeySummary `json:\"secret_keys\"`\n\tReportKeys []reportKeySummary `json:\"report_keys\"`\n}\n```\nStateSummary is the response for GET /v1/state.\n\n","path":"github.com/plexsphere/plexd/internal/nodeapi","name":"nodeapi","synopsis":"","isRedistributable":true}
