opentunnel

package module
v0.16.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 35 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-opentunnel

Go Reference

Expose a local application over public HTTPS with OpenTunnel. Use otgo to require password or GitHub login, or embed the client in your Go app. Visitor TLS terminates in your process. Read the security model for the relay and domain operator's trust boundaries.

Install

For the CLI:

brew install darron/tap/otgo
otgo version

Or download a macOS or Linux binary from GitHub releases. Verify the SHA-256 checksum before installing.

otgo version (or otgo --version) shows the version, full Git SHA and whether the source was clean or dirty when built. Missing build metadata is unknown.

For the Go library:

go get github.com/darron/go-opentunnel

Source compatibility starts at Go 1.26. Build production binaries with the latest patched release of a supported Go version. The core client uses github.com/coder/websocket. The optional metrics adapter and otgo use the official Prometheus Go client. The optional identity verifier uses golang-jwt; otgo also uses a QR encoder and terminal detection. These do not add dependencies to the core client import. Licensed under MIT. See the changelog for release highlights and the Homebrew guide for binary installation and updates.

For private API/relay certificates, use ClientOptions.CACertFile or --ca-cert after an otgo command. See custom CA trust.

Protect a local application with otgo

  1. Save a backend under a named profile:

    otgo auth init --profile inbox --upstream http://127.0.0.1:57732
    

    Setup creates or reuses a tunnel and shows a generated password once. Save it in your password manager. Use --password-stdin to supply your own password.

  2. Start the protected proxy:

    otgo proxy --profile inbox
    
  3. Open the printed HTTPS URL or scan the terminal QR code on your phone, then sign in.

The QR code appears in interactive terminals. Use --qr=never to hide it or --qr=always to force it; --json always keeps output machine-readable.

Every backend path requires authentication, including assets, HTTP MCP, SSE and WebSockets. Use proxy for protection: the diagnostic connect and listen commands expose services directly without a login gate.

A profile saves the hostname, backend and auth settings in XDG directories. Restarting reuses those settings and requires a fresh browser login. Use different profiles for different backends; they can run concurrently on one machine. List saved profiles, clickable HTTPS URLs, backends and launch commands:

otgo profiles

This is a local inventory, so it works while proxies are running or stopped. otgo profiles --json produces structured output; --names prints only names. Profiles without a matching auth setup have no proxy launch command.

GitHub login

Stop the profile's proxy, then switch its login mode:

otgo auth github --profile inbox --allow-user darron
otgo proxy --profile inbox

Setup tries to open your default browser; the printed link is a fallback. Use --no-browser to open it yourself. The completion page shows your profile and a copyable proxy command. It requests no repository permissions. Repeat --allow-user to approve more accounts. GitHub login replaces password login. Existing OAuth/GitHub Apps are also supported.

The backend receives the verified username and numeric ID in X-GitHub-User and X-GitHub-ID, plus a signed X-Otgo-Identity assertion. Export the profile's public key with otgo auth public-key --profile inbox and use the optional identity package to verify requests. See signed backend identity for the trust boundary and an example. Password and machine-token requests do not carry GitHub identity.

For a quick offline check, pipe an assertion value into:

otgo auth verify --profile inbox --assertion-stdin --method GET --request-uri /

Use the exact backend path/query. Expired assertions show their original issuance/expiration timestamps; add --require-current to reject them. See CLI verification for clipboard usage, companion-header checks and JSON output.

Machine clients and MCP

Create a short-lived token while the proxy runs:

otgo auth token create --profile inbox --ttl 1h

Send it as Authorization: Bearer TOKEN, or use X-Otgo-Token when the backend needs its own Authorization header. Tokens grant access to the whole backend. Clients that cannot supply a session cookie or token are denied. otgo does not implement an MCP OAuth authorization server or automatic client registration.

Upgrading to v0.7.0 requires resetting and reissuing existing machine tokens; see the migration instructions.

The auth guide covers token revocation, password replacement, GitHub setup, saved file paths and HTTP compatibility.

connect supports per-route PROXY headers for a TCP backend that understands them. See the PROXY v1/v2 options. Certificate diagnostics explain typed failures and safe CLI summaries.

Embed the client

Use Client.Listen to serve an HTTP handler over the visitor's TLS connection:

package example

import (
    "context"
    "net/http"
    "time"

    opentunnel "github.com/darron/go-opentunnel"
)

func serveTunnel(ctx context.Context, handler http.Handler) error {
    store, err := opentunnel.NewXDGStorage()
    if err != nil {
        return err
    }
    client, err := opentunnel.NewClient(opentunnel.ClientOptions{Storage: store})
    if err != nil {
        return err
    }
    defer client.Close()

    listener, err := client.Listen(ctx, opentunnel.ListenOptions{
        Profile:  "demo",
        Routes:   []string{"@"},
        Lifetime: ctx,
    })
    if err != nil {
        return err
    }
    defer listener.Close()

    server := &http.Server{Handler: handler, ReadHeaderTimeout: 5 * time.Second}
    return server.Serve(listener)
}

Request.TLS contains the real handshake. RemoteAddr comes from relay metadata; HTTP forwarding headers do not override it. The library exposes your handler directly; add application authentication when it is needed.

For an existing TCP server, use Client.Connect with a route such as opentunnel.Routes{"@": "127.0.0.1:8080"}. Both APIs use the caller's context for startup. Set Lifetime to stop the running tunnel on application shutdown, or close it explicitly. Client.Close stops its owned connections and joins workers.

For startup feedback, set OnEvent on ConnectOptions or ListenOptions. Callbacks run synchronously; keep them brief and use context cancellation rather than calling Close from them. Set OnRouteConflict: opentunnel.RouteConflictFail to stop with a typed *opentunnel.AttachError when another bridge owns a route; the default retries. The diagnostic CLI exposes this as --on-route-conflict=fail on connect and listen.

connection.URLs() and listener.URLs() return copies of the configured route URLs. Use PublicURL(route, hostname) and IsValidRouteName before connecting. For provisioning progress on a reused profile, use Client.EnsureWithOptions; otgo ensure prints the same stages to stderr unless --json is selected.

The webapp example demonstrates HTTP, streaming, WebSockets and shutdown. Run go run ./examples/webapp; use --forward for TCP forwarding or --local-only for a loopback test server.

To verify GitHub authentication inside the app, follow the webapp walkthrough. Its optional identity mode checks otgo's signature on every route and exposes the verified username and numeric ID at /whoami. It runs behind otgo proxy with a pinned public key.

Read the listener guide for shutdown and peer trust, and the Go API documentation for types, methods and examples. The package reference explains routes, storage, provisioning recovery and resource limits. Identity and PendingIdentity redact credentials in standard formatting and JSON; their exported fields still contain live secrets.

Monitor a running proxy

Available in v0.9.0 and later.

Start a separate local metrics listener:

otgo proxy --profile inbox --metrics-listen 127.0.0.1:9091

Scrape http://127.0.0.1:9091/metrics. Choose a different port for each instance. Metrics are disabled by default and omit tunnel identities and credentials. Save metrics_listen in the proxy's auth config to reuse its port on startup; an explicit flag overrides it, including an empty value to disable metrics. Embedded applications can read Client.Stats() or register the optional Prometheus adapter with their own registry.

Use an outbound proxy

Set HTTPS_PROXY for the OpenTunnel API and bridge, or ALL_PROXY as a fallback. NO_PROXY bypasses matching destinations. Both uppercase and lowercase names work; settings are captured at startup. See proxy configuration and diagnostics.

Select an OpenTunnel server

The SDK and otgo use the hosted service by default. Set OPENTUNNEL_API to use a self-hosted server:

export OPENTUNNEL_API=https://tunnel.example.com
otgo ensure --profile selfhosted

An explicit Go ClientOptions.API or CLI --api wins over the environment. An unset or empty variable selects https://opentunnel.xyz; invalid values fail. HTTPS is required except for loopback HTTP addresses. The selected base URL can include a path. It controls provisioning and bridge connections, not the local backend or visitor login. It contains no credentials.

