preview

package
v0.16.397 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: AGPL-3.0 Imports: 41 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 preview is the reverse proxy behind the right pane's browser: a slot origin of the gateway shows a local dev server port (with its neighbour ports) or an external site, named by a claim the gateway signs with the pair's secret. It rewrites what a dev server needs rewritten to work inside the slot origin, injects the page's bridge, passes WebSockets (HMR) through, refuses private addresses, and records what the page did for its DevTools.

Index

Constants

View Source
const (
	DefaultMaxTotalBytes = 200 * 1024 * 1024
	DefaultMaxFileBytes  = 20 * 1024 * 1024
)
View Source
const (
	BridgePath         = "/__tk/bridge.js"
	DevtoolsConfigPath = "/__tk/devtools/config"
	DevtoolsReportPath = "/__tk/devtools/report"
)

The slot's own paths, answered by the runtime before any routing to a dev server: the bridge script, and the DevTools paths the page's bridge reads its conditions from and reports what it saw to.

View Source
const (
	OriginOK        = "ok"        // the name resolves to an address of this machine
	OriginNotFound  = "not-found" // NXDOMAIN or no address at all
	OriginElsewhere = "elsewhere" // resolves, but to no address of this machine
	OriginError     = "error"     // the resolver failed (timeout, refused)
	OriginLiteral   = "literal"   // an IP address or localhost: there is no name to resolve
)

Origin check states.

View Source
const BodyLimit = 1 << 20

BodyLimit is the previous runtime's default request body limit.

View Source
const PreviewIDFile = "preview-id"

PreviewIDFile is where a runtime keeps the id it made for its slots' names.

Variables

This section is empty.

Functions

func CookieTag

func CookieTag(t devtools.Target, secret []byte) string

CookieTag names a target in its cookies on the slot host, so targets taking turns in a slot never share cookies. Keyed with the secret: a page cannot compute another target's tag.

func DomainOrigins

func DomainOrigins(domain, id string, n int) []string

DomainOrigins are the n slots' origins under domain for id: https://s1-<id>.<domain> … https://s<n>-<id>.<domain>.

func IsForbiddenAddress

func IsForbiddenAddress(address string, local map[string]bool) bool

IsForbiddenAddress: internal, special or this machine's own; not an address at all is refused too.

func NormalizeDomain

func NormalizeDomain(raw string) (string, error)

NormalizeDomain is RUNTIME_PREVIEW_DOMAIN as a lowercase name without a scheme, a leading "*." or a trailing dot; an error says why it is not a domain.

func NormalizeIPv4

func NormalizeIPv4(host string) string

NormalizeIPv4 is inet_aton: 2130706433, 0177.0.0.1, 0x7f.1 are all 127.0.0.1, as the URL parser and getaddrinfo read them; "" for anything else.

func OriginsHint

func OriginsHint(checks []OriginCheck) string

OriginsHint is what to do about the worst of the checks, "" when every name leads here.

func ParseTarget

func ParseTarget(v any) (devtools.Target, bool)

ParseTarget is a preview target as a request body names it: {kind:"port",port} or {kind:"url",origin} with the origin spelled exactly as the URL parser prints it.

func PreviewID

func PreviewID(named, machine, dataDir string) (string, error)

PreviewID is the id of this runtime's slot names: named is RUNTIME_PREVIEW_ID, machine the hub's machine id ("" when there is none). Without either the id is read from dataDir/preview-id, made and written there on the first start.

func PrivateHosts added in v0.16.123

func PrivateHosts(list []string) map[string]bool

PrivateHosts reads the deployment's list of hosts that may resolve into a private network: names only, written lower-case without a trailing dot; an address or localhost in the list is ignored.

func RewriteHTMLDocumentPaths

func RewriteHTMLDocumentPaths(doc []byte, prefix, docPath string) []byte

RewriteHTMLDocumentPaths is RewriteHTMLRootPaths for a page the browser opens at docPath (the path without the prefix): its relative addresses get the prefix too. A page with a <base href> of its own resolves them against that base, which gets the prefix here instead; the rest is then the browser's.

func RewriteHTMLRootPaths added in v0.16.154

func RewriteHTMLRootPaths(doc []byte, prefix string) []byte

RewriteHTMLRootPaths gives a document's root-absolute addresses the prefix, inline scripts' imports included.

func SelfAddresses

func SelfAddresses(named string) map[string]bool

SelfAddresses are the machine's own: its interfaces and the public ones named for it (behind NAT the public address is on no interface).

func SystemLookup

func SystemLookup(ctx context.Context, host string) ([]string, error)

SystemLookup is the system resolver.

func ValidID

