browser

package
v2.7.8 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 30 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 browser drives a headless Chromium process over the Chrome DevTools Protocol (CDP) while forcing every subresource TCP socket through an in-process SSRF-guarded loopback CONNECT proxy.

OS Process Sandbox & Container Fallback

Chromium's native OS process sandbox (AppContainer/Restricted Token on Windows, Seatbelt on macOS, and user/PID/network namespaces + seccomp-bpf on Linux) is enabled by default. On Linux, Renderer.ProbeStartup and `ensureBrowser` probe native sandbox support first and automatically fall back to container-isolated flags when container MAC profiles (such as AppArmor `edgefetch`), `NO_NEW_PRIVS`, or restricted user namespaces block unprivileged namespace creation — unless `EDGEFETCH_REQUIRE_BROWSER_SANDBOX=1` is set, in which case browser rendering fails closed (`Available() == false`). Active browser version and sandbox state (`"on"`, `"off"`, or `"unknown"`) are reported via Renderer.BrowserInfo.

SSRF Isolation Model

Untrusted JavaScript executing inside a headless browser can attempt `fetch("http://192.168.1.1/")`, cloud-metadata probes (`169.254.169.254`), or DNS-rebinding subresource loads. EdgeFetch launches Chromium with `--proxy-server=http://127.0.0.1:<port>`, `--proxy-bypass-list=<-loopback>`, and `--host-resolver-rules="MAP * ~NOTFOUND , EXCLUDE 127.0.0.1"`, disabling Chromium's internal DNS resolver so every socket traverses SSRFProxy:

  1. Plain-HTTP proxy requests (`GET http://...`) are rejected with `403 Forbidden`; only `CONNECT host:443` tunnels are permitted.
  2. Target authorities are validated against the caller's URL allowlist (blocking recursive coordination-hub fetches, non-443 ports, and IP literals).
  3. Outbound TCP dials attach `politeness.RejectNonPublicPeer` (`net.Dialer.Control`) so DNS-rebinding targets resolving to RFC 1918, loopback, link-local, CGNAT, NAT64, or IPv6 transition prefixes abort before SYN.
  4. Rendered DOMs are checked via `extract.DetectRenderedChallenge`; anti-bot/CAPTCHA challenges halt immediately with ErrChallengeDetected and are never clicked through or waited out.

Index

Constants

This section is empty.

Variables

View Source
var ErrBrowserUnavailable = errors.New("headless Chromium is not available on this node (connect a browser-capable worker node)")

ErrBrowserUnavailable indicates no headless Chromium binary is available in the current runtime (e.g. distroless Lite).

View Source
var ErrChallengeDetected = errors.New("anti-bot challenge detected in rendered DOM")

ErrChallengeDetected is returned when a rendered DOM contains a CAPTCHA or anti-bot challenge; EdgeFetch halts immediately and never attempts to solve, click through, or wait out challenges.

Functions

func FindChromeBinary

func FindChromeBinary() string

FindChromeBinary locates an installed headless Chromium/Chrome/Edge/Brave executable across Linux, macOS, and Windows, enabling a ~8 MB desktop binary download to render JavaScript (`browser-v1` + `interact-v1`) using pre-installed OS browsers.

Types

type ActionJSReturn added in v2.5.0

type ActionJSReturn struct {
	Type  string `json:"type"`
	Value any    `json:"value"`
}

ActionJSReturn records the return value of an `{ "type": "executeJavascript" }` action.

type ActionResult added in v2.7.1

type ActionResult struct {
	Index      int    `json:"index"`
	Type       string `json:"type"`
	Status     string `json:"status"` // "ok" or "no_effect"
	URLChanged bool   `json:"urlChanged"`
	DOMChanged bool   `json:"domChanged"`
	FinalURL   string `json:"finalUrl,omitempty"`
	Warning    string `json:"warning,omitempty"`
}

ActionResult records per-step outcome diagnostics for browser `interact` actions.

type ActionScrapeSnapshot added in v2.5.0

type ActionScrapeSnapshot struct {
	URL  string `json:"url"`
	HTML string `json:"html"`
}

ActionScrapeSnapshot records a mid-sequence DOM snapshot captured by a `{ "type": "scrape" }` action.

type CapturedJSONResponse added in v2.7.8

type CapturedJSONResponse struct {
	URL    string `json:"url"`
	Method string `json:"method,omitempty"`
	Status int    `json:"status"`
	Body   string `json:"body"`
}

CapturedJSONResponse holds a bounded, same-origin HTTP 200 application/json XHR/Fetch payload observed on the untainted top-level frame during headless browser rendering.

type InteractAction

type InteractAction struct {
	Type         string `json:"type"`                   // "click", "fill", "type", "write", "press", "wait", "scroll", "select", "navigate", "screenshot", "scrape", "executeJavascript", "pdf"
	Selector     string `json:"selector,omitempty"`     // CSS selector for click/fill/type/select/scroll/wait
	All          bool   `json:"all,omitempty"`          // Click every element matching Selector when true
	Value        string `json:"value,omitempty"`        // Input value for fill/type/select/write
	Text         string `json:"text,omitempty"`         // Alias for Value on write/type
	Key          string `json:"key,omitempty"`          // Key name for press (e.g. "Enter", "Tab", "Escape")
	Direction    string `json:"direction,omitempty"`    // "down" (default) or "up" for scroll
	Script       string `json:"script,omitempty"`       // JS snippet for executeJavascript
	FullPage     bool   `json:"fullPage,omitempty"`     // Full-page capture for screenshot action
	URL          string `json:"url,omitempty"`          // HTTPS target for navigate
	WaitMs       int    `json:"waitMs,omitempty"`       // Milliseconds to pause after or during "wait"
	Milliseconds int    `json:"milliseconds,omitempty"` // Firecrawl alias for WaitMs
}

