tunnel

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 16 Imported by: 0 modules, 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.

Documentation

Overview

Package tunnel is how homed reaches the internet: a Cloudflare Tunnel run by cloudflared as homed's child process (MCP Gatekeeper's tunnel/cloudflare Supervisor), in one of two modes:

  • named: the owner's own domain. Connect creates the tunnel with the cloudflared CLI (the login link, the tunnel, the DNS record, config.yml in <data dir>/tunnel); the first-run page and `homed cloudflare connect <host>` run it;
  • quick: a trycloudflare.com link, no account and no domain, "for trying": its host is random and changes at every start, which kills every passkey and connector of the old host (the passkeys' relying party is the host).

A Manager keeps the child up and says where the hub is (State): the public URL is the passkeys' relying party, the OAuth issuer and the MCP URL, so homed rebuilds its gatekeeper stack whenever it changes (Options.OnState). The supervisor's probe is the hub's self-check: GET https://<host>/healthz must come back with this hub's X-Homie-Instance, so a tunnel that reaches another hub, or none, never counts as connected.

Index

Constants

View Source
const (
	JobRunning = "running"
	JobOK      = "ok"
	JobFailed  = "failed"
)

The states of a ConnectJob.

View Source
const (
	ModeOff   = "off"
	ModeNamed = "named"
	ModeQuick = "quick"
)

Modes, as homed.yaml's tunnel.mode says them.

View Source
const CodeDNSExists = "dns_exists"

CodeDNSExists is ConnectJob.Code when the hostname already has a DNS record: connecting again with overwriteDNS replaces it, so the page asks the owner first.

View Source
const InstanceHeader = "X-Homie-Instance"

InstanceHeader carries the hub's instance id on every answer of the public listener; the probe looks for it.

View Source
const MCPPath = "/mcp"

MCPPath is the hub's one MCP endpoint, the whole home (core.SingleResource{At: "/mcp", ID: "home"}).

View Source
const NamePrefix = "homie-"

NamePrefix starts the names of the tunnels Connect creates ("homie-home-example-com"). A hub keeps it: it is the name of tunnels already created.

Variables

This section is empty.

Functions

func Cloudflared

func Cloudflared(configured string) (string, error)

Cloudflared is FindCloudflared for a daemon that starts anyway. When nothing is found it still returns what to run, with the error: the configured value as it stands, so an explicit tunnel.cloudflared that is missing fails when the tunnel starts and is never swapped for another cloudflared from PATH (a fake one in a test must never fall back to the real one, which would talk to Cloudflare); "cloudflared" when nothing is configured.

func Commands

func Commands(m *Manager, audit Auditor, ownerReady OwnerReady) []adminsock.Command

Commands are the admin socket's `cloudflare …` commands over m (`homed cloudflare …` while homed runs):

cloudflare connect <host> [--overwrite-dns]   connect the owner's domain; prints the Cloudflare login link, waits
cloudflare quick                              a quick tunnel, for trying (only while no tunnel is configured)
cloudflare status                             the mode, the state and the public and MCP URLs
cloudflare disconnect                         stop the tunnel; the hub is no longer reachable from the internet

func ConnectOffline

func ConnectOffline(ctx context.Context, o Options, hostname string, overwriteDNS bool, out io.Writer) (cloudflare.Record, error)

ConnectOffline is `homed cloudflare connect` while homed is not running: the same flow in this process, writing to out (the login link included) and into dir. The caller stores the mode in homed.yaml.

func FindCloudflared

func FindCloudflared(configured string) (string, error)

FindCloudflared returns the cloudflared to run: configured (homed.yaml tunnel.cloudflared: a path, or a name looked up in PATH), else "cloudflared" in PATH, else the one next to the homed binary (where the Linux installer puts it).

func ParseConnectArgs

func ParseConnectArgs(args []string) (host string, overwrite bool, err error)

ParseConnectArgs reads `<host> [--overwrite-dns]` (the flag on either side).

Types

type Auditor

type Auditor func(ctx context.Context, e core.AuditEntry)

Auditor appends an entry to the admin audit; the commands audit what they change.

type ChildLog

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

ChildLog is cloudflared's output in a file of the data dir (0600), rotated like the plugins' logs. It is safe for concurrent use; a file error is reported once to onError and then ignored, so the tunnel never stops for its log.

func NewChildLog

func NewChildLog(path string, onError func(error)) *ChildLog

NewChildLog returns the log at path; its directory is made 0700 when missing. onError may be nil.

func (*ChildLog) Close

func (l *ChildLog) Close() error

Close closes the file.

func (*ChildLog) Write

func (l *ChildLog) Write(p []byte) (int, error)

Write appends p, rotating first when the file is full.

type ConnectJSON

type ConnectJSON struct {
	Hostname  string `json:"hostname"`
	State     string `json:"state"`
	Step      string `json:"step"`
	LoginURL  string `json:"loginUrl,omitempty"`
	Error     string `json:"error,omitempty"`
	Code      string `json:"code,omitempty"`
	StartedAt string `json:"startedAt"`
	EndedAt   string `json:"endedAt,omitempty"`
}

ConnectJSON is ConnectJob as the first-run page sends it.

type ConnectJob

type ConnectJob struct {
	Hostname string
	State    string // JobRunning, JobOK or JobFailed
	// Step is the step it is at, or failed in: login, tunnel, dns or config (cloudflare.Step*).
	Step string
	// LoginURL is Cloudflare's authorization link, once cloudflared printed it. It is for the operator only: whoever
	// opens it first picks the Cloudflare account; it is never logged.
	LoginURL  string
	Error     string // why it failed, English
	Code      string // a failure a client may act on: CodeDNSExists; empty otherwise
	StartedAt time.Time
	EndedAt   time.Time // zero while running
	// contains filtered or unexported fields
}

ConnectJob is a connect of the owner's domain, as the first-run page and `homed cloudflare connect` follow it.

func (ConnectJob) JSON

func (j ConnectJob) JSON() ConnectJSON

JSON is j on the wire.

type Manager

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

Manager runs the tunnel. It is safe for concurrent use.

func New

func New(o Options) (*Manager, error)

New checks the options and returns a stopped Manager.

func (*Manager) Check

func (m *Manager) Check(ctx context.Context) Status

Check runs the probe now against the current URL and returns the status with its result: the supervisor's own probe stops once it passed, so this is how the admin re-checks a tunnel that is up.

func (*Manager) Connect

func (m *Manager) Connect(hostname string, overwriteDNS bool) (ConnectJob, error)

Connect starts connecting the owner's domain hostname in the background: the Cloudflare login (Job().LoginURL as soon as cloudflared prints it), the tunnel, the DNS record (replacing a record only with overwriteDNS) and config.yml in the tunnel directory. When it succeeds, the mode named and the host are stored in homed.yaml and the named tunnel replaces the running one, a quick tunnel included. One connect runs at a time (core.ErrConflict); a bad host name wraps cloudflare.ErrHostname. Whether a domain that is connected may be replaced is the caller's rule.

func (*Manager) Disconnect

func (m *Manager) Disconnect() error

Disconnect stops the tunnel and stores mode off. A connect that is still running (waiting for the Cloudflare login, say) is cancelled, so it can never bring the hub back onto the internet later. The tunnel directory stays, so a later connect of the same domain reuses the tunnel.

func (*Manager) Job

func (m *Manager) Job() (ConnectJob, bool)

Job returns the running or the last connect job; ok is false when there was none since homed started.

func (*Manager) Probe

func (m *Manager) Probe(ctx context.Context, publicURL string) error

Probe is the self-check: GET publicURL/healthz must answer 200 with this hub's instance id.

func (*Manager) Quick

func (m *Manager) Quick() error

Quick switches a hub without a tunnel to a quick tunnel and stores the mode. A hub whose domain is connected keeps it (core.ErrConflict): disconnect it first.

func (*Manager) Restart

func (m *Manager) Restart() error

Restart starts the child again (the admin's reconnect). A quick tunnel gets a new host: every passkey and connector of the old one stops working.

func (*Manager) Start

func (m *Manager) Start(ctx context.Context, mode, hostname string) error

Start runs the tunnel homed.yaml asks for: mode off runs nothing; named needs the tunnel Connect made for hostname (tunnel.json must name it); quick starts a quick tunnel. A child that cannot start (cloudflared missing, no tunnel connected) is an error, and the status says why; homed then runs without the tunnel. The children run until ctx ends or Stop.

func (*Manager) State

func (m *Manager) State() State

State returns where the hub is reachable now.

func (*Manager) Status

func (m *Manager) Status() Status

Status returns the tunnel's status now.

func (*Manager) Stop

func (m *Manager) Stop()

Stop ends the child; the mode stays.

type Options

type Options struct {
	// Dir is the tunnel directory, <data dir>/tunnel (0700): a named tunnel's config.yml, credentials.json and
	// tunnel.json, and the child's private HOME.
	Dir string
	// Service is where cloudflared forwards, the hub's loopback listener, e.g. http://127.0.0.1:8080.
	Service string
	// Binary is cloudflared (FindCloudflared).
	Binary string
	// InstanceID is what the probe expects in X-Homie-Instance.
	InstanceID string
	// Save stores the mode and host in homed.yaml. Required for Connect, Quick and Disconnect.
	Save Saver
	// OnState is called when the mode or the public URL changes (a quick tunnel's new host, a connect, a disconnect),
	// on the goroutine that changed it; it should return soon.
	OnState func(State)
	// Runner runs the cloudflared CLI for Connect; nil is cloudflare.ExecRunner{Binary}.
	Runner cloudflare.Runner
	// ProbeClient fetches https://<host>/healthz; nil is a client with a 10 s timeout. Tests route it to the listener.
	ProbeClient *http.Client
	// ChildLog receives cloudflared's output (homed passes <data dir>/logs/cloudflared.log); nil discards it.
	ChildLog io.Writer
	// Logger gets the manager's own events; nil discards them.
	Logger *slog.Logger
	// Clock stamps the statuses and the connect jobs; nil is time.Now.
	Clock core.Clock
}

Options configures a Manager.

type OwnerReady

type OwnerReady func(ctx context.Context) (bool, error)

OwnerReady reports whether the home's owner can sign in at the current public URL (a passkey of its host); the connect and quick commands then say how to get one when not. Nil never says it.

type Saver

type Saver func(mode, hostname string) error

Saver stores the tunnel's mode and host in homed.yaml (config.Update); the Manager calls it when a connect, a switch to quick or a disconnect changes them, before the new tunnel starts.

type State

type State struct {
	Mode string
	URL  string
	Host string
}

State is where the hub is reachable: the mode and the public URL (https://<host>, the passkeys' relying party and the OAuth issuer). URL and Host are empty while there is none: mode off, or a quick tunnel whose host is not known yet.

type Status

type Status struct {
	Mode string
	// State is the supervisor's: starting, probing, connected, failing or stopped (mode off).
	State     string
	URL       string // https://<host>; "" while unknown
	Hostname  string // the named tunnel's host
	Since     time.Time
	LastError string
}

Status is the tunnel as the admin and the first-run page show it.

func (Status) JSON

func (s Status) JSON() StatusJSON

JSON is s on the wire.

type StatusJSON

type StatusJSON struct {
	Mode      string `json:"mode"`
	State     string `json:"state"`
	URL       string `json:"url,omitempty"`
	MCPURL    string `json:"mcpUrl,omitempty"`
	Hostname  string `json:"hostname,omitempty"`
	Since     string `json:"since,omitempty"`
	LastError string `json:"lastError,omitempty"`
}

StatusJSON is TunnelStatus as /api/home/tunnel and the first-run page send it.

Directories

Path Synopsis
Package tunneltest gives tests a fake cloudflared: internal/tunnel/testdata/fakecloudflared, built once per test binary and copied, with its own control directory, for each test.
Package tunneltest gives tests a fake cloudflared: internal/tunnel/testdata/fakecloudflared, built once per test binary and copied, with its own control directory, for each test.

Jump to

Keyboard shortcuts

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