func ValidID(id string) bool

ValidID says whether an id fits in the slots' names: lowercase letters, digits and inner dashes, 42 at most.

func WritePage

func WritePage(w http.ResponseWriter, status int, text string)

WritePage answers with one of the runtime's own status pages: a slot listener's refusals look like the proxy's.

Types

type AssetCache

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

AssetCache is one directory of kept answers, oldest use first.

func NewAssetCache

func NewAssetCache(dir string, maxTotal, maxFile int64) *AssetCache

func (*AssetCache) Lookup

func (c *AssetCache) Lookup(key string) (int, Headers, *os.File, bool)

Lookup is a kept answer: its status, headers (its length added) and body; false when there is none.

func (*AssetCache) Tee

func (c *AssetCache) Tee(key string, status int, h Headers, ttl float64, body io.Reader) io.Reader

Tee wraps an upstream body: the same bytes come out, and a copy goes to disk when it ends whole and within the caps.

type BodyError

type BodyError struct {
	Status int
	Text   string
}

BodyError is the dispatcher's plain-text refusal of a body: 413 too large, 400 not JSON.

func ParseBody

func ParseBody(r *http.Request) (any, *BodyError)

ParseBody reads a request body as the previous runtime's dispatcher did, before any handler ran: JSON (an empty body is {}), a form as an object, anything else as text. Objects keep JavaScript's key order.

type Claim

type Claim struct {
	Sub        string
	Target     devtools.Target
	SlotOrigin string
	PortSlots  map[string]string
	// ParentOrigin is the platform's page origin the in-page bridge talks to; "" when the gateway sent none, and then
	// there is no bridge.
	ParentOrigin string
	// Carried: the gateway took the slot's session from the address, not a cookie (an app's view frame sends none). Such
	// a session is a bearer link, so the proxy opens only the apps' view server with it (Config.CarriedPort).
	Carried bool
	// PathPrefix is the slot's path on the page's own origin when the slot goes by path (<appBase>/__pv/<n>, a
	// standalone runtime's preview without origins of its own); "" for a slot origin of its own. SlotOrigin ends with it.
	PathPrefix string
}

Claim is what the gateway says a request may reach.

func VerifyClaim

func VerifyClaim(token string, secret []byte, audience string, now time.Time) *Claim

VerifyClaim checks an HS256 claim token of the fleet gateway with the audience; nil when it does not hold.

type Config

type Config struct {
	// Path is the proxy's own path; the rest of a request's path is the upstream's.
	Path string
	// ClaimHeader carries the gateway's claim; Audience is the claim's.
	ClaimHeader string
	Audience    string
	Secret      []byte
	// PrivateHeaderPrefix marks the headers only the gateway sets; none of them reaches an upstream.
	PrivateHeaderPrefix string
	// Forbidden are the ports never opened: the runtime's own and the platform's.
	Forbidden func() map[int]bool
	Stands    Stands
	// SelfIPs are the machine's public addresses no interface carries (behind NAT), comma-separated.
	SelfIPs string
	// PrivateHosts may resolve into a private network (GitLab behind an overlay network): the deployment names them.
	PrivateHosts []string
	Store        *devtools.Store
	// Cache keeps stand assets; nil keeps none.
	Cache *AssetCache
	// Bridge is the page bridge's script; with none the request goes to Fallback (the previous runtime, which has it).
	Bridge   func() ([]byte, bool)
	Fallback http.HandlerFunc
	// LocalOrigins: the claims come from this runtime's own slot listeners (a standalone runtime), whose slot and page
	// origins may be plain http and carry a port, like http://localhost:8023. The fleet gateway's are always https.
	LocalOrigins bool
	// CarriedPort is the only port a session carried in the address may open (the apps' view server); 0 or nil: none.
	CarriedPort func() int

	// Tests: where names point, the address of a port, the CA of an https target, shorter timeouts.
	Resolve      func(host string) Resolved
	UpstreamHost string
	RootCAs      *x509.CertPool
	Timeouts     Timeouts
	// Dial connects to a checked address; tests point a stand's port 443 at their own server.
	Dial func(ctx context.Context, address string) (net.Conn, error)
}

Config is what the deployment and the gate give the proxy.

type ContextLookup

type ContextLookup func(ctx context.Context, host string) ([]string, error)

ContextLookup resolves a name to its addresses.

type Headers

type Headers map[string][]string

Headers are a message's headers the way the previous runtime's HTTP library held them: lower-case names, Set-Cookie as a list, a repeated Cookie joined with "; ", other repeats joined with ", " except those of which only the first counts.

func HeadersOf

func HeadersOf(h http.Header) Headers