Use a separate profile/data directory for a different server: existing tunnel credentials belong to their original server. Protected profiles reject a changed API origin until explicitly reconfigured. Generated launch/resume commands include the selected API URL, including the hosted default, so another terminal's environment cannot repoint them.

Build and validate

make build builds only bin/otgo. make build-example builds the example.

make check
make race
make fuzz

make check runs tests, vet, formatting, full golangci-lint and the CLI build. See testing instructions for local and public-service checks.

Browse the documentation index for guides, security reviews and dated validation records. The v0.7.0 audit records security fixes, test-quality checks and remaining limits.

Documentation

Overview

Package opentunnel exposes local applications over OpenTunnel HTTPS. It terminates visitor TLS in your process and either serves an HTTP handler through a net.Listener or forwards decrypted bytes to a TCP backend.

Start a tunnel

Create a Client with NewClient. An empty ClientOptions.API selects OPENTUNNEL_API, then the hosted DefaultAPI. The URL is captured at construction; an explicit API overrides the environment. Zero options use persistent NewXDGStorage. Choose NewMemoryStorage for temporary identities or NewFileStorage for an application-owned directory. A profile names one stored tunnel; an empty profile selects "default".

Use Client.Listen for direct HTTP serving. Pass its Listener to net/http.Server.Serve, not ServeTLS: accepted connections have already completed TLS, and http.Request.TLS contains the actual handshake. Use Client.Connect to forward traffic to existing host:port targets instead. In both APIs, route "@" selects the root hostname; a lowercase DNS label selects that subdomain. The method examples show both paths. Set ConnectOptions.RouteOptions to emit ProxyProtocolV1 or ProxyProtocolV2 headers to a backend that supports them. Connection.SetRoutesWithOptions replaces targets and options together; SetRoutes clears forwarding options.

Lifetime and shutdown

The context passed to Connect or Listen bounds provisioning and initial attachment only. Cancelling it after a successful return does not stop the tunnel. Set Lifetime in ConnectOptions or ListenOptions to an application's shutdown context, or close the returned connection explicitly. Client.Close stops all operations and connections owned by that client.

Connection.Close and Listener.Close retain stored credentials and the remote tunnel. Use Client.Remove to delete them. Closing joins package workers and aborts active visitor sockets; it does not join application handlers or gracefully drain HTTP requests. Applications own that work.

State, routes and concurrency

Clients, connections and listeners support concurrent method calls. Construct them through NewClient, Connect and Listen; their zero values are not usable. Coordinate provisioning and route claims across separate clients or processes, even when they share storage. Within one client, overlapping routes for the same profile return ErrRouteInUse; disjoint routes may run concurrently.

Connections retry transient bridge failures. Use Connection.Status or Listener.Status for snapshots. Events are bounded and lossy; inspect DroppedEvents in Status rather than assuming every transition was delivered. Set OnEvent in ConnectOptions or ListenOptions to observe startup and running events synchronously; callbacks must return promptly and must not close their owners. Set OnRouteConflict to RouteConflictFail for a fatal route conflict; the default retries. Connection.URLs and Listener.URLs return configured URLs. PublicURL builds a URL without connecting; IsValidRouteName validates names. Wait for Done before reading the final Err. Resource bounds and timeout defaults are documented in TransportOptions.

Outbound proxies

Default transports capture HTTP_PROXY, HTTPS_PROXY and NO_PROXY at construction, with ALL_PROXY as a fallback when a scheme-specific proxy is unset. Lowercase spellings also work. API calls and bridge connections share that policy. An explicit ClientOptions.HTTPClient transport remains a trusted override. See the outbound proxy guide for bypass rules, credentials and diagnostics.

Statistics

Client.Stats, Connection.Stats and API.Stats expose concurrent operation snapshots without consuming events or starting a server. Client totals retain stopped connections. The optional metrics subpackage adapts these snapshots to the official Prometheus Go client; register its collector with an application-owned registry and protect the administrative HTTP endpoint.

Credentials and provisioning errors

Identity and PendingIdentity contain live tokens and private keys. Their JSON, fmt and slog representations redact credentials; direct field access does not. Custom Storage implementations must persist secret fields explicitly, protect them at rest and honor context cancellation. Low-level API responses, including CreateTunnelResponse, are not redacted.

Client.Get, Client.Pending and Client.Resume return (nil, nil) when no matching local identity exists. Use Client.EnsureWithOptions to observe provisioning or certificate checks while reusing an identity. Interrupted provisioning may leave a pending identity that Resume can finish or Remove can delete. If both persistence and remote cleanup fail, use errors.As to inspect ProvisioningError and securely recover or delete its Pending identity. Use errors.Is for package sentinel errors and errors.As for APIError, AttachError and CertificateIssuanceError. Certificate failures have safe classifications and HTTP status. Their bounded raw Reason is untrusted and omitted from fmt, JSON and slog output.

Authentication and trust

The library does not authenticate visitors. Add authentication to your handler or use the otgo CLI's proxy command for password/GitHub login and machine tokens. The CLI's ordinary connect and listen commands also expose services directly. Relay-provided peer metadata is not an independently verified visitor address and should not be treated as an end-to-end identity.

Set ClientOptions.CACertFile to add PEM certificates to the API and relay trust roots. For low-level NewAPI use, NewHTTPClientWithCACert builds an HTTP client with the same behavior. Certificate and hostname verification stay enabled. The library does not read OPENTUNNEL_CA_CERT; that variable belongs to otgo. This setting does not affect visitor TLS or backend connections.

The local private key never leaves the client. A normally operating relay carries encrypted visitor TLS, but the hosted domain/certificate operator remains inside the HTTPS trust boundary and could impersonate the hostname with another trusted certificate. See the security model and auth guide.

Index

Examples

Constants

View Source
const DefaultAPI = "https://opentunnel.xyz"

DefaultAPI is the hosted OpenTunnel control API endpoint.

View Source
const RootRoute = "@"

RootRoute selects the tunnel's root hostname instead of a subdomain.

View Source
const RouteLabelPattern = `^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$`

RouteLabelPattern matches a lowercase DNS label, excluding RootRoute.

View Source
const Version = "0.16.3"

Version is this module's protocol client version.

Variables

View Source
var (
	// ErrClosed reports an operation attempted after its Client, Connection, or Listener was closed.
	ErrClosed = errors.New("opentunnel: closed")
	// ErrExists reports an attempt to create a completed tunnel over an existing profile.
	ErrExists = errors.New("opentunnel: profile already has a tunnel")
	// ErrProfileChanged reports removal or replacement during provisioning.
	ErrProfileChanged = errors.New("opentunnel: profile removed or replaced during provisioning")
	// ErrInvalid reports invalid input or protocol/certificate data.
	ErrInvalid = errors.New("opentunnel: invalid input")
	// ErrRouteInUse reports overlapping routes on tunnels owned by one Client.
	ErrRouteInUse = errors.New("opentunnel: route already connected by this client")
	// ErrRouteMismatch reports a TLS hostname that differs from the relay route.
	ErrRouteMismatch = errors.New("opentunnel: TLS hostname does not match relay route")
	// ErrCertificateExpired reports a certificate at or past its NotAfter time.
	ErrCertificateExpired = fmt.Errorf("%w: certificate expired", ErrInvalid)
	// ErrCertificateIssuance reports terminal certificate issuance failure.
	ErrCertificateIssuance = errors.New("opentunnel: certificate issuance failed")
	// ErrInboundLimit reports a channel whose inbound buffer reached its limit.
	ErrInboundLimit = errors.New("opentunnel: inbound channel buffer limit exceeded")
	// ErrHalfCloseTimeout reports an observed half-close closed for subsequent inactivity.
	ErrHalfCloseTimeout = errors.New("opentunnel: half-closed channel inactivity timeout")
	// ErrIdleTimeout reports an established channel closed for inactivity.
	ErrIdleTimeout = errors.New("opentunnel: channel idle timeout")
)

