cloudflare

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 18 Imported by: ? 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 cloudflare creates an application's Cloudflare Tunnel with the cloudflared CLI, the way findmy-mcp-bridge does (src/tunnel.mjs), with no Cloudflare API token. Family Hub's `hub admin cloudflare connect` is a thin command over Connector.Connect:

  1. `cloudflared tunnel login` prints an authorization link; the operator opens it and picks the zone. cloudflared then saves the account certificate (cert.pem) in a temporary HOME.
  2. `cloudflared tunnel create` makes the tunnel and writes its credentials into the tunnel directory, unless the directory already holds a tunnel of an earlier run, which is reused.
  3. `cloudflared tunnel route dns` points the hostname at the tunnel (a CNAME), replacing a record only with ConnectOptions.OverwriteDNS (--overwrite-dns).
  4. config.yml and tunnel.json are written into the tunnel directory (0600).
  5. The account certificate is deleted, whatever happened: only the tunnel's own credentials stay.

The cloudflared service of the application's stack runs the tunnel from that directory, mounted at the same path. The cloudflared binary is reached through Runner, so tests (and applications that run it elsewhere) inject their own.

Connector.Start runs the same flow in the background for a web page, reporting Steps (the authorization link as soon as cloudflared prints it). A desktop application that has no cloudflared service of its own runs the child with a Supervisor, either on the tunnel directory (Named) or as a quick tunnel (Quick: no account, a random hostname).

Index

Constants

View Source
const (
	ConfigFile      = "config.yml"
	CredentialsFile = "credentials.json"
	RecordFile      = "tunnel.json"
)

Files inside the tunnel directory.

View Source
const (
	LoginTimeout   = 15 * time.Minute // a hard cap: cloudflared itself stops waiting for the operator after a few minutes
	CommandTimeout = 2 * time.Minute
)

Timeouts of the cloudflared steps.

View Source
const (
	StepLogin  = "login"  // cloudflared prints the authorization link; the operator opens it and picks the zone
	StepTunnel = "tunnel" // the tunnel is created (or the directory's own is reused)
	StepDNS    = "dns"    // the hostname is pointed at the tunnel
	StepConfig = "config" // config.yml and tunnel.json are written, the account certificate is deleted
)

Names of the steps of the connect flow, in order.

View Source
const (
	MinBackoff = time.Second
	MaxBackoff = time.Minute
)

Restart backoff and the other timing defaults.

View Source
const DefaultNamePrefix = "mcp-gatekeeper-"

DefaultNamePrefix starts the name of a tunnel the connector creates, when Options.NamePrefix is empty.

Variables

View Source
var ErrDNSRecordExists = errors.New("the DNS record already exists")

ErrDNSRecordExists marks a connect that stopped because the hostname already has a DNS record that cloudflared will replace only with ConnectOptions.OverwriteDNS. Test it with errors.Is; the message is for people.

View Source
var ErrHostname = errors.New("bad hostname")

ErrHostname marks a hostname the command refuses.

Functions

This section is empty.

Types

type ConnectOptions

type ConnectOptions struct {
	Hostname     string
	OverwriteDNS bool
}

ConnectOptions are the choices of one connect.

type Connector

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

Connector runs the connect flow.

func New

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

New validates o and returns a Connector.

func (*Connector) Connect

func (c *Connector) Connect(ctx context.Context, o ConnectOptions, out io.Writer) (Record, error)

Connect runs the whole flow, printing progress and the authorization link to out.

func (*Connector) Dir

func (c *Connector) Dir() string

Dir is the tunnel directory.

func (*Connector) Start added in v0.2.0

func (c *Connector) Start(ctx context.Context, o ConnectOptions, progress func(Step)) (*Flow, error)

Start runs the flow of Connect in the background, so a web page or a command can follow it: progress is called for every Step, in order and never concurrently, and the authorization link comes as soon as cloudflared prints it. progress runs on the flow's own goroutine and should return quickly; it may be nil.

A bad hostname or a flow already running (Connect or Start) is returned at once. ctx bounds the whole flow; Flow.Cancel stops it too. The connector runs one flow at a time until Wait returns or Done is closed.

type ExecRunner

type ExecRunner struct {
	Binary string
}

ExecRunner runs the cloudflared binary at Binary (a name looked up in PATH, or a path).

func (ExecRunner) Run

func (r ExecRunner) Run(ctx context.Context, env, args []string, line func(string)) (string, error)

Run implements Runner.

type Flow added in v0.2.0

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

Flow is a connect running in the background.

func (*Flow) Cancel added in v0.2.0

func (f *Flow) Cancel()

Cancel stops the flow: cloudflared is killed and the temporary HOME with the account certificate is removed.

func (*Flow) Done added in v0.2.0

func (f *Flow) Done() <-chan struct{}

Done is closed when the flow has ended, in success or not.

func (*Flow) Wait added in v0.2.0

func (f *Flow) Wait() (Record, error)

Wait blocks until the flow has ended and returns what Connect would.

type Mode added in v0.2.0

type Mode string

Mode is how the Supervisor runs cloudflared.

const (
	// Named runs the tunnel the Connector made: `cloudflared tunnel --no-autoupdate --config <Dir>/config.yml run`.
	Named Mode = "named"
	// Quick runs a quick tunnel, no account and no domain: `cloudflared tunnel --no-autoupdate --metrics <addr>
	// --url <Service>`. Its hostname is random and changes at every start, and is read from cloudflared's own output
	// only; it is "for trying" (no uptime promise, no Server-Sent Events, 200 requests in flight).
	Quick Mode = "quick"
)

The two modes.

type Options

