{"modulePath":"github.com/cloudapp3/vmflow","version":"v0.4.0","isLatest":true,"isStandardLibrary":false,"goos":"linux","goarch":"amd64","docs":"# package controlapi\n\nPackage controlapi implements vmflow's internal daemon management transport.\n\nIt exists for the bundled CLI, TUI, and bot. It is not a supported public integration API and does not provide compatibility guarantees for external callers.\n\n## Constants\n\n```go\nconst (\n\tRoleAdmin  = config.AuthRoleAdmin\n\tRoleViewer = config.AuthRoleViewer\n)\n```\n\n```go\nconst ManagementAPIVersion = \"1\"\n```\nManagementAPIVersion identifies the internal daemon management contract.\n\n## Functions\n\n```go\nfunc APIStatus(err error) int\n```\nAPIStatus returns the HTTP status embedded in err, or 0 if err is not an APIError.\n\n```go\nfunc BuildClientTLSConfig(o ClientTLSOptions) (*tls.Config, error)\n```\nBuildClientTLSConfig builds a \\*tls.Config for a control API client. MinVersion is pinned to TLS 1.2.\n\n```go\nfunc BuildServerTLSConfig(cfg config.ControlTLSConfig) (*tls.Config, error)\n```\nBuildServerTLSConfig builds a \\*tls.Config for the control API from cfg. It returns nil (plain HTTP) when neither cert nor key is configured. Setting ClientCAFile enables mutual TLS: every client must present a certificate signed by that CA.\n\n```go\nfunc CloneRules(rules []engine.Rule) []engine.Rule\n```\nCloneRules deep-copies a rule slice including nested string slices.\n\n```go\nfunc IsBotValidationError(err error) bool\n```\n\n```go\nfunc NewHTTPClient(opts ClientTLSOptions, timeout time.Duration) (*http.Client, error)\n```\nNewHTTPClient returns an \\*http.Client for talking to the control API. When no TLS option is set it returns http.DefaultClient (preserving existing behavior). A non-zero timeout applies an overall request deadline.\n\n```go\nfunc NewHandler(runtime *Runtime) http.Handler\n```\n\n```go\nfunc NormalizeETag(value string) string\n```\nNormalizeETag quotes a bare ETag value; already-quoted, weak, or wildcard values pass through unchanged.\n\n```go\nfunc SaveSetupConfig(path string, update SetupConfigUpdate) (config.File, error)\n```\nSaveSetupConfig validates and persists the language/auth/rules chosen by the first-run workflow. Existing files use the same guarded atomic replacement as live TUI rule management. A missing file is created exclusively with mode 0600.\n\n```go\nfunc SetupConfigCommitted(err error) bool\n```\nSetupConfigCommitted reports whether SaveSetupConfig reached its filesystem commit point before returning an error (for example, a later directory-sync failure). Callers must not roll back companion state in that case.\n\n## Types\n\n```go\ntype APIError struct {\n\tStatusCode int\n\tMessage    string\n\tBody       []byte\n}\n```\nAPIError preserves the HTTP status so callers can distinguish auth, validation, conflicts, and transient server failures.\n\n```go\nfunc (e *APIError) Error() string\n```\n\n```go\ntype ApplyResponse struct {\n\tRevision       string             `json:\"revision\"`\n\tWritable       bool               `json:\"writable\"`\n\tUDPMaxSessions int                `json:\"udp_max_sessions\"`\n\tRules          []engine.Rule      `json:\"rules\"`\n\tResult         engine.ApplyResult `json:\"result\"`\n\tETag           string             `json:\"-\"`\n}\n```\nApplyResponse is the PUT /v1/config/rules success payload.\n\n```go\nfunc (r *ApplyResponse) Snapshot() *ConfigRulesResponse\n```\nSnapshot builds a ConfigRulesResponse from an apply result.\n\n```go\ntype AuthInfo struct {\n\tName string `json:\"name\"`\n\tRole string `json:\"role\"`\n}\n```\nAuthInfo describes the authenticated Control API caller.\n\n```go\nfunc AuthInfoFromContext(ctx context.Context) (AuthInfo, bool)\n```\nAuthInfoFromContext returns caller auth info from a request context.\n\n```go\ntype Authenticator struct {\n\t// contains filtered or unexported fields\n}\n```\nAuthenticator validates Control API bearer tokens.\n\n```go\nfunc NewAuthenticator(cfg config.AuthConfig) *Authenticator\n```\nNewAuthenticator builds an authenticator from config.\n\n```go\nfunc (a *Authenticator) Authenticate(r *http.Request) (AuthInfo, bool)\n```\nAuthenticate validates the Authorization header and returns caller info.\n\n```go\nfunc (a *Authenticator) Enabled() bool\n```\nEnabled returns whether authentication is enforced.\n\n```go\ntype BotConfigRequest struct {\n\tBotToken        string `json:\"bot_token\"`\n\tBotChat         int64  `json:\"bot_chat\"`\n\tBotControlToken string `json:\"bot_control_token\"`\n}\n```\nBotConfigRequest is the PUT /v1/config/bot body.\n\n```go\ntype BotConfigResponse struct {\n\tRevision        string `json:\"revision\"`\n\tBotToken        string `json:\"bot_token\"`\n\tBotChat         int64  `json:\"bot_chat\"`\n\tBotControlToken string `json:\"bot_control_token\"`\n\tRunning         bool   `json:\"running\"`\n\tETag            string `json:\"-\"`\n}\n```\nBotConfigResponse is the GET /v1/config/bot payload. Tokens are plaintext (admin-only endpoint); the TUI masks them for display.\n\n```go\ntype BotController interface {\n\t// Apply stops any running bot and starts a new one with settings. If Token\n\t// or ChatID are zero, the bot is stopped and not restarted.\n\tApply(settings BotSettings) error\n\t// Stop stops the running bot without changing persisted configuration.\n\tStop() error\n\t// Running reports whether a bot goroutine is currently active.\n\tRunning() bool\n}\n```\nBotController manages the Telegram bot lifecycle at runtime, allowing the bot to be started, stopped, and reconfigured without restarting the daemon. It is implemented by the bot package and injected into Runtime so controlapi does not need to import bot (avoiding an import cycle).\n\n```go\ntype BotSettings struct {\n\tToken        string\n\tChatID       int64\n\tControlToken string\n}\n```\nBotSettings is the Telegram bot configuration managed at runtime.\n\n```go\ntype BotUnavailableError struct {\n\tErr error\n}\n```\nBotUnavailableError reports that readiness could not be established due to a transient Telegram or network failure.\n\n```go\nfunc (err *BotUnavailableError) Error() string\n```\n\n```go\nfunc (err *BotUnavailableError) Unwrap() error\n```\n\n```go\ntype BotValidationError struct {\n\tErr error\n}\n```\nBotValidationError reports bot settings that Telegram has rejected. Error is intentionally generic because low-level HTTP errors may contain the bot token in their request URL.\n\n```go\nfunc (err *BotValidationError) Error() string\n```\n\n```go\nfunc (err *BotValidationError) Unwrap() error\n```\n\n```go\ntype Client struct {\n\t// contains filtered or unexported fields\n}\n```\nClient calls vmflow's internal daemon management transport. It is shared by the bundled TUI, CLI, and Telegram bot.\n\n```go\nfunc NewClient(baseURL, token string) *Client\n```\nNewClient returns an internal management client for baseURL with the given bearer token. The token may be empty for read-only access.\n\n```go\nfunc (c *Client) Apply(ctx context.Context, match string, draft ConfigRulesRequest) (*ApplyResponse, error)\n```\nApply replaces the managed rules configuration. match is the If-Match ETag from a prior ConfigRules call (optimistic concurrency).\n\n```go\nfunc (c *Client) ApplyBotConfig(ctx context.Context, match string, req BotConfigRequest) (*BotConfigResponse, error)\n```\nApplyBotConfig updates the bot configuration (persisted to config.yaml) and restarts the bot goroutine. match is the If-Match ETag from a prior BotConfig.\n\n```go\nfunc (c *Client) BaseURL() string\n```\nBaseURL returns the internal management base URL configured for the client.\n\n```go\nfunc (c *Client) BotConfig(ctx context.Context) (*BotConfigResponse, error)\n```\nBotConfig fetches the current bot configuration and running state.\n\n```go\nfunc (c *Client) ConfigRules(ctx context.Context) (*ConfigRulesResponse, error)\n```\n\n```go\nfunc (c *Client) CurrentPrecheck(ctx context.Context) (*CurrentPrecheckResponse, error)\n```\nCurrentPrecheck validates the daemon's current on-disk configuration. HTTP 400 is a structured precheck result rather than a transport error.\n\n```go\nfunc (c *Client) HasToken() bool\n```\nHasToken reports whether the client can perform authenticated write actions.\n\n```go\nfunc (c *Client) Precheck(ctx context.Context, match string, draft ConfigRulesRequest) (*PrecheckResponse, error)\n```\nPrecheck validates exactly the supplied draft. HTTP 422 is a successful protocol response carrying validation findings, not a transport error.\n\n```go\nfunc (c *Client) Reload(ctx context.Context) (*ReloadResponse, error)\n```\nReload reloads the daemon configuration from disk.\n\n```go\nfunc (c *Client) Rules(ctx context.Context) (*RulesResponse, error)\n```\n\n```go\nfunc (c *Client) Session(ctx context.Context) (*SessionResponse, error)\n```\n\n```go\nfunc (c *Client) SetHTTPClient(h *http.Client)\n```\nSetHTTPClient replaces the HTTP client used for management requests. Pass nil to keep the default; otherwise the caller controls TLS and timeouts.\n\n```go\nfunc (c *Client) SetHeaders(h http.Header)\n```\nSetHeaders sets extra headers applied to every request. nil clears them.\n\n```go\nfunc (c *Client) StartBot(ctx context.Context) error\n```\nStartBot starts the bot using the current persisted configuration.\n\n```go\nfunc (c *Client) Stats(ctx context.Context) (*StatsResponse, error)\n```\n\n```go\nfunc (c *Client) StopBot(ctx context.Context) error\n```\nStopBot stops the running bot without changing persisted configuration.\n\n```go\ntype ClientTLSFlags struct {\n\t// contains filtered or unexported fields\n}\n```\nClientTLSFlags holds the standard control-API client TLS flags registered on a \\*flag.FlagSet. Call Opts() after parsing to get a ClientTLSOptions.\n\n```go\nfunc AddClientTLSFlags(fs *flag.FlagSet) *ClientTLSFlags\n```\nAddClientTLSFlags registers the standard control-API client TLS flags on fs (use flag.CommandLine for the legacy relay\\* binaries) and returns a handle. Each flag falls back to its VMFLOW\\_TLS\\_\\* environment variable.\n\n```go\nfunc (f *ClientTLSFlags) Opts() ClientTLSOptions\n```\nOpts returns the parsed client TLS options.\n\n```go\ntype ClientTLSOptions struct {\n\tCAFile             string // CA bundle to verify the server certificate (for private/self-signed CAs)\n\tClientCertFile     string // client certificate (required for mTLS when the server sets client_ca_file)\n\tClientKeyFile      string // client key (required together with ClientCertFile)\n\tInsecureSkipVerify bool   // skip server certificate verification (debug only)\n}\n```\nClientTLSOptions configures TLS for a control API client (vmflow ctl/tui).\n\n```go\nfunc (o ClientTLSOptions) Any() bool\n```\nAny reports whether any TLS option is set.\n\n```go\ntype ConfigRuleDiff struct {\n\tRuleID        string `json:\"rule_id\"`\n\tConfigAction  string `json:\"config_action\"`\n\tRuntimeAction string `json:\"runtime_action\"`\n}\n```\n\n```go\ntype ConfigRulesRequest struct {\n\tUDPMaxSessions int           `json:\"udp_max_sessions\"`\n\tRules          []engine.Rule `json:\"rules\"`\n}\n```\nConfigRulesRequest is the PUT /v1/config/rules body.\n\n```go\ntype ConfigRulesResponse struct {\n\tRevision       string        `json:\"revision\"`\n\tWritable       bool          `json:\"writable\"`\n\tUDPMaxSessions int           `json:\"udp_max_sessions\"`\n\tRules          []engine.Rule `json:\"rules\"`\n\tETag           string        `json:\"-\"`\n}\n```\nConfigRulesResponse is the GET /v1/config/rules payload. ETag is populated from the response ETag header (or the revision) for optimistic concurrency.\n\n```go\ntype CurrentPrecheckResponse struct {\n\tConfigPath string          `json:\"config_path,omitempty\"`\n\tRuleCount  int             `json:\"rule_count,omitempty\"`\n\tError      string          `json:\"error,omitempty\"`\n\tResult     precheck.Result `json:\"result\"`\n}\n```\nCurrentPrecheckResponse is the GET /v1/precheck payload for the daemon's current on-disk configuration. A non-empty Error reports a configuration load failure; Result still contains the corresponding structured finding.\n\n```go\ntype HeaderFlags []string\n```\nHeaderFlags is a repeatable -H/--header flag. Each entry is \"Name: Value\" or \"Name=Value\" (curl-style). It is seeded from the VMFLOW\\_HEADERS environment variable (semicolon-separated) so service tokens etc. can be supplied without putting secrets on the command line.\n\n```go\nfunc AddHeaderFlags(fs *flag.FlagSet) *HeaderFlags\n```\nAddHeaderFlags registers -H and --header on fs, seeded from VMFLOW\\_HEADERS (semicolon-separated \"Name: Value\"). Returns the handle.\n\n```go\nfunc (h HeaderFlags) Any() bool\n```\nAny reports whether any header is configured.\n\n```go\nfunc (h HeaderFlags) Apply(req *http.Request)\n```\nApply sets the configured headers on req (later entries win per name).\n\n```go\nfunc (h HeaderFlags) HTTPHeader() http.Header\n```\nHTTPHeader returns the configured headers as an http.Header.\n\n```go\nfunc (h *HeaderFlags) Set(s string) error\n```\n\n```go\nfunc (h *HeaderFlags) String() string\n```\n\n```go\ntype PrecheckResponse struct {\n\tRevision              string           `json:\"revision\"`\n\tUDPMaxSessionsChanged bool             `json:\"udp_max_sessions_changed\"`\n\tDiff                  []ConfigRuleDiff `json:\"diff\"`\n\tPrecheck              precheck.Result  `json:\"precheck\"`\n}\n```\n\n```go\ntype ReloadApplyError struct {\n\tTransaction engine.TransactionalApplyResult `json:\"transaction\"`\n}\n```\n\n```go\nfunc (err *ReloadApplyError) Error() string\n```\n\n```go\ntype ReloadResponse struct {\n\tConfigPath  string `json:\"config_path\"`\n\tControlPort int    `json:\"control_port\"`\n\tRuleCount   int    `json:\"rule_count\"`\n}\n```\n\n```go\ntype RestartRequiredError struct {\n\tFields []string `json:\"fields\"`\n}\n```\nRestartRequiredError reports configuration fields that cannot be changed by hot reload without leaving the API response out of sync with the daemon.\n\n```go\nfunc (err *RestartRequiredError) Error() string\n```\n\n```go\ntype RulesResponse struct {\n\tItems []engine.Rule `json:\"items\"`\n}\n```\nRulesResponse is the legacy runtime-only rule endpoint. ConfigRulesResponse is the source of truth for management because it also contains disabled rules.\n\n```go\ntype Runtime struct {\n\tConfigPath      string\n\tServerVersion   string\n\tCommit          string\n\tStartedAt       time.Time\n\tManager         *engine.Manager\n\tLogger          *slog.Logger\n\tAuth            *Authenticator\n\tMetrics         *metrics.Collector\n\tPrecheckOptions *precheck.Options\n\tCertStore       *certstore.Store\n\tCertReviewer    *certreview.Reviewer\n\t// HostNetwork returns a snapshot of the daemon host. It is optional so\n\t// embedders can omit host-level inspection from their control surface.\n\tHostNetwork func(context.Context) (netinfo.Snapshot, error)\n\t// Bot controls the Telegram bot lifecycle at runtime. May be nil when bot\n\t// support is disabled; bot config endpoints report unavailable then.\n\tBot BotController\n\t// StartupConfig is the normalized file configuration used to start the\n\t// daemon. Reload uses it to reject changes to restart-only fields.\n\tStartupConfig *config.File\n\t// contains filtered or unexported fields\n}\n```\n\n```go\nfunc (runtime *Runtime) Precheck() (config.File, precheck.Result, error)\n```\n\n```go\nfunc (runtime *Runtime) Reload() (config.File, engine.ApplyResult, error)\n```\n\n```go\ntype SessionCapabilities struct {\n\tRulesWrite bool `json:\"rules_write\"`\n}\n```\n\n```go\ntype SessionResponse struct {\n\tActor         string              `json:\"actor\"`\n\tRole          string              `json:\"role\"`\n\tCapabilities  SessionCapabilities `json:\"capabilities\"`\n\tAPIVersion    string              `json:\"api_version,omitempty\"`\n\tServerVersion string              `json:\"server_version,omitempty\"`\n\tCommit        string              `json:\"commit,omitempty\"`\n\tStartedTime   int64               `json:\"started_time,omitempty\"`\n\tDegraded      bool                `json:\"degraded\"`\n\tDegradedCause string              `json:\"degraded_cause,omitempty\"`\n}\n```\n\n```go\ntype SetupConfigUpdate struct {\n\tLanguage         string\n\tAuth             config.AuthConfig\n\tRules            []engine.Rule\n\tRulesHeadComment string\n}\n```\nSetupConfigUpdate is the configuration surface owned by the first-run workflow. Existing files retain every other top-level field and unknown YAML node.\n\n```go\ntype StatsResponse struct {\n\tItems       []TrafficSnapshot `json:\"items\"`\n\tHostNetwork *netinfo.Snapshot `json:\"host_network,omitempty\"`\n}\n```\n\n```go\ntype TrafficSnapshot = engine.TrafficSnapshot\n```\n\n","path":"github.com/cloudapp3/vmflow/controlapi","name":"controlapi","synopsis":"Package controlapi implements vmflow's internal daemon management transport.","isRedistributable":true}