Functions

func IsValidRouteName added in v0.16.0

func IsValidRouteName(route string) bool

IsValidRouteName reports whether route is RootRoute or a lowercase DNS label.

func NewHTTPClientWithCACert added in v0.13.0

func NewHTTPClientWithCACert(path string) (*http.Client, error)

NewHTTPClientWithCACert returns a client that trusts the system roots and the certificates in a PEM file. It verifies certificate chains and hostnames as usual. Use it with NewAPI for direct control API access; ClientOptions.CACertFile applies the same trust to a Client's API and relay connections. The file must contain only CERTIFICATE blocks and whitespace, up to 1 MiB. The returned client has no timeout; NewAPI supplies its operation timeout.

func PublicURL added in v0.16.0

func PublicURL(route, hostname string) (string, error)

PublicURL returns the HTTPS URL for route on hostname. Hostname must be a DNS name without a scheme, port, trailing dot, or path. Invalid input or a combined hostname longer than 253 bytes returns ErrInvalid. This does not check DNS or whether a route is attached.

Example
package main

import (
	"fmt"

	opentunnel "github.com/darron/go-opentunnel"
)

func main() {
	url, err := opentunnel.PublicURL("api", "demo.opentunnel.xyz")
	if err != nil {
		return
	}
	fmt.Println(url)
	fmt.Println(opentunnel.IsValidRouteName(opentunnel.RootRoute))
}
Output:
https://api.demo.opentunnel.xyz
true

func RouteForSNI

func RouteForSNI(sni, hostname string) (string, bool)

RouteForSNI returns "@" for hostname itself or a lowercase route label for one subdomain of hostname. Matching is case-insensitive. Unrelated hostnames and multi-label subdomains return ("", false). It does not check that a route is configured or perform certificate validation.

Example
package main

import (
	"fmt"

	opentunnel "github.com/darron/go-opentunnel"
)

func main() {
	route, ok := opentunnel.RouteForSNI("API.demo.opentunnel.xyz", "demo.opentunnel.xyz")
	fmt.Println(route, ok)
	route, ok = opentunnel.RouteForSNI("demo.opentunnel.xyz", "demo.opentunnel.xyz")
	fmt.Println(route, ok)
	_, ok = opentunnel.RouteForSNI("other.example", "demo.opentunnel.xyz")
	fmt.Println(ok)
}
Output:
api true
@ true
false

func ValidateRoutes

func ValidateRoutes(routes Routes) error

ValidateRoutes checks route names and host:port targets, returning ErrInvalid for an invalid entry or more than 128 routes per bridge. Targets use a DNS hostname or literal IP and a numeric port from 1 to 65535; URLs and Unix sockets are not accepted. Nil and empty maps are valid here, although Client.Connect requires an initial route. Validation does not resolve names, dial targets or authorize access.

Example
package main

import (
	"fmt"

	opentunnel "github.com/darron/go-opentunnel"
)

func main() {
	err := opentunnel.ValidateRoutes(opentunnel.Routes{
		"@":   "127.0.0.1:8080",
		"api": "[::1]:9090",
	})
	fmt.Println(err)
}
Output:
<nil>

Types

type API

type API struct {
	// contains filtered or unexported fields
}

API performs requests to the OpenTunnel control API, authenticating with the supplied tunnel token when required. It does not persist identities or keys. Methods may be called concurrently when the supplied HTTP client and its transport/hooks support concurrent use. Construct it with NewAPI; the zero value is not usable.

func NewAPI

func NewAPI(base string, client *http.Client, timeout time.Duration) (*API, error)

NewAPI creates an API client for base. HTTPS bases may use any host; HTTP is limited to localhost or a literal loopback IP so bearer credentials are never sent across a network in cleartext. Redirects must remain at the initial origin. The supplied client is cloned before its redirect policy is hardened; its Transport, Jar, and redirect hook remain trusted with API credentials. Nil Transport uses a default-transport clone with environment proxies, including ALL_PROXY fallback and NO_PROXY, captured at construction. An explicit Transport overrides that policy. Zero timeout selects 15 seconds; negative timeout is invalid. The timeout covers all retries, backoff and body reads. Transient failures get at most six retries following the OpenTunnel protocol; ambiguous failures of tunnel creation/deletion are never replayed. Responses are limited to 1 MiB. Use DefaultAPI for the hosted service.

func (*API) BindCertificate

func (a *API) BindCertificate(ctx context.Context, id, token, csr string) (out CertificateInfo, err error)

BindCertificate submits a PEM-encoded CSR for tunnel id using token and returns the initial issuance state. It does not poll until readiness or save the result. Stats counts each validated terminal failed response, not remote jobs/attempts.

func (*API) Certificate

func (a *API) Certificate(ctx context.Context, id, token string) (out CertificateInfo, err error)

Certificate returns the current certificate issuance state for tunnel id using token. A missing certificate returns an APIError; a failed issuance is a valid response whose State.Type is "failed" and whose State.Reason explains failure. Stats counts each validated failed response; repeated polls can count the same failed state again. It does not count remote issuance attempts or jobs.

func (*API) Create

func (a *API) Create(ctx context.Context) (out CreateTunnelResponse, err error)

Create creates a new remote tunnel and returns its public metadata and secret token. It does not generate a private key, request a certificate or save the result. Use Client.Create for the complete provisioning workflow.

func (*API) Get

func (a *API) Get(ctx context.Context, id, token string) (out TunnelInfo, err error)

Get returns the remote state of tunnel id using token. Missing tunnels return an APIError with HTTP status 404, unlike Client.Get's absent local result.

func (*API) Remove

func (a *API) Remove(ctx context.Context, id, token string) (err error)

Remove permanently removes remote tunnel id using token. Missing tunnels return an APIError with HTTP status 404. It does not stop local connections or remove stored credentials; Client.Remove performs that coordinated cleanup.

func (*API) Stats added in v0.9.0

func (a *API) Stats() Stats

Stats returns API-only completed-request and terminal certificate counters. Transport fields are zero. It includes direct low-level calls when the API belongs to a Client.

type APIError

type APIError struct {
	// StatusCode is the rejected request's HTTP response status.
	StatusCode int
	// Tag is a recognized service error tag, or HttpError for an unknown tag.
	Tag string
	// Message is diagnostic text. API-generated errors do not copy response bodies.
	Message string
}

APIError reports the remote HTTP status and a recognized protocol error tag. Unknown tags become HttpError so reflected credentials cannot reach logs.

func (*APIError) Error

func (e *APIError) Error() string

Error returns HTTP status, a normalized tag and Message.

type AttachError

type AttachError struct {
	// Code is a recognized relay error code, or unknown for an unrecognized code.
	Code string
}

AttachError reports a relay bridge attachment failure code. bad_token and cert_not_ready stop a connection; other failures are retried.

func (*AttachError) Error

func (e *AttachError) Error() string

Error returns the normalized attachment failure code.

type CertificateFailureClass added in v0.9.0

type CertificateFailureClass string

CertificateFailureClass is a bounded diagnostic cause inferred from a terminal provider reason. It does not express the server's retry policy or attempts.

const (
	CertificateFailureNetwork              CertificateFailureClass = "network"
	CertificateFailureTimeout              CertificateFailureClass = "timeout"
	CertificateFailureHTTP5xx              CertificateFailureClass = "http_5xx"
	CertificateFailureHTTP429              CertificateFailureClass = "http_429"
	CertificateFailureBadBody              CertificateFailureClass = "bad_body"
	CertificateFailureNonce                CertificateFailureClass = "nonce"
	CertificateFailureBadNonce             CertificateFailureClass = "bad_nonce"
	CertificateFailureAuthorizationPending CertificateFailureClass = "authz_pending"
	CertificateFailureDNS                  CertificateFailureClass = "dns"
	CertificateFailureRejected             CertificateFailureClass = "rejected"
	CertificateFailureOther                CertificateFailureClass = "other"
)

