### Start ProxyManager Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/proxy-manager.md Starts the proxy manager and activates all configured targets. Check for errors during startup. ```go if err := pm.Start(); err != nil { log.Printf("Failed to start proxy manager: %v", err) } ``` -------------------------------- ### Install Newt Client Source: https://github.com/fosrl/newt/blob/main/_autodocs/README.md Install the Newt client using the go get command. Ensure you have Go 1.25+ installed. ```bash go get github.com/fosrl/newt@latest ``` -------------------------------- ### Start Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/proxy-manager.md Starts the proxy manager and activates all configured proxy targets. Returns an error if the manager fails to start. ```APIDOC ## Start ### Description Starts the proxy manager and activates all configured proxy targets. Returns an error if the manager fails to start. ### Returns - **error** - An error if the manager cannot start. ### Example ```go if err := pm.Start(); err != nil { log.Printf("Failed to start proxy manager: %v", err) } ``` ``` -------------------------------- ### Create and Start ProxyManager Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/proxy-manager.md Creates a new proxy manager instance for a specific virtual network stack and starts it. Ensure to stop the manager when done. ```go pm := proxy.NewProxyManager(tnet) deffer pm.Stop() if err := pm.Start(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Example Usage of New Monitor with Callback Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/healthcheck-monitor.md Demonstrates how to initialize a new healthcheck monitor with a callback function to process status changes. ```go monitor := healthcheck.NewMonitor( func(targets map[int]*healthcheck.Target) { for id, target := range targets { // Send status update to server sendHealthStatus(id, target.Status.String()) } }, true, ) ``` -------------------------------- ### Provision Newt Client with a Provisioning Key Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md This example shows how to provision the Newt client using a one-time provisioning key and setting a site name. ```bash newt \ --endpoint https://api.example.com \ --provisioning-key "one-time-key-from-server" \ --name "My New Site" ``` -------------------------------- ### Minimal Newt Setup Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md A basic Newt configuration with essential parameters like endpoint, ID, and secret. ```bash newt \ --endpoint "https://api.example.com" \ --id "newt-123" \ --secret "secret-key" ``` -------------------------------- ### Initialize Newt WebSocket Client Source: https://github.com/fosrl/newt/blob/main/_autodocs/INDEX.md Example of how to initialize a Newt WebSocket client. Refer to websocket-client.md for the full API. ```go import "github.com/fosrl/newt/websocket" // Reference websocket-client.md for full API client, err := websocket.NewClient(...) ``` -------------------------------- ### Apply Blueprint During Provisioning Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md Specify a blueprint file to be applied once after the initial provisioning of the target host. This is useful for one-time setup configurations. ```bash newt --provisioning-blueprint-file "/etc/newt/provisioning.json" ``` -------------------------------- ### Build Newt Binary Source: https://github.com/fosrl/newt/blob/main/README.md Build the Newt binary using make. Ensure Go 1.25 or later is installed. ```bash make ``` -------------------------------- ### Handle Unsupported Protocol Error Source: https://github.com/fosrl/newt/blob/main/_autodocs/errors.md This example shows how adding a target with an unsupported protocol results in an error. ```go err := pm.AddTarget("xyz", "127.0.0.1", 8080, "target:8080") // Returns: fmt.Errorf("unsupported protocol: xyz") ``` -------------------------------- ### Get Configuration Version Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/websocket-client.md Retrieve the version number of the latest configuration received from the server. ```go func (c *Client) GetConfigVersion() int64 ``` -------------------------------- ### Start Docker Event Monitor Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/docker.md Activates the Docker event monitor to begin watching for container changes and triggering callbacks. ```Go if err := monitor.Start(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Configure Newt System Settings Source: https://github.com/fosrl/newt/blob/main/_autodocs/INDEX.md Example of configuring Newt system settings via command-line arguments. Refer to configuration.md for all options. ```bash # Reference configuration.md for all options newt --endpoint https://api.example.com \ --id my-id \ --secret my-secret ``` -------------------------------- ### Create WebSocket Client Programmatically Source: https://github.com/fosrl/newt/blob/main/_autodocs/README.md Programmatically create a Newt WebSocket client in Go. This example shows how to set up the client, register a handler for WireGuard connections, and establish the connection. ```go package main import ( "log" "time" "github.com/fosrl/newt/websocket" ) func main() { client, err := websocket.NewClient( "newt", "your-id", "your-secret", "https://api.pangolin.net", 30*time.Second, ) if err != nil { log.Fatal(err) } defer client.Close() // Register handler for WireGuard connection client.RegisterHandler("newt/wg/connect", func(msg websocket.WSMessage) { log.Printf("Received connection: %+v", msg.Data) }) if err := client.Connect(); err != nil { log.Fatal(err) } // Keep running select {} } ``` -------------------------------- ### Get Server Version Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/websocket-client.md Retrieve the version string of the connected server. This is typically obtained during the authentication process. ```go func (c *Client) GetServerVersion() string ``` -------------------------------- ### Configure TLS with Separate Certificate, Key, and CA Files Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md This example shows how to configure TLS client authentication using separate certificate, key, and CA files via command-line flags. ```bash newt \ --endpoint https://api.example.com \ --id my-id \ --secret my-secret \ --tls-client-cert-file /path/to/cert.pem \ --tls-client-key /path/to/key.pem \ --tls-client-ca /path/to/ca.pem ``` -------------------------------- ### Set Connection Callback Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/websocket-client.md Define a function to execute upon successful connection to the server. This is useful for sending initial messages or performing setup. ```go func (c *Client) OnConnect(callback func() error) ``` ```go client.OnConnect(func() error { logger.Info("Connected to server") // Send initial registration or other setup return nil }) ``` -------------------------------- ### Custom LogWriter Implementation Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/logger.md Provides an example of a custom LogWriter implementation that formats and prints log messages to standard output with timestamps and log levels. ```go type MyWriter struct{} func (w *MyWriter) Write(level LogLevel, t time.Time, msg string) { fmt.Printf("[%s] %s: %s\n", t.Format(time.RFC3339), level.String(), msg) } log := logger.NewLoggerWithWriter(&MyWriter{}) ``` -------------------------------- ### Newt Client Configuration File Example Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md This JSON structure represents the configuration file for the Newt client, storing essential settings like ID, secret, and endpoint. ```json { "id": "newt-12345", "secret": "secret-key-here", "endpoint": "https://api.pangolin.net", "provisioningKey": "", "name": "My Site", "tlsClientCert": "/path/to/cert.p12" } ``` -------------------------------- ### Get Metrics Context Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/websocket-client.md Obtain the context used for emitting telemetry data when an active connection is established. ```go func (c *Client) MetricsContext() context.Context ``` -------------------------------- ### Add Proxy Target Source: https://github.com/fosrl/newt/blob/main/_autodocs/README.md Creates a new proxy manager and adds a TCP target. The proxy manager should be started after adding targets. ```go pm := proxy.NewProxyManager(tnet) pm.AddTarget("tcp", "10.0.0.1", 8080, "192.168.1.1:80") pm.Start() ``` -------------------------------- ### Development Newt Setup with Debugging Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md Configure Newt for development with a local endpoint, DEBUG log level, enabled metrics, and pprof debugging enabled on a specific admin address. ```bash newt \ --endpoint "http://localhost:8000" \ --id "dev-newt" \ --secret "dev-secret" \ --log-level DEBUG \ --metrics \ --pprof \ --metrics-admin-addr "127.0.0.1:2112" ``` -------------------------------- ### Get Client Configuration Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/websocket-client.md Retrieve the current configuration of the WebSocket client. This includes details like client ID and endpoint. ```go func (c *Client) GetConfig() *Config ``` ```go cfg := client.GetConfig() fmt.Printf("Client ID: %s\nEndpoint: %s\n", cfg.ID, cfg.Endpoint) ``` -------------------------------- ### Get Default Logger Instance Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/logger.md Retrieves the global default logger instance. It will be initialized if it hasn't been already. ```go log := logger.GetLogger() log.Info("Using default logger") ``` -------------------------------- ### EventMonitor.Start Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/docker.md Starts the Docker event monitor. This method begins watching for Docker events and triggers the registered callback function upon detecting changes in containers. ```APIDOC ## Start ### Description Starts the event monitor. The monitor watches for Docker events and invokes the callback when containers are added, removed, or updated. ### Method Signature ```go func (em *EventMonitor) Start() error ``` ### Returns - **error** - An error if the monitor cannot start. ### Example ```go if err := monitor.Start(); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Production Newt Setup with mTLS Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md Configure Newt for production with mutual TLS (mTLS) authentication, specifying certificate and key files. Also sets a WARN log level and enables metrics. ```bash newt \ --endpoint "https://api.example.com" \ --id "newt-prod-01" \ --secret "secret-key" \ --tls-client-cert-file "/etc/newt/cert.pem" \ --tls-client-key "/etc/newt/key.pem" \ --tls-client-ca "/etc/newt/ca.pem" \ --log-level WARN \ --metrics \ --region "us-east-1" ``` -------------------------------- ### Log Message Filtering Example Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/logger.md Demonstrates how log messages are filtered based on the currently set logger level. Messages at or above the set level are logged, while those below are discarded. ```go // If level is set to WARN, these are logged: logger.Warn("Warning") logger.Error("Error") logger.Fatal("Fatal") // These are NOT logged: logger.Debug("Debug") logger.Info("Info") ``` -------------------------------- ### Set Logger Output Destination Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/logger.md Changes the output destination for logs, specifically for the StandardWriter. This example demonstrates writing logs to a file named 'app.log'. ```go logFile, _ := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY, 0644) logger.GetLogger().SetOutput(logFile) ``` -------------------------------- ### Initialize and use the default logger Source: https://github.com/fosrl/newt/blob/main/examples/README.md Demonstrates standard usage with the default logger or creating a custom instance with a specific log level. ```go package main import "your-project/logger" func main() { // Use default logger logger.Info("This works as before") logger.Debug("Debug message") logger.Error("Error message") // Or create a custom instance log := logger.NewLogger() log.SetLevel(logger.INFO) log.Info("Custom logger instance") } ``` -------------------------------- ### Provisioning Authentication (One-Time Key) Source: https://github.com/fosrl/newt/blob/main/_autodocs/README.md Authenticate and provision Newt using a one-time provisioning key and a site name. ```bash newt --provisioning-key "one-time-key" --name "My Site" ``` -------------------------------- ### Get Token Source: https://github.com/fosrl/newt/blob/main/_autodocs/endpoints.md Obtains an authentication token for Newt to establish a WebSocket connection. Requires Newt ID and secret. ```APIDOC ## POST /api/v1/auth/newt/get-token ### Description Obtains an authentication token for Newt to establish a WebSocket connection. Requires Newt ID and secret. ### Method POST ### Endpoint /api/v1/auth/newt/get-token ### Parameters #### Request Body - **newtId** (string) - Required - The unique identifier for the Newt instance. - **secret** (string) - Required - The secret key associated with the Newt instance. ### Request Example { "newtId": "string", "secret": "string" } ### Response #### Success Response (200 OK) - **success** (boolean) - Indicates if the token retrieval was successful. - **data** (object) - Contains the authentication token and server version. - **token** (string) - The JWT authentication token. - **serverVersion** (string) - The version of the server. #### Response Example { "success": true, "data": { "token": "jwt.token.here", "serverVersion": "1.13.0" } } #### Error Response (401/403) - **success** (boolean) - Indicates if the token retrieval was successful. - **message** (string) - Error message describing the issue (e.g., "Invalid credentials"). #### Error Response Example { "success": false, "message": "Invalid credentials" } ``` -------------------------------- ### Build Newt with Nix Source: https://github.com/fosrl/newt/blob/main/_autodocs/README.md Build the Newt project or enter a development shell using Nix commands. ```bash nix build nix develop # Development shell ``` -------------------------------- ### Configure TLS with Environment Variables Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md Shows how to set TLS client certificate, key, and CA files using environment variables. ```bash export TLS_CLIENT_CERT="/path/to/cert.pem" export TLS_CLIENT_KEY="/path/to/key.pem" export TLS_CLIENT_CAS="/path/to/ca1.pem,/path/to/ca2.pem" newt ``` -------------------------------- ### Configure TLS with PKCS12 Certificate File Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md Demonstrates configuring TLS client authentication using a single PKCS12 file via a command-line flag. ```bash newt \ --endpoint https://api.example.com \ --id my-id \ --secret my-secret \ --tls-client-cert /path/to/cert.p12 ``` -------------------------------- ### Build Newt from Source Source: https://github.com/fosrl/newt/blob/main/_autodocs/README.md Build the Newt binary and run tests using make. Clean build artifacts with 'make clean'. ```bash git clone https://github.com/fosrl/newt.git cd newt make # Build binary make test # Run tests make clean # Clean build artifacts ``` -------------------------------- ### Configure TLS with Multiple CA Files Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md Illustrates specifying multiple CA certificate files for TLS client authentication using command-line flags. ```bash newt \ --tls-client-cert-file /path/to/cert.pem \ --tls-client-key /path/to/key.pem \ --tls-client-ca /path/to/ca1.pem \ --tls-client-ca /path/to/ca2.pem ``` -------------------------------- ### Get Authentication Token (POST /api/v1/auth/newt/get-token) Source: https://github.com/fosrl/newt/blob/main/_autodocs/endpoints.md Use this endpoint to obtain an authentication token for Newt. It requires the newtId and secret in the request body. ```http POST /api/v1/auth/newt/get-token Content-Type: application/json X-CSRF-Token: x-csrf-protection ``` ```json { "newtId": "string", "secret": "string" } ``` ```json { "success": true, "data": { "token": "jwt.token.here", "serverVersion": "1.13.0" } } ``` ```json { "success": false, "message": "Invalid credentials" } ``` -------------------------------- ### Get All Health Check Targets Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/healthcheck-monitor.md Retrieves a snapshot of all currently configured health check targets and their statuses. Useful for monitoring the overall health state. ```go targets := monitor.GetTargets() for id, target := range targets { fmt.Printf("Target %d: %s (last check: %v)\n", id, target.Status.String(), target.LastCheck, ) } ``` -------------------------------- ### Create New Logger Instance Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/logger.md Creates a new logger instance with a standard output writer. Use this for basic logging needs. ```go log := logger.NewLogger() log.Info("Application started") ``` -------------------------------- ### Configure WebSocket Client with File Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/websocket-client.md Specifies a custom path to a configuration file for the WebSocket client. This is useful for externalizing client settings. ```go client, err := websocket.NewClient( "newt", "", "", endpoint, 30*time.Second, websocket.WithConfigFile("/etc/newt/config.json"), ) ``` -------------------------------- ### Logger Initialization and Configuration Source: https://github.com/fosrl/newt/blob/main/examples/README.md Methods for creating logger instances and configuring their behavior. ```APIDOC ## Logger Initialization ### Description Methods to instantiate a new logger or configure an existing one. ### Methods - `NewLogger()`: Creates a logger with the default StandardWriter. - `NewLoggerWithWriter(writer LogWriter)`: Creates a logger with a custom writer. - `SetLevel(level LogLevel)`: Sets the minimum log level for the logger instance. - `SetOutput(output *os.File)`: Sets the output file (StandardWriter only). ``` -------------------------------- ### Initialize Default Logger Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/logger.md Initializes the global default logger. Pass nil to use a standard logger. This should be called once at application startup. ```go logger.Init(nil) // Use default logger ``` -------------------------------- ### Example HTTP Health Check Request Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/healthcheck-monitor.md Illustrates the format of an HTTP request used for health checks, including method, scheme, host, path, and custom headers. ```http GET https://api.example.com:443/health HTTP/1.1 Host: api.example.com Authorization: Bearer token123 ``` -------------------------------- ### Newt Provisioning Configuration Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md Configure Newt for provisioning with a one-time key, dynamic name using environment variables, and mTLS client authentication. ```bash newt \ --endpoint "https://api.example.com" \ --provisioning-key "one-time-key" \ --name "Site-{{env.ENVIRONMENT}}" \ --tls-client-cert-file "/etc/newt/cert.pem" \ --tls-client-key "/etc/newt/key.pem" ``` -------------------------------- ### Register Message Handler Source: https://github.com/fosrl/newt/blob/main/_autodocs/README.md Registers a handler function for incoming WebSocket messages with a specific topic. This example shows how to process messages for adding new TCP targets. ```go client.RegisterHandler("newt/tcp/add", func(msg websocket.WSMessage) { // Process new TCP targets }) ``` -------------------------------- ### Basic Newt Client Usage Source: https://github.com/fosrl/newt/blob/main/_autodocs/README.md Run the Newt client from the command line with essential parameters like endpoint, ID, and secret. ```bash newt \ --endpoint "https://api.pangolin.net" \ --id "your-newt-id" \ --secret "your-secret" ``` -------------------------------- ### WithConfigFile Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/websocket-client.md Specifies a custom path for the client configuration file, allowing for external configuration management. ```APIDOC ## WithConfigFile ### Description Specifies a custom path for the client configuration file, allowing for external configuration management. ### Function Signature ```go func WithConfigFile(path string) ClientOption ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters Table | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | path | string | Yes | Path to configuration file | ### Example ```go client, err := websocket.NewClient( "newt", "", "", endpoint, 30*time.Second, websocket.WithConfigFile("/etc/newt/config.json"), ) ``` ``` -------------------------------- ### Add TCP Proxy Target via Message Protocol Source: https://github.com/fosrl/newt/blob/main/_autodocs/INDEX.md Example of adding a TCP proxy target using the Newt message protocol. Refer to endpoints.md for the message schema. ```json // Reference endpoints.md for message schema { "type": "newt/tcp/add", "data": { "targets": ["8080:192.168.1.1:80"] } } ``` -------------------------------- ### Create New WebSocket Client Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/websocket-client.md Initializes a new WebSocket client for connecting to the Pangolin server. Requires client type, endpoint, and ping interval. Authentication details and optional configurations can also be provided. ```go client, err := websocket.NewClient( "newt", "my-newt-id", "my-secret", "https://api.pangolin.net", 30*time.Second, ) if err != nil { log.Fatal(err) } deffer client.Close() // Connect to the server if err := client.Connect(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Apply Blueprint on Connect Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md Specify a blueprint file to be applied every time Newt connects. This file contains JSON configuration commands for the target host. ```bash newt --blueprint-file "/etc/newt/blueprint.json" ``` -------------------------------- ### Connect WebSocket Client Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/websocket-client.md Establishes the WebSocket connection to the server. This method handles token acquisition and automatic reconnection attempts. ```go if err := client.Connect(); err != nil { log.Printf("Failed to connect: %v", err) } ``` -------------------------------- ### Init Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/logger.md Initializes the default logger for the application. It can accept a custom logger or create a default one if nil is provided. Typically called once at startup. ```APIDOC ## Init ### Description Initializes the default logger. If `nil` is passed, a standard logger is created. This is typically called once at application startup. ### Parameters #### Path Parameters - **logger** (*Logger) - Optional - Custom logger instance, or `nil` for default ### Returns - `*Logger`: The initialized default logger. ### Example ```go logger.Init(nil) // Use default logger ``` ``` -------------------------------- ### Create Docker Event Monitor Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/docker.md Initializes a monitor to watch for Docker events. It calls a provided callback function whenever container lists change, optionally filtering by network. ```Go monitor, err := docker.NewEventMonitor( "unix:///var/run/docker.sock", true, func(containers []docker.Container) { fmt.Printf("Container list updated: %d containers\n", len(containers)) // Send updated list to server via WebSocket }, ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Enable pprof Debug Endpoints Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md Enable Go profiling endpoints for debugging and performance analysis. These endpoints are usually accessible via the metrics admin address. ```bash newt \ --endpoint https://api.example.com \ --id my-id \ --secret my-secret \ --metrics \ --pprof ``` -------------------------------- ### Implement the LogWriter interface Source: https://github.com/fosrl/newt/blob/main/examples/README.md The interface required for creating custom log backends. ```go type LogWriter interface { Write(level LogLevel, timestamp time.Time, message string) } ``` -------------------------------- ### Provisioning (Register) Source: https://github.com/fosrl/newt/blob/main/_autodocs/endpoints.md Registers a new Newt instance, providing a provisioning key and name to obtain a Newt ID and secret. ```APIDOC ## POST /api/v1/auth/newt/register ### Description Registers a new Newt instance, providing a provisioning key and name to obtain a Newt ID and secret. ### Method POST ### Endpoint /api/v1/auth/newt/register ### Parameters #### Request Body - **provisioningKey** (string) - Required - A one-time key used for provisioning. - **name** (string) - Required - The desired name for the Newt instance. ### Request Example { "provisioningKey": "one-time-key", "name": "My Site Name" } ### Response #### Success Response (200 OK) - **success** (boolean) - Indicates if the registration was successful. - **data** (object) - Contains the newt ID and secret. - **newtId** (string) - The unique identifier assigned to the new Newt instance. - **secret** (string) - The secret key for the new Newt instance. #### Response Example { "success": true, "data": { "newtId": "newt-12345", "secret": "secret-key-here" } } ``` -------------------------------- ### Check if Just Provisioned Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/websocket-client.md Determine if the client recently exchanged a provisioning key for permanent credentials. This flag is reset after each check. ```go func (c *Client) WasJustProvisioned() bool ``` ```go if client.Connect() == nil && client.WasJustProvisioned() { logger.Info("Site was just provisioned with ID: %s", client.GetConfig().ID) } ``` -------------------------------- ### WebSocket Provisioning Response Structure Source: https://github.com/fosrl/newt/blob/main/_autodocs/types.md The server's response after provisioning a new site using a provisioning key. It contains the new site's ID and secret, along with success status. ```go type ProvisioningResponse struct { Data struct { NewtID string // Newly provisioned Newt ID Secret string // Secret for the provisioned ID } `json:"data"` Success bool // Whether provisioning succeeded Message string // Error message if not successful } ``` -------------------------------- ### Create New Health Check Monitor Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/healthcheck-monitor.md Initializes a new health check monitor. Use this to set up callbacks for status changes and certificate validation preferences. ```go monitor := healthcheck.NewMonitor( func(targets map[int]*healthcheck.Target) { for id, target := range targets { logger.Info("Target %d status: %s", id, target.Status.String()) } }, true, // enforce certificate validation ) defer monitor.Stop() ``` -------------------------------- ### Check Docker Socket and List Containers Source: https://github.com/fosrl/newt/blob/main/_autodocs/README.md Checks if the Docker socket is available and lists containers if it is. The Docker socket path can be configured via the DOCKER_SOCKET environment variable. ```go available := docker.CheckSocket("unix:///var/run/docker.sock") if available { containers, _ := docker.ListContainers("unix:///var/run/docker.sock", true) } ``` -------------------------------- ### Connect Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/websocket-client.md Establishes the WebSocket connection to the server. This method automatically handles token acquisition and reconnection attempts. ```APIDOC ## Connect ### Description Establishes the WebSocket connection to the server. Automatically handles token acquisition and reconnection attempts. ### Method Signature ```go func (c *Client) Connect() error ``` ### Parameters * None ### Returns An error if the connection cannot be initiated. ### Example ```go if err := client.Connect(); err != nil { log.Printf("Failed to connect: %v", err) } ``` ``` -------------------------------- ### Provision Newt Client with Environment Variable Interpolation in Name Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md Illustrates using environment variable interpolation within the `--name` flag during Newt client provisioning. ```bash export SITE_ID="prod-01" newt \ --provisioning-key "key" \ --name "Site-{{env.SITE_ID}}" ``` -------------------------------- ### Accept Any Certificate in Newt Monitor Source: https://github.com/fosrl/newt/blob/main/_autodocs/errors.md When enforcing TLS certificate validation is not desired or feasible, set the `enforceCert` parameter to `false` in `NewMonitor()` to accept any certificate. This is useful for development or internal networks where certificate management is less critical. ```go monitor := healthcheck.NewMonitor(callback, false) // Accept any cert // OR add target's CA to system trust store ``` -------------------------------- ### Enable Prometheus Metrics Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md Enable Prometheus metrics collection and specify the admin address for accessing them. Metrics are typically available at http://localhost:2112/metrics. ```bash newt \ --endpoint https://api.example.com \ --id my-id \ --secret my-secret \ --metrics \ --metrics-admin-addr "0.0.0.0:2112" ``` -------------------------------- ### Config Structure Definition Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/websocket-client.md Defines the structure for client configuration, including authentication details and endpoint information. Configuration is persisted automatically. ```go type Config struct { ID string // Client ID for authentication Secret string // Client secret for authentication Endpoint string // Server endpoint URL TlsClientCert string // Path to client certificate (legacy) ProvisioningKey string // One-time provisioning key (exchanged for ID/Secret) Name string // Name for provisioned site } ``` -------------------------------- ### Test TLS Configuration with OpenSSL Source: https://github.com/fosrl/newt/blob/main/_autodocs/errors.md Use OpenSSL to connect to a server and test its TLS configuration, including certificate and key validation. ```bash openssl s_client -cert /path/to/cert.pem \ -key /path/to/key.pem \ -CAfile /path/to/ca.pem \ -connect api.example.com:443 ``` -------------------------------- ### Build Newt with Nix Flake Source: https://github.com/fosrl/newt/blob/main/README.md Build the Newt binary using Nix Flake. The binary will be located at ./result/bin/newt. A development shell is available with 'nix develop'. ```bash nix build ``` -------------------------------- ### Implement a multi-writer Source: https://github.com/fosrl/newt/blob/main/examples/README.md Aggregates multiple log writers to broadcast log messages to several destinations simultaneously. ```go package main import ( "time" "your-project/logger" ) // MultiWriter writes to multiple log writers type MultiWriter struct { writers []logger.LogWriter } func NewMultiWriter(writers ...logger.LogWriter) *MultiWriter { return &MultiWriter{writers: writers} } func (w *MultiWriter) Write(level logger.LogLevel, timestamp time.Time, message string) { for _, writer := range w.writers { writer.Write(level, timestamp, message) } } func main() { // Log to both standard output and OS log standardWriter := logger.NewStandardWriter() osWriter := logger.NewOSLogWriter("com.example.app", "Main", "App") multiWriter := NewMultiWriter(standardWriter, osWriter) log := logger.NewLoggerWithWriter(multiWriter) log.Info("This goes to both stdout and os_log!") } ``` -------------------------------- ### Listing Docker Containers with a Custom Socket Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/architecture.md Connect to a Docker daemon using a custom socket address (e.g., TCP) to list containers. ```go socket := "tcp://localhost:2375" containers, err := docker.ListContainers(socket, false) ``` -------------------------------- ### WebSocket Configuration Structure Source: https://github.com/fosrl/newt/blob/main/_autodocs/types.md Defines the configuration parameters for establishing a WebSocket connection, including authentication details and server endpoint. This structure is persisted to disk and used by Newt client initialization. ```go type Config struct { ID string // Client ID for authentication with Pangolin Secret string // Client secret for authentication Endpoint string // Server endpoint URL (e.g., https://api.pangolin.net) TlsClientCert string // Path to client certificate file (legacy field) ProvisioningKey string // One-time provisioning key (optional) Name string // Name for provisioned site (optional) } ``` -------------------------------- ### Package-level Logging Functions Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/logger.md Log messages directly using the default logger without explicit calls to GetLogger(). Supports Printf-style formatting. ```go logger.Info("Server started on port %d", 8080) logger.Error("Failed to connect: %v", err) logger.Fatal("Critical error: %v", err) ``` -------------------------------- ### Set Environment Variables for Newt Client Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md Demonstrates setting environment variables to configure the Newt client's endpoint, ID, secret, and log level. ```bash export PANGOLIN_ENDPOINT="https://api.example.com" export NEWT_ID="my-newt-id" export NEWT_SECRET="my-secret" export LOG_LEVEL="DEBUG" newt ``` -------------------------------- ### Provisioning (Register) Newt (POST /api/v1/auth/newt/register) Source: https://github.com/fosrl/newt/blob/main/_autodocs/endpoints.md Register a new Newt instance to obtain its ID and secret. This is a one-time process using a provisioning key. ```http POST /api/v1/auth/newt/register Content-Type: application/json X-CSRF-Token: x-csrf-protection ``` ```json { "provisioningKey": "one-time-key", "name": "My Site Name" } ``` ```json { "success": true, "data": { "newtId": "newt-12345", "secret": "secret-key-here" } } ``` -------------------------------- ### Configure TLS for WebSocket Client Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/websocket-client.md Sets up mutual TLS (mTLS) for the WebSocket client connection using certificate and key files. CA files can also be provided for certificate validation. ```go client, err := websocket.NewClient( "newt", id, secret, endpoint, 30*time.Second, websocket.WithTLSConfig(websocket.TLSConfig{ ClientCertFile: "/path/to/cert.pem", ClientKeyFile: "/path/to/key.pem", CAFiles: []string{"/path/to/ca.pem"}, }), ) ``` -------------------------------- ### Verify Newt Configuration Loading Source: https://github.com/fosrl/newt/blob/main/_autodocs/errors.md Check which configuration Newt is loading by setting the LOG_LEVEL to DEBUG and observing the output for a 'Config:' log line. ```bash # Check what config is loaded export LOG_LEVEL=DEBUG newt ... # Look for "Config:" log line ``` -------------------------------- ### Define Targets Grouped by Protocol Source: https://github.com/fosrl/newt/blob/main/_autodocs/types.md Groups proxy targets by protocol. ```go type TargetsByType struct { UDP []string // UDP targets in format "port:host:port" TCP []string // TCP targets in format "port:host:port" } ``` -------------------------------- ### Configure an OS log writer Source: https://github.com/fosrl/newt/blob/main/examples/README.md Uses the built-in OS log writer for macOS/iOS platforms. ```go package main import "your-project/logger" func main() { // Create an OS log writer osWriter := logger.NewOSLogWriter( "net.pangolin.Pangolin.PacketTunnel", "PangolinGo", "MyApp", ) // Create a logger with the OS log writer log := logger.NewLoggerWithWriter(osWriter) log.SetLevel(logger.DEBUG) // Use it just like the standard logger log.Info("This message goes to os_log") log.Error("Error logged to os_log") } ``` -------------------------------- ### Custom Logger Implementation Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/architecture.md Implement a custom logger by defining a struct that satisfies the logger.Writer interface and initializing the logger with your custom writer. ```go type MyLogger struct{} func (l *MyLogger) Write(level logger.LogLevel, t time.Time, msg string) { // Custom output format } logger.Init(logger.NewLoggerWithWriter(&MyLogger{})) ``` -------------------------------- ### Enable OTLP Exporter Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md Enable the OpenTelemetry Protocol (OTLP) exporter to send metrics and traces to OpenTelemetry backends. Ensure the OTEL_EXPORTER_OTLP_ENDPOINT environment variable is set. ```bash export OTEL_EXPORTER_OTLP_ENDPOINT="https://otel-collector.example.com:4317" newt \ --endpoint https://api.example.com \ --id my-id \ --secret my-secret \ --otlp ``` -------------------------------- ### Configure WireGuard Interface Source: https://github.com/fosrl/newt/blob/main/_autodocs/configuration.md Customize the WireGuard interface name, Maximum Transmission Unit (MTU), and DNS server. This is useful for setting up custom network configurations. ```bash newt \ --endpoint https://api.example.com \ --id my-id \ --secret my-secret \ --interface wg0 \ --mtu 1500 \ --dns 8.8.8.8 ``` -------------------------------- ### Configure Log Level via Command-line Flag Source: https://github.com/fosrl/newt/blob/main/_autodocs/README.md Set the log level to DEBUG using the --log-level flag. ```bash newt --log-level DEBUG ``` -------------------------------- ### GetServerVersion Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/websocket-client.md Fetches the version of the server that the client is currently connected to. This information is typically obtained during the authentication process. ```APIDOC ## GetServerVersion ### Description Returns the server version string received during authentication. ### Method Signature ```go func (c *Client) GetServerVersion() string ``` ### Returns - **string** - Server version string (e.g., "1.13.0"). ### Example ```go version := client.GetServerVersion() logger.Info("Connected to server version: %s", version) ``` ``` -------------------------------- ### Register Newt with Server Source: https://github.com/fosrl/newt/blob/main/_autodocs/endpoints.md Registers Newt with the server and provides selected exit node information. Includes WireGuard public key, ping results, Newt version, and chain ID. ```json { "type": "newt/wg/register", "data": { "publicKey": "base64-encoded-wireguard-public-key", "pingResults": [ { "exitNodeId": 1, "exitNodeName": "US East Node", "endpoint": "10.1.0.1:21820", "latencyMs": 25, "weight": 1.0, "error": "", "wasPreviouslyConnected": false } ], "newtVersion": "1.5.0", "backwardsCompatible": true, "chainId": "hexadecimal-deduplication-id" } } ``` -------------------------------- ### OnConnect Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/websocket-client.md Sets a callback function to be executed when the client successfully connects to the server. This is useful for performing actions immediately after a connection is established, such as sending initial data. ```APIDOC ## OnConnect ### Description Sets a callback function to be executed when the client successfully connects to the server. ### Method Signature ```go func (c *Client) OnConnect(callback func() error) ``` ### Parameters #### Path Parameters - **callback** (func() error) - Required - Callback function ### Example ```go client.OnConnect(func() error { logger.Info("Connected to server") // Send initial registration or other setup return nil }) ``` ``` -------------------------------- ### NewClient Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/websocket-client.md Creates a new WebSocket client instance for communicating with Pangolin. It supports authentication, endpoint configuration, and connection keep-alive intervals. ```APIDOC ## NewClient ### Description Creates a new WebSocket client instance for communicating with Pangolin. It supports authentication, endpoint configuration, and connection keep-alive intervals. ### Function Signature ```go func NewClient(clientType string, ID, secret string, endpoint string, pingInterval time.Duration, opts ...ClientOption) (*Client, error) ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | clientType | string | Yes | — | Type of client (e.g., "newt", "olm") | | ID | string | No | "" | Client ID for authentication | | secret | string | No | "" | Client secret for authentication | | endpoint | string | Yes | — | Server endpoint URL (e.g., https://api.example.com) | | pingInterval | time.Duration | Yes | — | Interval for keeping connection alive | | opts | ...ClientOption | No | — | Optional client configuration options | ### Returns A new `*Client` instance and any error encountered during initialization. ### Example ```go client, err := websocket.NewClient( "newt", "my-newt-id", "my-secret", "https://api.pangolin.net", 30*time.Second, ) if err != nil { log.Fatal(err) } defer client.Close() // Connect to the server if err := client.Connect(); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Add TCP and UDP Proxy Targets Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/proxy-manager.md Adds new proxy targets for TCP or UDP traffic. Specify the protocol, listening IP and port, and the target address. ```go // Add a TCP target err := pm.AddTarget("tcp", "10.0.0.1", 8080, "192.168.1.100:80") // Add a UDP target err = pm.AddTarget("udp", "10.0.0.1", 53, "8.8.8.8:53") ``` -------------------------------- ### Custom TLS Configuration for WebSocket Client Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/architecture.md Configure custom TLS settings, including client certificates and CA files, when establishing a WebSocket connection. ```go client, _ := websocket.NewClient( "newt", id, secret, endpoint, 30*time.Second, websocket.WithTLSConfig(websocket.TLSConfig{ ClientCertFile: "/path/to/cert.pem", ClientKeyFile: "/path/to/key.pem", CAFiles: []string{"/path/to/ca.pem"}, }), ) ``` -------------------------------- ### Configure Log Level via Environment Variable Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/logger.md Shows how to set the global log level using the LOG_LEVEL environment variable. The variable is case-insensitive and affects which messages are logged. ```bash export LOG_LEVEL=DEBUG # All messages export LOG_LEVEL=INFO # Info and above export LOG_LEVEL=WARN # Warnings and above ``` -------------------------------- ### Handle Authentication Errors Source: https://github.com/fosrl/newt/blob/main/_autodocs/errors.md Check for 401 or 403 status codes in the error when connecting to authenticate. ```go err := client.Connect() if err != nil { if strings.Contains(err.Error(), "401") || strings.Contains(err.Error(), "403") { log.Fatal("Authentication failed - check ID and secret") } } ``` -------------------------------- ### Create a custom log writer Source: https://github.com/fosrl/newt/blob/main/examples/README.md Defines a custom struct that implements the LogWriter interface for specialized logging destinations. ```go package main import ( "fmt" "time" "your-project/logger" ) // CustomWriter writes logs to a custom destination type CustomWriter struct { // your custom fields } func (w *CustomWriter) Write(level logger.LogLevel, timestamp time.Time, message string) { // Your custom logging logic fmt.Printf("[CUSTOM] %s [%s] %s\n", timestamp.Format(time.RFC3339), level.String(), message) } func main() { customWriter := &CustomWriter{} log := logger.NewLoggerWithWriter(customWriter) log.Info("Custom logging!") } ``` -------------------------------- ### WithTLSConfig Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/websocket-client.md Configures mTLS certificate settings for the client connection, allowing for secure communication with the server. ```APIDOC ## WithTLSConfig ### Description Configures mTLS certificate settings for the client connection, allowing for secure communication with the server. ### Function Signature ```go func WithTLSConfig(config TLSConfig) ClientOption ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters Table | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | config | TLSConfig | Yes | TLS configuration object | ### TLSConfig Structure ```go type TLSConfig struct { ClientCertFile string // Path to client certificate file (PEM/DER) ClientKeyFile string // Path to client private key file (PEM/DER) CAFiles []string // Paths to CA certificate files for remote validation PKCS12File string // Path to PKCS12 certificate (deprecated) } ``` ### Example ```go client, err := websocket.NewClient( "newt", id, secret, endpoint, 30*time.Second, websocket.WithTLSConfig(websocket.TLSConfig{ ClientCertFile: "/path/to/cert.pem", ClientKeyFile: "/path/to/key.pem", CAFiles: []string{"/path/to/ca.pem"}, }), ) ``` ``` -------------------------------- ### Create Logger with Custom Writer Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/logger.md Creates a new logger instance using a provided custom LogWriter implementation. Useful for directing logs to specific destinations like files or network sockets. ```go customWriter := MyCustomWriter{} log := logger.NewLoggerWithWriter(customWriter) ``` -------------------------------- ### Configure Log Level via Environment Variable Source: https://github.com/fosrl/newt/blob/main/_autodocs/README.md Set the log level to DEBUG by exporting the LOG_LEVEL environment variable. ```bash export LOG_LEVEL=DEBUG newt ``` -------------------------------- ### NewProxyManagerWithoutTNet Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/proxy-manager.md Creates a proxy manager without an attached network stack. A network stack can be attached later using `SetTNet()`. ```APIDOC ## NewProxyManagerWithoutTNet ### Description Creates a proxy manager without an attached network stack. A network stack can be attached later using `SetTNet()`. ### Returns - **ProxyManager** (*ProxyManager) - A new `*ProxyManager` instance without a network stack. ### Example ```go pm := proxy.NewProxyManagerWithoutTNet() // Later... pm.SetTNet(tnet) ``` ``` -------------------------------- ### NewLogger Source: https://github.com/fosrl/newt/blob/main/_autodocs/api-reference/logger.md Creates a new logger instance with a standard output writer. This is a constructor for the Logger type. ```APIDOC ## NewLogger ### Description Creates a new logger instance with a standard output writer. ### Returns - `*Logger`: A new `*Logger` instance. ### Example ```go log := logger.NewLogger() log.Info("Application started") ``` ```