HeadersOf reads Go's header map.

func (Headers) Clone

func (h Headers) Clone() Headers

func (Headers) Del

func (h Headers) Del(name string)

func (Headers) Get

func (h Headers) Get(name string) string

Get is a header's value, "" when absent; Set-Cookie's lines joined.

func (Headers) Has

func (h Headers) Has(name string) bool

func (Headers) Set

func (h Headers) Set(name, value string)

type Lookup

type Lookup func(host string) ([]string, error)

Lookup is the system resolver's answers for a name.

type OriginCheck

type OriginCheck struct {
	Origin    string   `json:"origin"`
	Host      string   `json:"host"`
	State     string   `json:"state"`
	Addresses []string `json:"addresses,omitempty"`
	Error     string   `json:"error,omitempty"`
}

OriginCheck is what DNS says of one slot origin.

func CheckOrigins

func CheckOrigins(ctx context.Context, origins []string, lookup ContextLookup, self map[string]bool) []OriginCheck

CheckOrigins resolves the host of every origin and says whether it leads to this machine (self: its addresses, SelfAddresses). A name of another machine is not wrong in itself: a reverse proxy or a balancer may stand there.

type Proxy

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

Proxy is the preview's reverse proxy.

func New

func New(cfg Config) *Proxy

func (*Proxy) AnswerDevtools

func (p *Proxy) AnswerDevtools(w http.ResponseWriter, r *http.Request, path, slot string, target devtools.Target)

AnswerDevtools answers a slot's own DevTools paths for its current target.

func (*Proxy) Matches

func (p *Proxy) Matches(r *http.Request) bool

Matches: the request is for the proxy. The path is matched as sent, before anything is taken off it.

func (*Proxy) ServeHTTP

func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Resolved

type Resolved struct {
	Address string
	Family  int
	Error   string
}

Resolved is where a name points, or why it is refused: "forbidden" or "not-found".

func LiteralAddress

func LiteralAddress(host string) Resolved

LiteralAddress is the address a host names by itself (an IPv6 literal, an IPv4 in any spelling); Family 0 for a name.

func ResolveListed added in v0.16.123

func ResolveListed(host string, lookup Lookup, local map[string]bool) Resolved

ResolveListed resolves a host the deployment named (RUNTIME_PREVIEW_PRIVATE_HOSTS, GitLab behind an overlay network, say): it may point into a private network, never into the machine itself or a special range.

func ResolvePublic

func ResolvePublic(host string, lookup Lookup, local map[string]bool) Resolved

ResolvePublic resolves a host once and refuses it when any of its addresses is not public.

type Stands

type Stands struct {
	// Domain is the stands' domain with its leading dot; "" makes no host a stand.
	Domain string
	// SignInHosts are where a stand sends a person without a session.
	SignInHosts []string
	// SessionHeader carries the person's stand session from the gateway.
	SessionHeader string
}

Stands are the deployment's feature stands (https://<label><domain>): the one kind of external site that gets the person's own sign-in with the request, passed by the gateway in its own header.

func (Stands) IsHost

func (s Stands) IsHost(host string) bool

func (Stands) IsOrigin

func (s Stands) IsOrigin(origin string) bool

IsOrigin: https://<stand> exactly as the URL parser prints an origin.

type Timeouts

type Timeouts struct {
	Connect, Headers, Idle time.Duration
}

Timeouts of a url target: connect, until the headers, and a body that stops flowing. A WebSocket, once upgraded, has none.

Directories

Path Synopsis
Package devtools is the DevTools record of the preview slots: what a slot's page did on the network and in its console, and the conditions it runs under (throttling, blocked addresses, cache).
Package devtools is the DevTools record of the preview slots: what a slot's page did on the network and in its console, and the conditions it runs under (throttling, blocked addresses, cache).
Package ports lists the dev servers a preview can open (the listeners of this machine grouped by the conversation's work folders and the agents' worktrees) and maps a component picked in a preview to its source files.
Package ports lists the dev servers a preview can open (the listeners of this machine grouped by the conversation's work folders and the agents' worktrees) and maps a component picked in a preview to its source files.
Package weburl parses URLs the way browsers and Node's URL class do (the WHATWG URL standard) for the http(s) and ws(s) schemes the preview deals with: lowercase scheme and host, default port dropped, dot segments resolved, the same characters percent-encoded.
Package weburl parses URLs the way browsers and Node's URL class do (the WHATWG URL standard) for the http(s) and ws(s) schemes the preview deals with: lowercase scheme and host, default port dropped, dot segments resolved, the same characters percent-encoded.

Jump to

Keyboard shortcuts

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