type CertificateInfo

type CertificateInfo struct {
	// ID identifies the service's certificate record.
	ID string `json:"id"`
	// State contains its current issuance result or challenge.
	State CertificateState `json:"state"`
}

CertificateInfo is the control API response for certificate status.

type CertificateIssuanceError added in v0.6.0

type CertificateIssuanceError struct {
	// Reason is bounded raw text received from the remote provider. It is
	// untrusted and may contain sensitive data. Do not log or display it without
	// an explicit review and redaction step.
	Reason string `json:"-"`
	// Code is a safe, normalized classification of a recognized ACME problem,
	// rate limit, or timeout. Unrecognized failures use unknown.
	Code string
	// Class is a bounded best-effort diagnostic cause, independent of Code.
	Class CertificateFailureClass
	// StatusCode is a parsed HTTP status in the range 100 through 599, or zero
	// when the provider reason contained no recognized status.
	StatusCode int
}

CertificateIssuanceError reports failed issuance or deferred recovery during its retry cooldown. Reason is available only for deliberate diagnostic inspection; ordinary formatting, JSON and structured logging expose safe derived fields.

func (CertificateIssuanceError) Error added in v0.6.0

func (e CertificateIssuanceError) Error() string

Error returns a credential-safe summary of the failure.

func (CertificateIssuanceError) Format added in v0.6.0

func (e CertificateIssuanceError) Format(s fmt.State, _ rune)

Format writes a credential-safe summary regardless of the requested verb.

func (CertificateIssuanceError) GoString added in v0.6.0

func (e CertificateIssuanceError) GoString() string

GoString returns a credential-safe summary of the failure.

func (CertificateIssuanceError) LogValue added in v0.6.0

func (e CertificateIssuanceError) LogValue() slog.Value

LogValue returns only normalized, credential-safe fields.

func (CertificateIssuanceError) MarshalJSON added in v0.6.0

func (e CertificateIssuanceError) MarshalJSON() ([]byte, error)

MarshalJSON emits only normalized, credential-safe fields.

func (CertificateIssuanceError) String added in v0.6.0

func (e CertificateIssuanceError) String() string

String returns a credential-safe summary of the failure.

func (CertificateIssuanceError) Unwrap added in v0.6.0

func (e CertificateIssuanceError) Unwrap() error

Unwrap returns ErrCertificateIssuance for errors.Is compatibility.

type CertificateState

type CertificateState struct {
	// Type is challenge, issuing, ready or failed.
	Type string `json:"type"`
	// Token is the service's ACME challenge token when Type is challenge.
	Token string `json:"token,omitempty"`
	// Key is the ACME DNS-01 TXT value, not the local TLS private key.
	Key string `json:"key,omitempty"`
	// Certificate is the PEM leaf certificate when Type is ready.
	Certificate string `json:"certificate,omitempty"`
	// Chain is the PEM certificate chain when Type is ready.
	Chain string `json:"chain,omitempty"`
	// Expiry is the certificate expiration when Type is ready.
	Expiry time.Time `json:"expiry,omitzero"`
	// Reason explains terminal issuance failure when Type is failed.
	Reason string `json:"reason,omitempty"`
}

CertificateState describes the current certificate issuance state. Type determines which other fields apply. Treat challenge material as sensitive; this API response does not redact it in JSON or ordinary formatting.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client owns provisioning operations and connections; Close cancels and joins them. Applications must coordinate same-profile provisioning across clients or processes, even when sharing a store. Methods support concurrent calls. Construct a Client with NewClient; its zero value is not usable. User-supplied Storage and HTTP hooks must also support concurrent use. Do not call Close from a provisioning progress callback.

func NewClient

func NewClient(options ClientOptions) (*Client, error)

NewClient creates an owner for provisioning and running tunnels. Zero options select OPENTUNNEL_API (or the hosted API when unset/empty), persistent XDG storage, and documented transport defaults. A nonempty API option overrides the environment; an invalid selected URL returns ErrInvalid without fallback. Call Close when the application no longer needs the client. NewClient does not contact the service or create a tunnel. Invalid API URLs, CA bundles, negative resource limits/timeouts and inconsistent backoff limits return ErrInvalid.

func (*Client) API

func (c *Client) API() *API

API returns the low-level HTTP client for remote inspection and custom workflows. Its calls use their own contexts; Client.Close does not cancel them.

func (*Client) Close

func (c *Client) Close() error

Close cancels and joins client-owned operations and connections. It is safe to call repeatedly and does not remove stored identities or remote tunnels. Calls already running through API use their own contexts and are not joined. It does not wait for application handlers and must not be called from an OnProgress callback. New client-owned operations return ErrClosed after closing.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context, o ConnectOptions) (*Connection, error)

Connect provisions and attaches a tunnel. ctx bounds startup only; cancel it after return without stopping the tunnel. Set Lifetime for context-owned shutdown. Expired identities attach to trigger server renewal, but readiness waits for a valid certificate. Overlapping routes within one client return ErrRouteInUse. Routes are copied on entry; callers must not mutate the input map while this call is running. At least one valid initial route is required. Cancellation during startup may preserve a pending identity for Client.Resume or Client.Remove.

Example
package main

import (
	"context"
	"fmt"
	"os"
	"os/signal"
	"time"

	opentunnel "github.com/darron/go-opentunnel"
)

func main() {
	startup, cancelStartup := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancelStartup()

	lifetime, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()

	client, err := opentunnel.NewClient(opentunnel.ClientOptions{})
	if err != nil {
		return
	}
	defer func() { _ = client.Close() }()

	connection, err := client.Connect(startup, opentunnel.ConnectOptions{
		Profile:  "demo",
		Routes:   opentunnel.Routes{"@": "127.0.0.1:8080"},
		Lifetime: lifetime,
	})
	if err != nil {
		return
	}
	defer func() { _ = connection.Close() }()

	// Releasing startup after attachment does not stop the running tunnel.
	cancelStartup()
	fmt.Println(connection.URLs()[opentunnel.RootRoute])
	<-connection.Done() // Ctrl-C cancels lifetime and stops the tunnel.
	if err := connection.Err(); err != nil {
		fmt.Fprintln(os.Stderr, err)
	}
}

func (*Client) Create

func (c *Client) Create(ctx context.Context, profile string, options ProvisionOptions) (*Identity, error)

Create provisions a tunnel or resumes pending issuance. A completed local identity returns ErrExists. Empty profile selects "default". Cancellation leaves persisted pending credentials available to Resume or Remove. After a known remote creation, bounded persistence or cleanup completes even if ctx is canceled. If both fail, ProvisioningError exposes credentials for manual recovery. ctx bounds the issuance wait; bounded recovery work can outlast its cancellation.

func (*Client) Ensure

func (c *Client) Ensure(ctx context.Context, profile string) (*Identity, error)

Ensure loads, resumes, or provisions a currently valid identity. Empty profile selects "default". Use Connect to attach an expired identity and trigger the hosted service's ordinary renewal; Ensure does not attach a bridge.

func (*Client) EnsureWithOptions added in v0.16.0

func (c *Client) EnsureWithOptions(ctx context.Context, profile string, o ProvisionOptions) (*Identity, error)

EnsureWithOptions is Ensure with synchronous provisioning progress reporting. A stored identity reports checking-certificate before the API check, then ready on success. Provisioning and recovery report their usual stages.

func (*Client) Get

func (c *Client) Get(ctx context.Context, profile string) (*Identity, error)

Get loads a completed local identity. An absent profile returns (nil, nil). Empty profile selects "default"; the returned identity contains credentials.

func (*Client) List

func (c *Client) List(ctx context.Context) ([]StoredTunnel, error)

List lists local completed identities with their profile names. Returned identities contain credentials even though their JSON representation omits them.

func (*Client) Listen added in v0.3.0

func (c *Client) Listen(ctx context.Context, o ListenOptions) (*Listener, error)