type Options struct {
	// Runner runs cloudflared; nil is ExecRunner{Binary: "cloudflared"}.
	Runner Runner
	// Dir is the tunnel directory, the same path in the application and in cloudflared. Required.
	Dir string
	// Service is where the tunnel sends the traffic, e.g. http://fh-hub:8080. Required.
	Service string
	// TempDir is where the temporary HOME is made; "" is os.TempDir.
	TempDir string
	// NamePrefix starts the tunnel's name (the prefix and the host with dashes, e.g. "family-hub-hub-example-com");
	// "" is DefaultNamePrefix. An application keeps its value: it is the name of tunnels already created.
	NamePrefix string
	// StartHint is printed last, how to start the tunnel (e.g. "docker compose restart cloudflared"); "" prints
	// nothing.
	StartHint string
}

Options configure a Connector.

type Record

type Record struct {
	Name     string `json:"name"`
	ID       string `json:"id"`
	Hostname string `json:"hostname,omitempty"`
}

Record is tunnel.json: which tunnel the directory holds and where it points.

func ReadRecord

func ReadRecord(dir string) (Record, error)

ReadRecord reads tunnel.json of dir; a missing file is the zero Record and no error.

type Runner

type Runner interface {
	// Run runs cloudflared with args in exactly the environment env, calls line (when not nil) with every line of its
	// output as it comes, and returns the whole output. A non-zero exit is an error.
	Run(ctx context.Context, env, args []string, line func(string)) (string, error)
}

Runner runs the cloudflared CLI.

type State added in v0.2.0

type State string

State is where the Supervisor's tunnel stands.

const (
	StateStarting  State = "starting"  // cloudflared was started (named: with a Probe this lasts an instant) or has no hostname yet (quick)
	StateProbing   State = "probing"   // the public URL is known and Probe has not passed yet
	StateConnected State = "connected" // the tunnel is up (and the probe passed, when there is one)
	StateFailing   State = "failing"   // cloudflared exited; a restart is waiting for its backoff
	StateStopped   State = "stopped"   // not started, or Stop was called
)

The states.

type Status added in v0.2.0

type Status struct {
	State State `json:"state"`
	// URL is the public address, https://<host>: the named tunnel's hostname, or the quick tunnel's current one
	// (empty while cloudflared has not announced it yet).
	URL string `json:"url,omitempty"`
	// Since is when State last changed.
	Since time.Time `json:"since"`
	// LastError is the last failure (cloudflared exited, or the probe failed); it clears when the tunnel connects.
	LastError string `json:"lastError,omitempty"`
}

Status is a snapshot of the Supervisor.

type Step added in v0.2.0

type Step struct {
	Name     string
	LoginURL string
	Done     bool
	Err      error
}

Step is one report of an asynchronous connect (Connector.Start).

A step is reported when it begins ({Name}), once more with LoginURL as soon as cloudflared prints the link (only the login step), and when it ends: {Name, Done: true}, or {Name, Done: true, Err: err} when it failed, which ends the whole flow.

type Supervisor added in v0.2.0

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

Supervisor runs one cloudflared child and keeps it up, with restarts on a backoff from MinBackoff to MaxBackoff.

The child gets a private empty HOME (Dir/home, 0700), so a ~/.cloudflared of the user can never change or block it, and a minimal environment: HOME and the PATH of the binary. No secret is ever put in its arguments; a named tunnel reads its credentials file.

func NewSupervisor added in v0.2.0

func NewSupervisor(o SupervisorOptions) (*Supervisor, error)

NewSupervisor validates o. cloudflared itself is looked for in Start.

func (*Supervisor) Start added in v0.2.0

func (s *Supervisor) Start(ctx context.Context) error

Start checks that cloudflared (and, for Named, the connected tunnel) is there, then runs the child in the background until ctx ends or Stop is called. A Supervisor starts once.

func (*Supervisor) Status added in v0.2.0

func (s *Supervisor) Status() Status

Status returns a snapshot.

func (*Supervisor) Stop added in v0.2.0

func (s *Supervisor) Stop()

Stop ends the child (SIGTERM, then a kill after a few seconds), waits for it and leaves the state stopped.

type SupervisorOptions added in v0.2.0

type SupervisorOptions struct {
	// Mode is Named or Quick. Required.
	Mode Mode
	// Binary is the cloudflared to run, a name looked up in PATH or a path; "" is "cloudflared".
	Binary string
	// Dir is the tunnel directory of the Connector (Named: it holds config.yml, credentials.json and tunnel.json).
	// The child's private HOME is Dir/home. Required.
	Dir string
	// Service is where a quick tunnel sends the traffic, e.g. http://127.0.0.1:8080. Quick only, required there.
	Service string
	// MetricsAddr is the loopback address of a quick tunnel's metrics server; "" is 127.0.0.1:0, a free port picked at
	// each start. Quick only. Its /quicktunnel only confirms the hostname cloudflared printed (a log line either way):
	// another local program could hold the port, so the hostname is never taken from there.
	MetricsAddr string
	// Probe checks the public URL end to end (an application typically fetches a well-known path through it). While it
	// fails the state is probing and its error is the LastError; nil means "connected as soon as cloudflared says so".
	Probe func(ctx context.Context, publicURL string) error
	// OnURL is called when a quick tunnel's hostname appears in cloudflared's output or changes (every restart makes a
	// new one), with https://<host>. It runs on the supervisor's goroutine and should return quickly. Named mode never
	// calls it.
	OnURL func(url string)
	// Log receives cloudflared's output, line by line: the application's rotating writer. nil discards it.
	Log io.Writer
	// Logger receives the supervisor's own events; nil discards them.
	Logger *slog.Logger
	// Clock is the source of Status.Since; nil is time.Now.
	Clock core.Clock
}

SupervisorOptions configure a Supervisor.

Jump to

Keyboard shortcuts

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