InteractAction describes a single deterministic browser interaction step (`firecrawl_interact` & `/scrape` inline `actions` parity).

type Output

type Output struct {
	Status            int
	Headers           http.Header
	FinalURL          string
	HTML              string
	ScreenshotBase64  string
	ActionScreenshots []string
	ActionScrapes     []ActionScrapeSnapshot
	JavascriptReturns []ActionJSReturn
	ActionResults     []ActionResult
	CapturedJSON      []CapturedJSONResponse
	PDFBase64         string
	SessionID         string
}

Output holds the rendered DOM, HTTP metadata, screenshot, action outputs, and optional session handle.

type Renderer

type Renderer struct {
	CheckRobots func(ctx context.Context, rawURL string) error
	// contains filtered or unexported fields
}

Renderer manages a shared headless Chromium process + SSRF-safe loopback CONNECT proxy.

func NewMockRenderer

func NewMockRenderer(wsURL string, allow func(*url.URL) error, userAgent string) *Renderer

NewMockRenderer creates a Renderer backed by an in-memory/loopback CDP WebSocket URL for deterministic unit tests.

func NewRenderer

func NewRenderer(chromeBin string, allow func(*url.URL) error, userAgent string, maxConcurrent int, log *slog.Logger) *Renderer

NewRenderer constructs a Renderer bounded to `maxConcurrent` simultaneous tabs (default 2).

func (*Renderer) Available

func (r *Renderer) Available() bool

Available reports whether a headless browser binary (or test override) is available and permitted by sandbox policy.

func (*Renderer) BrowserInfo added in v2.6.0

func (r *Renderer) BrowserInfo() (version string, sandbox string)

BrowserInfo returns the detected Chromium product version and OS process sandbox state ("on", "off", or "unknown").

func (*Renderer) Close

func (r *Renderer) Close() error

Close terminates any active Chromium subprocess, loopback SSRF proxy, and temporary profile directory.

func (*Renderer) CloseSession

func (r *Renderer) CloseSession(ctx context.Context, sessionID string) bool

CloseSession terminates a retained `interact` browser session immediately (`interact_stop`).

func (*Renderer) Execute

func (r *Renderer) Execute(ctx context.Context, task Task) (out Output, retErr error)

Execute runs a stateless page render or stateful multi-step `interact` turn inside an isolated incognito context.

func (*Renderer) ProbeStartup added in v2.6.0

func (r *Renderer) ProbeStartup(ctx context.Context)

ProbeStartup pre-populates r.browserVersion via `<chromeBin> --version` and probes OS sandbox support on Linux. When EDGEFETCH_REQUIRE_BROWSER_SANDBOX is set and the OS sandbox is "off", Available() becomes false.

func (*Renderer) SetAllowNoSandbox added in v2.7.4

func (r *Renderer) SetAllowNoSandbox(allow bool)

SetAllowNoSandbox configures whether Chromium may fall back to `--no-sandbox` when the host OS or Home Assistant OS AppArmor/seccomp profile blocks unprivileged user namespaces (`CLONE_NEWUSER`). Ignored when EDGEFETCH_REQUIRE_BROWSER_SANDBOX is set.

func (*Renderer) SetOtelExporter added in v2.6.3

func (r *Renderer) SetOtelExporter(exp *otel.Exporter)

SetOtelExporter attaches an optional non-blocking OpenTelemetry OTLP/HTTP span exporter.

type SSRFProxy

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

SSRFProxy is a loopback-only HTTP CONNECT tunnel (`127.0.0.1:0`) paired with Chromium's `--proxy-server` + `--host-resolver-rules="MAP * ~NOTFOUND , EXCLUDE 127.0.0.1"` flags.

Why this matters on Home Assistant OS: Untrusted JavaScript executing inside a headless browser can call `fetch("http://192.168.1.1/...")`, open WebSockets, or trigger DNS-rebinding subresources. By disabling Chromium's own DNS resolver (`MAP * ~NOTFOUND`) and forcing all connections through `SSRFProxy`, every subresource TCP dial passes through both `allow(*url.URL)` and `politeness.RejectNonPublicPeer` BEFORE the TCP SYN leaves the kernel.

func NewSSRFProxy

func NewSSRFProxy(allow func(*url.URL) error, customDial func(ctx context.Context, network, addr string) (net.Conn, error)) (*SSRFProxy, error)

NewSSRFProxy starts a loopback CONNECT proxy enforcing `allow` and `politeness.RejectNonPublicPeer` on every tunnel.

func (*SSRFProxy) Addr

func (p *SSRFProxy) Addr() string

Addr returns `127.0.0.1:<port>` suitable for `--proxy-server=http://<Addr()>`.

func (*SSRFProxy) Close

func (p *SSRFProxy) Close() error

Close shuts down the loopback proxy listener.

type Task

type Task struct {
	URL                string
	UserAgent          string
	AcceptLanguage     string
	Headers            map[string]string
	Mobile             bool
	ViewportWidth      int
	ViewportHeight     int
	WaitForMs          int
	WaitSelector       string
	Screenshot         bool
	ScreenshotFullPage bool
	ScreenshotQuality  int
	Actions            []InteractAction
	SessionID          string // Optional existing session to resume
	KeepSession        bool   // Retain tab open for follow-up `interact` calls
	CloseSession       bool   // Close `SessionID` immediately after or without running actions
}

Task describes a browser render or interaction request.

Jump to

Keyboard shortcuts

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