Listen provisions or resumes an identity and attaches its routes. ctx bounds startup only; Lifetime or Close controls the running listener. It shares route ownership with Connect: overlapping names on one client/profile are rejected. Routes are copied; callers must not mutate the slice during this call. It does not add authentication or HTTP request deadlines: those belong to the handler and http.Server. Use a finite startup context because issuance may require polling.

Example
package main

import (
	"context"
	"net/http"
	"os"
	"os/signal"
	"time"

	opentunnel "github.com/darron/go-opentunnel"
)

func main() {
	client, err := opentunnel.NewClient(opentunnel.ClientOptions{})
	if err != nil {
		return
	}
	defer func() { _ = client.Close() }()
	lifetime, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()
	startup, cancelStartup := context.WithTimeout(lifetime, 30*time.Second)
	defer cancelStartup()
	listener, err := client.Listen(startup, opentunnel.ListenOptions{
		Profile: "demo", Routes: []string{"@"}, Lifetime: lifetime,
	})
	if err != nil {
		return
	}
	defer func() { _ = listener.Close() }()
	cancelStartup() // lifetime continues to own the listener after startup.
	server := &http.Server{ReadHeaderTimeout: 5 * time.Second, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// r.TLS holds the actual handshake; RemoteAddr comes from the relay.
		if r.TLS == nil {
			http.Error(w, "HTTPS required", http.StatusBadRequest)
			return
		}
		w.WriteHeader(http.StatusNoContent)
	})}
	_ = server.Serve(listener)
}

func (*Client) Pending

func (c *Client) Pending(ctx context.Context, profile string) (*PendingIdentity, error)

Pending loads unfinished local provisioning. Absence returns (nil, nil). Empty profile selects "default"; the result contains credentials.

func (*Client) Profiles

func (c *Client) Profiles(ctx context.Context) ([]string, error)

Profiles lists sorted local profile names using the configured store, including unfinished provisioning records. It does not contact the service.

func (*Client) Remove

func (c *Client) Remove(ctx context.Context, profile string) error

Remove releases the remote tunnel, stops this client's same-profile bridges, and removes local credentials. Remote failures retain credentials for retry. Empty profile selects "default"; an absent local identity succeeds. Remote HTTP 404 is treated as successful deletion. After confirmed remote deletion, local cleanup uses its own finite timeout even if ctx is canceled. It does not remove otgo's separate authentication configuration or GitHub App.

func (*Client) Resume

func (c *Client) Resume(ctx context.Context, profile string, o ProvisionOptions) (*Identity, error)

Resume finishes pending issuance; no pending identity returns (nil, nil). Empty profile selects "default". ctx bounds the entire issuance wait.

func (*Client) Stats added in v0.9.0

func (c *Client) Stats() Stats

Stats returns all this client's API calls and transport operations, including direct API() calls and totals from connections that have already been removed. The API and transport snapshots are taken separately; no workers are blocked for the duration of a scrape. Client.Close does not cancel direct API() calls.

type ClientOptions

type ClientOptions struct {
	// API is the control API base URL. Empty selects OPENTUNNEL_API, then
	// DefaultAPI. The selection is captured when NewClient is called.
	API string
	// Storage persists identities. Nil selects XDG-backed storage.
	Storage Storage
	// HTTPClient performs API and bridge handshakes. A nil Transport uses a
	// default-transport clone with per-client HTTP_PROXY/HTTPS_PROXY, ALL_PROXY
	// fallback and NO_PROXY settings. An explicit Transport overrides that policy.
	// Custom transport, cookie jar and hooks are trusted with secrets.
	HTTPClient *http.Client
	// CACertFile adds PEM certificates to the API and relay trust roots. Empty
	// uses HTTPClient's existing trust. With a custom HTTPClient, its transport
	// must be an *http.Transport with TLS verification enabled and no custom
	// TLS dialer; it is cloned.
	// This does not change visitor TLS, backend trust, or process-wide defaults.
	CACertFile string
	// RequestTimeout limits each control API operation, including retries and
	// body reads. Zero selects 15 seconds.
	RequestTimeout time.Duration
	// Transport configures connection limits and timing.
	Transport TransportOptions
}

ClientOptions configures a Client.

type ConnectOptions

type ConnectOptions struct {
	// Profile is a lowercase DNS-label storage name; empty selects "default".
	Profile string
	// Routes must include 1 to 128 valid route-to-backend mappings per bridge.
	Routes Routes
	// RouteOptions enables local forwarding options for configured route names.
	// Missing entries forward bytes unchanged. Both maps are copied on entry.
	RouteOptions map[string]RouteOptions
	// Lifetime controls the running connection after startup. Nil leaves lifetime
	// ownership to Connection.Close and Client.Close. Connect's context bounds startup.
	Lifetime context.Context
	// OnRouteConflict defaults to RouteConflictRetry. RouteConflictFail applies
	// to both startup and later reattachments. Other values return ErrInvalid.
	OnRouteConflict RouteConflictPolicy
	// OnEvent observes every lifecycle event, including events before Connect
	// returns. Calls are synchronous and serialized, independent of the lossy
	// Events channel. The callback must return promptly and must not call Close
	// on the client, connection, or listener: Close waits for this callback.
	// Cancel a context to request shutdown from a callback instead.
	OnEvent func(Event)
}

ConnectOptions selects the profile, routes, and lifetime of a connection.

type Connection

type Connection struct {
	// contains filtered or unexported fields
}

Connection reconnects until context cancellation, Close, or a fatal attach error. Events are bounded and lossy; Status gives the current state. Done closes after all workers exit. Methods support concurrent calls. Obtain a Connection through Client.Connect; its zero value is not usable. Close does not delete the remote tunnel.

func (*Connection) Close

func (x *Connection) Close() error

Close stops the connection and joins its workers. It is safe to call repeatedly or concurrently. A normal requested close leaves Err nil; an already recorded terminal error remains available. Stored credentials and the remote tunnel remain.

func (*Connection) Done

func (x *Connection) Done() <-chan struct{}

Done closes after bridge, channel, and certificate-refresh workers exit.

func (*Connection) Err

func (x *Connection) Err() error

Err reports the terminal error after Done closes. Requested Close returns nil; explicit Lifetime cancellation returns its context error.

func (*Connection) Events

func (x *Connection) Events() <-chan Event

Events returns the bounded, lossy event stream. Repeated calls return the same channel, so multiple readers divide events rather than each receiving a copy. It closes when Done closes. Status.DroppedEvents counts omitted events.

func (*Connection) Identity

func (x *Connection) Identity() Identity

Identity returns a copy of the current identity, including credentials.

func (*Connection) SetRoutes

func (x *Connection) SetRoutes(routes Routes) error

SetRoutes clears forwarding options and updates targets for new channels. Name changes reattach asynchronously and close existing channels when the session changes. An empty map pauses attachment. Invalid routes or more than 128 routes return ErrInvalid; overlapping names on this client's same-profile connections return ErrRouteInUse. The input map is copied; do not mutate it concurrently with this call.

func (*Connection) SetRoutesWithOptions added in v0.6.0

func (x *Connection) SetRoutesWithOptions(routes Routes, options map[string]RouteOptions) error

SetRoutesWithOptions atomically replaces targets and forwarding options for new channels. Existing channels retain their options. Name changes reattach as in SetRoutes. Invalid options return ErrInvalid without changing configuration. Both maps are copied; do not mutate them concurrently with this call.

func (*Connection) Stats added in v0.9.0

func (x *Connection) Stats() Stats

Stats returns transport counters for this connection across all reattachments. API fields are zero: provisioning and refresh calls belong to Client/API scope. Snapshot reads are safe during forwarding, teardown and after Close.

func (*Connection) Status

func (x *Connection) Status() Status

Status returns a snapshot with copied route and option maps. LastError is diagnostic text.

func (*Connection) URLs added in v0.16.0

func (x *Connection) URLs() map[string]string

URLs returns a fresh map from configured routes to public HTTPS URLs. It follows SetRoutes immediately, including changes still awaiting attachment. Empty routes produce an empty map. This is configuration, not a readiness check.

type CreateTunnelResponse

type CreateTunnelResponse struct {
	// Tunnel contains the new remote tunnel's public metadata.
	Tunnel TunnelInfo `json:"tunnel"`
	// Token authenticates the new tunnel. Keep it secret and persist it securely.
	Token string `json:"token"`
}

CreateTunnelResponse is the control API response for tunnel creation. Unlike Identity, this response includes Token in JSON and ordinary formatting.

type Event

type Event struct {
	// Type is connecting, connected, disconnected, reconnecting, stopped,
	// connection-opened, connection-closed, certificate-expiring,
	// certificate-expired, certificate-renewed, certificate-refresh-failed,
	// certificate-recovery-started, or route-conflict.
	Type string `json:"type"`
	// Attempt is the retry count for connecting or reconnecting events.
	Attempt int `json:"attempt,omitempty"`
	// Session is the relay session identifier for a connected event.
	Session string `json:"session,omitempty"`
	// Routes contains relay-accepted names for connected, or all attempted names
	// for route-conflict. The relay does not identify which route conflicted.
	Routes []string `json:"routes,omitempty"`
	// Reason explains a disconnected event.
	Reason string `json:"reason,omitempty"`
	// Delay is the planned reconnect wait, encoded as integer nanoseconds in JSON.
	Delay time.Duration `json:"delay,omitempty"`
	// Conn identifies a visitor channel within its relay session. Zero is valid.
	Conn uint32 `json:"conn,omitempty"`
	// Route is the route name for a connection-opened or connection-closed event.
	Route string `json:"route,omitempty"`
	// Peer is the relay-provided address for a connection-opened event.
	// It is not an independently verified visitor identity.
	Peer string `json:"peer,omitempty"`
	// Error contains diagnostic text for a failed channel, certificate or tunnel.
	Error string `json:"error,omitempty"`
	// Expiry is the certificate expiration for expiring, expired or renewed events.
	Expiry time.Time `json:"expiry,omitzero"`
}

Event reports a lifecycle transition. Type determines which fields apply; unused fields have their zero values. Delivery is bounded and lossy; use Status.DroppedEvents to detect omissions and Status for current state.

func (Event) MarshalJSON added in v0.7.0

func (e Event) MarshalJSON() ([]byte, error)

MarshalJSON includes Conn for visitor lifecycle events even when its ID is zero. Other events omit an unused connection ID.

type Identity

type Identity struct {
	// ID identifies the remote tunnel.
	ID string `json:"id"`
	// Hostname is the tunnel's public root DNS name, without a scheme or port.
	Hostname string `json:"hostname"`
	// Token authenticates control API and relay requests. Keep it secret.
	Token string `json:"-"`
	// PrivateKey is the locally generated PKCS#8 PEM key. Keep it secret.
	PrivateKey string `json:"-"`
	// Certificate is the PEM-encoded visitor TLS leaf certificate.
	Certificate string `json:"certificate"`
	// Chain is the PEM-encoded certificate chain returned by the service.
	Chain string `json:"chain"`
	// CertificateExpiry is the stored certificate's expiration time.
	CertificateExpiry time.Time `json:"certificateExpiry"`
}

Identity holds a completed tunnel's credentials. JSON omits Token and PrivateKey; custom Storage implementations must persist those secrets separately if they need to restore an identity.

func (Identity) Format added in v0.2.0

func (i Identity) Format(s fmt.State, _ rune)

Format writes an identifier-only representation regardless of the requested verb, preventing formatted values from exposing credentials.

func (Identity) GoString added in v0.2.0

func (i Identity) GoString() string

GoString returns an identifier-only Go-syntax representation of an Identity.

func (Identity) LogValue added in v0.2.0

func (i Identity) LogValue() slog.Value

LogValue returns only non-secret identity attributes for structured logging.

func (Identity) String added in v0.2.0

func (i Identity) String() string

String returns an identifier-only representation of an Identity.

type ListenOptions added in v0.3.0

type ListenOptions struct {
	// Profile selects stored credentials; empty selects "default".
	Profile string
	// Routes contains "@" for the root hostname or lowercase DNS labels.
	// At least one initial route is required, with at most 128 per bridge;
	// duplicate names are invalid.
	Routes []string
	// Lifetime controls the running listener. Nil uses the client's lifetime.
	Lifetime context.Context
	// OnRouteConflict has the same default and behavior as ConnectOptions.OnRouteConflict.
	OnRouteConflict RouteConflictPolicy
	// OnEvent observes startup and running events as in ConnectOptions.OnEvent.
	// It must return promptly and must not synchronously close its owners.
	OnEvent func(Event)
}

ListenOptions selects a profile, SNI route names, and listener lifetime.

type Listener added in v0.3.0

type Listener struct {
	// contains filtered or unexported fields
}

Listener accepts locally terminated visitor TLS without a loopback backend. Accept returns a handshaken *tls.Conn, so http.Server.Serve preserves Request.TLS. RemoteAddr is relay-provided metadata, not an independently verified visitor IP. Closing the listener also aborts accepted connections and joins package workers. It does not join application handlers or remove stored credentials. Methods support concurrent calls. Obtain a Listener through Client.Listen; its zero value is not usable. Use http.Server.Serve, not ServeTLS.

func (*Listener) Accept added in v0.3.0

func (l *Listener) Accept() (net.Conn, error)

Accept waits through transient reconnects. Invalid visitor handshakes are rejected internally. After shutdown it waits for owned workers and returns net.ErrClosed for requested Close/client shutdown, the Lifetime context error, or the fatal *AttachError. Queued connections from dead sessions are discarded. The caller must close each accepted connection to release its admission slot.

func (*Listener) Addr added in v0.3.0

func (l *Listener) Addr() net.Addr

Addr identifies the tunnel root hostname; it is not a local TCP socket address.

func (*Listener) Close added in v0.3.0

func (l *Listener) Close() error

Close aborts Accept and active I/O, joins package workers, and retains identity. It is safe to call repeatedly or concurrently. It also aborts accepted and hijacked sockets, so http.Server.Shutdown does not provide a graceful drain through this listener. Coordinate application draining before closing it.

func (*Listener) Done added in v0.3.0

func (l *Listener) Done() <-chan struct{}

Done closes after all package-owned workers exit.

func (*Listener) Err added in v0.3.0

func (l *Listener) Err() error

Err returns the terminal error after Done. Requested Close returns nil.

func (*Listener) Events added in v0.3.0

func (l *Listener) Events() <-chan Event

Events returns bounded, lossy lifecycle events. Repeated calls return the same channel; multiple readers divide events. It closes with Done.

func (*Listener) Identity added in v0.3.0

func (l *Listener) Identity() Identity

Identity returns current credentials. Its exported fields contain secrets.

func (*Listener) SetRoutes added in v0.3.0

func (l *Listener) SetRoutes(names []string) error

SetRoutes changes accepted SNI names. Name changes reattach asynchronously and abort existing channels. An empty list pauses attachment until routes are added. Invalid or duplicate names, or more than 128 names, return ErrInvalid. Overlapping names on this client's same-profile connections return ErrRouteInUse. Names are copied; do not mutate the input slice concurrently with this call.

func (*Listener) Status added in v0.3.0

func (l *Listener) Status() Status

Status returns a snapshot. Routes maps claimed names to empty strings because listener routes have no backend targets.

func (*Listener) URLs added in v0.16.0

func (l *Listener) URLs() map[string]string

URLs returns a fresh map of configured route names to HTTPS URLs, as in Connection.URLs.

type PendingIdentity

type PendingIdentity struct {
	// ID identifies the remote tunnel awaiting issuance.
	ID string `json:"id"`
	// Hostname is the tunnel's public root DNS name.
	Hostname string `json:"hostname"`
	// Token authenticates recovery or remote deletion. Keep it secret.
	Token string `json:"-"`
	// PrivateKey is the PKCS#8 PEM key used for CSR. Keep it secret.
	PrivateKey string `json:"-"`
	// CSR is the PEM-encoded certificate signing request for this key and hostname.
	CSR string `json:"csr"`
}

PendingIdentity holds credentials and a CSR while certificate issuance is pending. JSON omits Token and PrivateKey; custom Storage implementations must persist those secrets separately if they need to resume issuance.

func (PendingIdentity) Format added in v0.2.0

func (i PendingIdentity) Format(s fmt.State, _ rune)

Format writes an identifier-only representation regardless of the requested verb, preventing formatted values from exposing credentials.

func (PendingIdentity) GoString added in v0.2.0

func (i PendingIdentity) GoString() string

GoString returns an identifier-only Go-syntax representation of a PendingIdentity.

func (PendingIdentity) LogValue added in v0.2.0

func (i PendingIdentity) LogValue() slog.Value

LogValue returns only non-secret pending identity attributes for structured logging.

func (PendingIdentity) String added in v0.2.0

func (i PendingIdentity) String() string

String returns an identifier-only representation of a PendingIdentity.

type ProvisionOptions

type ProvisionOptions struct {
	// OnProgress runs synchronously during Create, Resume, or EnsureWithOptions.
	// It must return promptly and must not reenter operations on the same profile or call
	// Client.Close, which waits for the operation invoking the callback.
	OnProgress func(ProvisionStage)
}

ProvisionOptions configures progress reporting. Its zero value disables callbacks.

type ProvisionStage

type ProvisionStage string

ProvisionStage identifies synchronous provisioning progress callbacks.

const (
	// StageCreatingTunnel reports remote tunnel creation.
	StageCreatingTunnel ProvisionStage = "creating-tunnel"
	// StageGeneratingKey reports local private-key generation.
	StageGeneratingKey ProvisionStage = "generating-key"
	// StageGeneratingCSR reports local certificate-request generation.
	StageGeneratingCSR ProvisionStage = "generating-csr"
	// StageResumingCertificate reports a persisted issuance recovery attempt.
	StageResumingCertificate ProvisionStage = "resuming-certificate"
	// StageRequestingCertificate reports CSR submission.
	StageRequestingCertificate ProvisionStage = "requesting-certificate"
	// StageWaitingCertificate reports certificate status polling.
	StageWaitingCertificate ProvisionStage = "waiting-certificate"
	// StageCheckingCertificate reports a stored identity's remote certificate check.
	StageCheckingCertificate ProvisionStage = "checking-certificate"
	// StageSavingIdentity reports completed-identity storage.
	StageSavingIdentity ProvisionStage = "saving-identity"
	// StageReady reports a completed identity ready for use.
	StageReady ProvisionStage = "ready"
)

type ProvisioningError added in v0.2.0

type ProvisioningError struct {
	// Pending contains the remote identity's recovery credentials.
	Pending PendingIdentity
	// Err is the underlying persistence or cleanup failure.
	Err error
}

ProvisioningError means a known remote creation could neither be persisted nor deleted. Pending contains secret credentials: persist them securely or pass Pending.ID and Pending.Token to API.Remove. Key/CSR may be absent if generation failed; such a record supports deletion, not Resume.

func (*ProvisioningError) Error added in v0.2.0

func (e *ProvisioningError) Error() string

Error returns a recovery-required message with the underlying failure.

func (*ProvisioningError) RecoveryIdentity added in v0.2.0

func (e *ProvisioningError) RecoveryIdentity() PendingIdentity

RecoveryIdentity returns the known credentials for secure recovery or deletion.

func (*ProvisioningError) Unwrap added in v0.2.0

func (e *ProvisioningError) Unwrap() error

Unwrap returns the underlying failure for errors.Is and errors.As.

type ProxyProtocol added in v0.6.0

type ProxyProtocol string

ProxyProtocol selects a PROXY protocol preamble on a forwarded TCP connection. The empty value forwards application bytes without a preamble.

const (
	// ProxyProtocolV1 selects the text PROXY protocol header.
	ProxyProtocolV1 ProxyProtocol = "v1"
	// ProxyProtocolV2 selects the binary header, including an authority TLV for SNI.
	ProxyProtocolV2 ProxyProtocol = "v2"
)

type RouteConflictPolicy added in v0.16.0

type RouteConflictPolicy string

RouteConflictPolicy controls how relay route conflicts are handled.

const (
	// RouteConflictRetry reconnects with backoff until the route is available.
	RouteConflictRetry RouteConflictPolicy = "retry"
	// RouteConflictFail stops with an *AttachError whose Code is "route_conflict".
	RouteConflictFail RouteConflictPolicy = "fail"
)

type RouteOptions added in v0.6.0

type RouteOptions struct {
	// ProxyProtocol is empty, ProxyProtocolV1 or ProxyProtocolV2. Peer addresses
	// originate at the relay and must not be treated as verified identities.
	ProxyProtocol ProxyProtocol `json:"proxyProtocol,omitempty"`
}

RouteOptions configures local forwarding. The backend must accept the selected PROXY protocol; ordinary HTTP servers generally do not. These options do not authenticate visitors or change the bridge protocol.

type Routes

type Routes map[string]string

Routes maps route names to backend host:port targets. "@" is the root hostname; other names are lowercase DNS labels for subdomains.

type Stats added in v0.9.0

type Stats struct {
	// APIRequests counts completed logical API operations, including failures.
	// Internal retries count once; intermediate failures are not APIErrors.
	// APIErrors counts transport, body, decoding, validation and HTTP status errors.
	// APIDuration includes all attempts, backoff, body reads and validation.
	// Inputs rejected before an HTTP request is attempted do not count.
	APIRequests, APIErrors uint64
	APIDuration            time.Duration
	// CertificateFailures counts validated terminal failed Certificate and
	// BindCertificate responses, by diagnostic class. Polling the same failed
	// state again counts another response, not another remote job or attempt.
	// This map is copied independently in each snapshot.
	CertificateFailures map[CertificateFailureClass]uint64
	// BridgeAttempts counts attach attempts; Reconnects counts attempts after the
	// first on each Connection. BridgeFailures counts unsuccessful attachment,
	// including cancellation, rather than teardown of an established bridge.
	BridgeAttempts, BridgeAttachments, BridgeFailures, Reconnects uint64
	// ConnectionsOpened/Closed count each admitted relay visitor once. Rejected
	// admissions count separately. ActiveConnections includes TLS handshakes and
	// handshaken listener visitors waiting for Accept.
	ConnectionsOpened, ConnectionsClosed, ConnectionsRejected uint64
	// BytesReceived/Sent count relay data-frame payload bytes received/successfully
	// sent, including TLS headers and handshakes, excluding relay frame headers
	// and WebSocket framing/control traffic. Successfully sent chunks
	// count even when a later chunk of the same write fails.
	// Incoming totals include data later rejected for an unknown/full channel.
	BytesReceived, BytesSent uint64
	// DroppedEvents counts omissions from bounded Events channels.
	DroppedEvents uint64
	// Current gauges converge to zero after their owner closes.
	ActiveBridges, ActiveConnections, InboundBufferedBytes int64
}

Stats is a copied snapshot of cumulative counters and current gauges. Counters survive connection shutdown. Concurrent operations may progress between snapshots. It contains no tunnel, route, visitor, session or credential metadata.

type Status

type Status struct {
	// State is connecting, connected, reconnecting, waiting-routes or stopped.
	State string `json:"state"`
	// Hostname is the tunnel's public root DNS name.
	Hostname string `json:"hostname"`
	// Routes is a copy of the locally configured routes. Listener targets are empty.
	Routes Routes `json:"routes"`
	// RouteOptions is a copy of the local forwarding options. Listeners have none.
	RouteOptions map[string]RouteOptions `json:"routeOptions,omitempty"`
	// Session is the current relay session identifier, empty when unattached.
	Session string `json:"session,omitempty"`
	// Connections counts visitor channels, including handshaking and queued sockets.
	Connections int `json:"connections"`
	// LastError is diagnostic text, cleared after a successful bridge attachment.
	// It is not a typed error; use Connection.Err or Listener.Err for terminal errors.
	LastError string `json:"lastError,omitempty"`
	// ConnectedAt is the most recent successful attachment time, zero before the first.
	ConnectedAt time.Time `json:"connectedAt,omitzero"`
	// DroppedEvents counts lifecycle events omitted because the event buffer was full.
	DroppedEvents uint64 `json:"droppedEvents"`
}

Status is a snapshot of one connection. DroppedEvents counts events omitted because its bounded event channel was full.

type Storage

type Storage interface {
	// Profiles returns sorted profile names.
	Profiles(context.Context) ([]string, error)
	// Load returns a completed identity, or (nil, nil) when absent.
	Load(context.Context, string) (*Identity, error)
	// Save persists a completed identity and clears any pending identity.
	Save(context.Context, string, Identity) error
	// LoadPending returns a pending identity, or (nil, nil) when absent.
	LoadPending(context.Context, string) (*PendingIdentity, error)
	// SavePending persists an issuance recovery record.
	SavePending(context.Context, string, PendingIdentity) error
	// Remove removes the profile's credentials.
	Remove(context.Context, string) error
	// List returns all completed identities with their profile names.
	List(context.Context) ([]StoredTunnel, error)
}

Storage persists profiles. Implementations must support concurrent calls and cancellation. Missing identities return (nil, nil). Save must clear any pending identity only after successfully storing the completed identity.

func NewFileStorage

func NewFileStorage(root string) Storage

NewFileStorage stores profiles directly below root using the upstream file layout. It creates directories on save, with private directory/file modes on Unix, and rejects symlinked profile paths and credential files. Each store serializes its methods, but separate stores/processes must coordinate provisioning. File replacement is atomic per file, not across an identity's files; a crash can leave mixed generations. It does not change an existing root's mode or implement Windows ACL validation. Constructing the store performs no I/O.

func NewMemoryStorage

func NewMemoryStorage() Storage

NewMemoryStorage returns an empty, concurrent store held only in memory. It keeps no files and its credentials disappear when the store is discarded.

Example
package main

import (
	"context"
	"fmt"

	opentunnel "github.com/darron/go-opentunnel"
)

func main() {
	ctx := context.Background()
	store := opentunnel.NewMemoryStorage()
	if err := store.Save(ctx, "demo", opentunnel.Identity{
		ID: "example-id", Hostname: "demo.opentunnel.xyz",
	}); err != nil {
		fmt.Println(err)
		return
	}
	identity, err := store.Load(ctx, "demo")
	if err != nil {
		fmt.Println(err)
		return
	}
	if identity != nil {
		fmt.Println(identity.Hostname)
	}
}
Output:
demo.opentunnel.xyz

func NewXDGStorage

func NewXDGStorage() (Storage, error)

NewXDGStorage uses $XDG_DATA_HOME/opentunnel, falling back to ~/.local/share/opentunnel for upstream compatibility. Relative XDG_DATA_HOME values are ignored. An unavailable home directory returns an error when the fallback is needed. No directories are created until saving.

type StoredTunnel

type StoredTunnel struct {
	// Profile is the local storage name associated with Tunnel.
	Profile string `json:"profile"`
	// Tunnel is the completed identity, including live credential fields.
	Tunnel Identity `json:"tunnel"`
}

StoredTunnel associates a stored completed identity with its profile name.

type TransportOptions

type TransportOptions struct {
	// MaxConnections defaults to 256 concurrent visitor channels.
	MaxConnections int
	// EventBuffer defaults to 256 queued lossy lifecycle events.
	EventBuffer int
	// MaxInboundBytes defaults to 8 MiB buffered per visitor channel.
	MaxInboundBytes int
	// MaxInboundTotalBytes defaults to 64 MiB buffered across all visitor
	// channels in one relay session.
	MaxInboundTotalBytes int
	// AttachTimeout defaults to 10 seconds for one bridge attachment.
	AttachTimeout time.Duration
	// HandshakeTimeout defaults to 10 seconds for each visitor TLS handshake.
	HandshakeTimeout time.Duration
	// DialTimeout defaults to 10 seconds for each backend dial.
	DialTimeout time.Duration
	// WriteTimeout defaults to 10 seconds for each bridge write and PROXY header write.
	WriteTimeout time.Duration
	// CertificatePollInterval defaults to 2 seconds while issuance is pending.
	CertificatePollInterval time.Duration
	// CertificateRefreshInterval defaults to 12 hours between renewal checks.
	CertificateRefreshInterval time.Duration
	// CertificateDueInterval defaults to 1 minute between checks in the renewal window.
	CertificateDueInterval time.Duration
	// CertificateRetryInterval defaults to 1 hour between failed-issuance CSR
	// submissions. The cooldown is shared by this client's same-profile bridges.
	CertificateRetryInterval time.Duration
	// BackoffMin defaults to 250 milliseconds for bridge reconnection.
	BackoffMin time.Duration
	// BackoffMax defaults to 30 seconds for bridge reconnection.
	BackoffMax time.Duration
	// IdleTimeout closes inactive established channels. Connect counts application
	// bytes; Listen counts TLS records read/written by the application. Zero disables it.
	IdleTimeout time.Duration
	// HalfCloseTimeout defaults to 60 seconds of inactivity after an observed
	// half-close. Negative values are invalid. Application bytes and successful
	// transport chunks extend it, including progress within a pending TLS Write.
	// Fully open idle streams are unaffected. Connect observes either copy reaching
	// EOF. Listen observes explicit relay end or raw CloseWrite; it cannot observe
	// encrypted TLS close_notify itself. Applications must close accepted
	// connections. Listen counts transport record activity.
	HalfCloseTimeout time.Duration
}

TransportOptions sets resource limits and timeouts. Zero values select defaults, except IdleTimeout, which stays disabled. Negative values are invalid, and BackoffMax must be at least BackoffMin after defaults are applied. The relay has no per-channel flow control; sustained outbound backpressure can delay other channels. Inbound overflow resets the affected channel.

type TunnelInfo

type TunnelInfo struct {
	// ID identifies the remote tunnel.
	ID string `json:"id"`
	// Hostname is its public root DNS name.
	Hostname string `json:"hostname"`
	// State is online or offline as reported by the service.
	State string `json:"state"`
	// CertificateID identifies its certificate, if assigned.
	CertificateID string `json:"certificateID,omitempty"`
}

TunnelInfo is the public remote state of a tunnel.

Directories

Path Synopsis
cmd
otgo command
otgo exercises the public opentunnel package for testing and diagnostics.
otgo exercises the public opentunnel package for testing and diagnostics.
examples
webapp command
webapp serves HTTP/WebSocket through a tunnel TLS listener or a loopback target.
webapp serves HTTP/WebSocket through a tunnel TLS listener or a loopback target.
Package identity verifies the GitHub identity assertions sent by otgo to a protected backend.
Package identity verifies the GitHub identity assertions sent by otgo to a protected backend.
internal
authproxy
Package authproxy implements otgo's private HTTP authentication boundary.
Package authproxy implements otgo's private HTTP authentication boundary.
Package metrics adapts OpenTunnel statistics to the official Prometheus collector interface.
Package metrics adapts OpenTunnel statistics to the official Prometheus collector interface.
scripts
auth-smoke command
This backend and WebSocket probe are fixtures for the opt-in public-service smoke test.
This backend and WebSocket probe are fixtures for the opt-in public-service smoke test.
proxy-smoke command
proxy-smoke creates one temporary public tunnel, checks SDK startup/conflicts and PROXY forwarding, then deletes it.
proxy-smoke creates one temporary public tunnel, checks SDK startup/conflicts and PROXY forwarding, then deletes it.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址