Documentation
¶
Overview ¶
Package client provides low-level HTTP client abstractions: capability negotiation, URL proxying helpers (JSProxy, FetchProxy), and network property extraction. Most callers should use safehttp.NewClient instead.
fetchproxy.go is the unified fleet-internal "fetch a URL" helper. It supersedes the per-service habit of hand-rolling net/http.Get for HTML scraping: instead of every service reimplementing redirect handling, encoding sniffing, SSRF guard, Set-Cookie collection and UA rotation, callers do:
res, err := client.Fetch(ctx, url)
and get back a normalised FetchResult regardless of which backend actually served the request. The helper picks a backend in this order:
js-proxy (when WithJSRender(true) is set — full Chromium render, returns rendered DOM + network[] + cookies_set[]). Requires JS_PROXY_URL + JS_PROXY_API_KEY. Fails hard on error; we never silently downgrade to plain HTML when the caller asked for a rendered DOM.
html-proxy (only when HTML_PROXY_URL is explicitly set — a dedicated proxy service that handles redirect/encoding/CF normalisation upstream of this caller. Currently no fleet service ships this role; the slot is reserved for when one does. Falls back to direct on error.)
direct (the DEFAULT path — uses safehttp.NewClient for SSRF protection plus a CheckRedirect callback that captures each hop's headers + Set-Cookie trail. The "centralisation" lives in this library function, not in a separate service: services that call Fetch all share the same SSRF guard, redirect handler, cookie collector, and UA. JS rendering is unavailable on this path; opt in with WithJSRender if you need it.)
FetchResult.Backend says which path won. FetchResult.Degraded is true whenever the helper fell back from the requested backend; the degradation reason is in DegradedReason. Callers can surface this via depcheck or just log it; the data is always present.
Environment variables (all optional):
HTML_PROXY_URL if set, route through this URL before direct HTML_PROXY_API_KEY key for the html-proxy backend JS_PROXY_URL default https://go-js-proxy-network.0exec.com JS_PROXY_API_KEY required when WithJSRender(true) FLEET_API_KEY single fleet-wide key, used when *_API_KEY unset FETCHPROXY_ALLOW_DIRECT "false" disables the direct-fetch fallback
No keys are baked in: go-common is public and must stay clean. Services receive scoped credentials through the approved secret path; missing keys must be fixed at provisioning rather than replaced with a shared fallback.
Package client - jsproxy.go provides clients for the fleet's two JS-rendering proxies. They are SEPARATE services with separate payloads — pick the one that matches your need:
go-js-proxy https://go-js-proxy.0exec.com
Rendered DOM only. Cheaper. Use when all you
need is the post-mount HTML.
Function: JSProxyDOM(ctx, target)
go-js-proxy-network https://go-js-proxy-network.0exec.com
Rendered DOM PLUS the full network log
(every request, response headers, sizes,
timings) PLUS console output PLUS the
Performance API snapshot. More expensive,
rate-limited harder. Use when downstream
logic needs to walk request/response
telemetry (XHR endpoints, loaded scripts,
Set-Cookie chain, etc.).
Function: JSProxy(ctx, target)
`client.Fetch(ctx, target, ...)` picks the right backend automatically based on whether the caller asked for the network log: WithJSRender(true) alone routes to the DOM-only proxy; WithNetworkLog(true) routes to the network-aware proxy.
Environment:
JS_PROXY_NETWORK_URL Network-aware proxy base URL. Default:
https://go-js-proxy-network.0exec.com
JS_PROXY_NETWORK_API_KEY API key for the network-aware proxy.
JS_PROXY_DOM_URL DOM-only proxy base URL. Default:
https://go-js-proxy.0exec.com
JS_PROXY_DOM_API_KEY API key for the DOM-only proxy.
JS_PROXY_URL Backward-compat alias for
JS_PROXY_NETWORK_URL.
JS_PROXY_API_KEY Backward-compat fallback used by either
proxy if its specific *_API_KEY env var
is unset. Existed before the split; do
not rely on it in new code.
The two proxies use SEPARATE keys — one key does not authenticate against the other. Set `JS_PROXY_DOM_API_KEY` and `JS_PROXY_NETWORK_API_KEY` independently. The `JS_PROXY_API_KEY` fallback only exists so deployments wired before the split don't break; once both specific keys are set it's ignored.
The helper is intentionally dependency-free: it uses net/http directly so it can be vendored in services with strict build constraints.
Package client - netextract.go consumes the rich telemetry that JSProxy / Fetch(WithNetworkLog(true)) attach to FetchResult.Network and turns it into the small set of primitives that pentest / recon services actually want:
XHREndpoints — every API call the SPA made (xhr+fetch+ws),
deduped by method+path-template. The
"attack-surface map" output that idor-finder,
graphql-introspection, cors-scanner, and
api-extractor all want to consume.
GraphQLEndpoints — XHR/fetch POSTs whose payload looks like a
GraphQL operation. Cheap structural sniff;
downstream services run real introspection.
JSAssets — every loaded script (.js, modulepreload, eval
blobs). secrets-scanner and apikey-scanner
iterate this list to fetch+entropy-scan each.
SourcemapCandidates — JSAssets whose response advertises a
SourceMap header or a /*# sourceMappingURL=*/
marker via initiator chain. sourcemap-finder.
IframeURLs — child documents loaded into <iframe>. Frame
embeddability analysis (clickjacking,
iframe-analyzer).
RedirectParams — query-string keys observed across the network
that look like redirect targets (?next=,
?return_to=, ?redirect_uri=, ...). Seed for
open-redirect fuzzing.
SetCookiesAll — every Set-Cookie observed across all hops
(not just the final document). Auth/session
analysis (session-management, cookie-checker).
ConsoleErrors — console log lines that look like errors or
framework dev-mode warnings. debug-detector.
By — generic filters: ByResourceType, ByHostSuffix,
ByMethod, ByStatusClass, BySizeGreaterThan,
ByContentType. Compose freely.
The helpers never panic on nil input — passing a zero FetchResult returns empty slices, so callers can wire them in unconditionally.
All extractors are pure functions of the rich-telemetry payload. They do NOT make new network calls — that's the consumer service's job. This keeps the helpers cheap, deterministic, and trivially testable.
Index ¶
- Constants
- Variables
- func ConsoleErrors(r *FetchResult) []string
- func IframeURLs(r *FetchResult) []string
- func ModeFromQuery(r *http.Request) string
- func ProbeHTMLProxy(ctx context.Context) error
- func ProbeJSProxy(ctx context.Context) error
- func ProbeJSProxyDOM(ctx context.Context) error
- type Capability
- type Clientdeprecated
- func New() *Clientdeprecated
- type FetchCookie
- type FetchHop
- type FetchOption
- type FetchResult
- type NetworkEntry
- func ByContentType(entries []NetworkEntry, prefixes ...string) []NetworkEntry
- func ByHostSuffix(entries []NetworkEntry, suffixes ...string) []NetworkEntry
- func ByMethod(entries []NetworkEntry, methods ...string) []NetworkEntry
- func ByResourceType(entries []NetworkEntry, types ...string) []NetworkEntry
- func BySizeGreaterThan(entries []NetworkEntry, n int64) []NetworkEntry
- func ByStatusClass(entries []NetworkEntry, classes ...int) []NetworkEntry
- func JSAssets(r *FetchResult) []NetworkEntry
- func SourcemapCandidates(r *FetchResult) []NetworkEntry
- type Performance
- type ProxyResult
- type RedirectParam
- type XHREndpoint
Constants ¶
const ( DefaultFetchTimeout = 25 * time.Second DefaultBodyCap = 32 << 20 // 32 MiB per response )
Defaults & env-key names — exported for test/override use.
const ( DefaultJSProxyNetworkURL = "https://go-js-proxy-network.0exec.com" DefaultJSProxyDOMURL = "https://go-js-proxy.0exec.com" DefaultJSProxyTimeMS = 20000 // 20s — give the server up to its own 15s hard timeout // Deprecated: use DefaultJSProxyNetworkURL. DefaultJSProxyURL = DefaultJSProxyNetworkURL // Deprecated: use DefaultJSProxyDOMURL. LegacyJSProxyURL = DefaultJSProxyDOMURL )
Defaults — kept exported so callers can override per-call.
Variables ¶
var FetchCapabilities = []Capability{ { Name: "use_js", Description: "Render the page with JavaScript executed. Returns post-mount DOM via go-js-proxy.", Type: "bool", Values: []string{"true", "1", "yes", "on"}, Default: "false", Cost: "rendered_dom", }, { Name: "use_network", Description: "Return the full network log (requests, response headers, sizes, timings) plus console plus performance, via go-js-proxy-network. Implies use_js.", Type: "bool", Values: []string{"true", "1", "yes", "on"}, Default: "false", Cost: "rendered_network", Implies: []string{"use_js"}, }, }
FetchCapabilities is the set of standard query flags this package understands. Services that use Fetch + OptionsFromQuery should surface this on their /capabilities endpoint so the catalog and hub can auto-discover which flags work without trying each one.
Keep this in sync with OptionsFromQuery above — adding a flag means adding both the parsing AND the capability entry.
Functions ¶
func ConsoleErrors ¶
func ConsoleErrors(r *FetchResult) []string
ConsoleErrors filters ConsoleLogs to lines that look like errors or dev-mode warnings. Cheap substring sniff — debug-detector applies stricter classification.
func IframeURLs ¶
func IframeURLs(r *FetchResult) []string
IframeURLs returns the URLs of every child document the page loaded into an iframe (CDP resource_type "document" with an initiator that isn't the top-level navigation).
func ModeFromQuery ¶
ModeFromQuery describes how Fetch will route, given the flags on r. Useful for echoing the mode back in the service's response shape so the caller can tell at a glance which path produced the data.
Returns one of: "static", "rendered_dom", "rendered_network".
func ProbeHTMLProxy ¶
ProbeHTMLProxy is a depcheck-friendly probe for the html-proxy backend. Returns nil immediately if HTML_PROXY_URL is unset (no backend to probe — services running on the direct path don't need a probe). Otherwise hits its /health endpoint with a 2s budget; returns nil if 200 OK.
func ProbeJSProxy ¶
ProbeJSProxy is a depcheck-friendly probe for the network-aware js-proxy backend (go-js-proxy-network). Use this when your service depends on the network log being available.
func ProbeJSProxyDOM ¶
ProbeJSProxyDOM is a depcheck-friendly probe for the DOM-only js-proxy backend (go-js-proxy). Use this when your service only renders pages and never walks the network array — the cheaper proxy will still serve you and that's the dep you should declare.
Types ¶
type Capability ¶
type Capability struct {
Name string `json:"name"`
Description string `json:"description"`
Type string `json:"type"` // "bool" | "string" | "int"
Values []string `json:"values,omitempty"` // allowed values (bool true forms, enum values)
Default string `json:"default,omitempty"` // textual default
Cost string `json:"cost,omitempty"` // "static"|"rendered_dom"|"rendered_network" or service-specific
Implies []string `json:"implies,omitempty"` // other flags this one turns on
}
Capability describes one query-string flag a service accepts. Serialised on /capabilities so external tools (catalog, hub) can learn the surface area without trying random parameter names.
The shape is intentionally small — adding fields breaks every downstream consumer, so keep new metadata in Description for now.
type Client
deprecated
Client wraps http.Client to inject headers from context
Deprecated: use safehttp.NewClient for calls to the public internet, or meshclient for calls to a sibling fleet service; both propagate the W3C trace context by default. Client only copies the X-Request-ID header from the request context (see middleware.GetRequestID); a caller that needs that can set header.RequestID itself. The rest of this package (Fetch, JSProxy, Capability, the network-extraction helpers) is not deprecated and has no replacement. Removal no earlier than v0.104.0.
func (*Client) Post
deprecated
func (c *Client) Post(ctx context.Context, url string, contentType string, body interface{}) (*http.Response, error)
Post helper
Deprecated: Post never sends its body argument (the request goes out with an empty body), so it cannot be used for a real POST. Build the request with http.NewRequestWithContext and send it with safehttp.NewClient (public internet) or meshclient (sibling fleet services). Removal no earlier than v0.104.0.
type FetchCookie ¶
type FetchCookie struct {
Raw string `json:"raw"`
Name string `json:"name"`
Value string `json:"value"`
Domain string `json:"domain,omitempty"`
SetOn string `json:"set_on"` // URL that set it
}
FetchCookie is one cookie observed during the fetch, with the URL that issued it and the raw Set-Cookie header for downstream parsing.
func SetCookiesAll ¶
func SetCookiesAll(r *FetchResult) []FetchCookie
SetCookiesAll returns every Set-Cookie header observed across every hop of the network — not just the final document. Auth flows that rotate tokens on /login or /oauth/callback are invisible to a "what's the cookie on the landing page" check; this surfaces them.
Each entry is the raw header line plus the URL that issued it. We keep it as []FetchCookie for symmetry with FetchResult.CookiesSet, using only the Raw + SetOn fields — full attribute parsing belongs in cookie-checker.
type FetchHop ¶
type FetchHop struct {
URL string `json:"url"`
Status int `json:"status"`
Headers map[string]string `json:"headers"`
SetCookie []string `json:"set_cookie,omitempty"`
}
FetchHop is one entry in the redirect chain. SetCookie is the raw Set-Cookie header values from THIS hop (one slice element per Set-Cookie header on the response); join across hops to get the full cookie trail.
type FetchOption ¶
type FetchOption func(*fetchConfig)
FetchOption configures a single Fetch call. Options are additive; later options override earlier ones if they touch the same field.
func OptionsFromQuery ¶
func OptionsFromQuery(r *http.Request) []FetchOption
OptionsFromQuery returns the FetchOption set implied by the standard fleet query flags on r. Unrecognised flags are ignored — services may parse their own flags from the same URL without conflicting with this helper.
Returns an empty slice (NOT nil) if no flags are set, so callers can pass the result directly to Fetch without nil-checking.
func WithAllowDirect ¶
func WithAllowDirect(b bool) FetchOption
WithAllowDirect explicitly opts in or out of the direct safehttp fallback when both proxies are unreachable. Overrides FETCHPROXY_ALLOW_DIRECT env var. Default (env unset, option unused): fallback is enabled — services degrade rather than fail hard.
func WithFetchTimeout ¶
func WithFetchTimeout(d time.Duration) FetchOption
WithFetchTimeout caps total request budget (default 25s).
func WithFetchUserAgent ¶
func WithFetchUserAgent(s string) FetchOption
WithFetchUserAgent overrides the User-Agent forwarded by the proxy (default: whatever the proxy backend supplies).
func WithJSRender ¶
func WithJSRender(b bool) FetchOption
WithJSRender, when true, routes the request to the js-proxy so the returned Body is the post-mount DOM (cost: 1-3s extra latency, full Chromium render). Default false — plain HTML fetch is much cheaper.
func WithNetworkLog ¶
func WithNetworkLog(b bool) FetchOption
WithNetworkLog, when true, asks the helper to attach the full rendered-page telemetry to the returned FetchResult: Network, ConsoleLogs, Performance, and the rich CookiesSet observed by the browser. Implies WithJSRender(true) — there is no source of this data on the direct or html-proxy paths.
Use this when downstream logic needs to walk the request tree (XHR/fetch endpoints, dynamically-loaded JS bundles, redirect params observed in real navigation, console errors, etc.). The payload is already in memory after a JS render; opt-in is purely to make the cost/intent explicit at the call site.
type FetchResult ¶
type FetchResult struct {
URL string `json:"url"` // original request
FinalURL string `json:"final_url"` // after redirects
Status int `json:"status"` // final response status
Headers map[string]string `json:"headers"` // final response headers
Body string `json:"body"` // final response body (rendered DOM when js-proxy)
RedirectChain []FetchHop `json:"redirect_chain"` // all hops INCLUDING final
CookiesSet []FetchCookie `json:"cookies_set"` // Set-Cookie across all hops
Backend string `json:"backend"` // "html-proxy"|"js-proxy"|"direct"
Degraded bool `json:"degraded"` // fell back from requested backend
DegradedReason string `json:"degraded_reason,omitempty"`
// Network is every HTTP request the browser made while rendering
// the page (document, scripts, XHR, fetch, images, fonts…). Each
// entry carries URL, method, status, request+response headers,
// resource_type, initiator and timing. Populated only when
// WithNetworkLog(true) was passed.
Network []NetworkEntry `json:"network,omitempty"`
// ConsoleLogs is the verbatim browser console output (info, warn,
// error). Most useful: framework dev-mode warnings, stack traces,
// unhandled-promise rejections. Populated only when
// WithNetworkLog(true) was passed.
ConsoleLogs []string `json:"console_logs,omitempty"`
// Performance carries the CDP lifecycle events and the
// window.performance.timing snapshot from the rendered page.
// Populated only when WithNetworkLog(true) was passed.
Performance *Performance `json:"performance,omitempty"`
}
FetchResult is the unified shape returned by Fetch — same struct regardless of which backend (html-proxy / js-proxy / direct) served the request.
Rich-telemetry fields (Network, ConsoleLogs, Performance) are populated only when the caller passes WithNetworkLog(true) (which implies a JS render). They are nil on the html-proxy and direct paths because those backends do not produce that data. Callers should nil-check before walking them; the netextract.go helpers do.
func Fetch ¶
func Fetch(ctx context.Context, target string, opts ...FetchOption) (*FetchResult, error)
Fetch retrieves target through the configured proxy chain. See package doc for backend selection.
func (*FetchResult) HasNetwork ¶
func (r *FetchResult) HasNetwork() bool
HasNetwork reports whether the rich-telemetry fields are present. Callers use this as a guard before walking Network/ConsoleLogs/etc. — keeps the "did we ask for it?" check at one obvious site instead of replicated nil-checks in every consumer.
type NetworkEntry ¶
type NetworkEntry struct {
URL string `json:"url"`
Method string `json:"method"`
Status int `json:"status"`
RequestHeaders map[string]string `json:"request_headers"`
ResponseHeaders map[string]string `json:"response_headers"`
ResponseSize int64 `json:"response_size"`
TimingMs int64 `json:"timing_ms"`
ResourceType string `json:"resource_type"`
Initiator string `json:"initiator"`
}
NetworkEntry is one row of the captured network log for a JS-rendered page.
func ByContentType ¶
func ByContentType(entries []NetworkEntry, prefixes ...string) []NetworkEntry
ByContentType keeps entries whose response Content-Type header begins with any of the listed prefixes (case-insensitive). Pass e.g. "application/javascript", "text/javascript".
func ByHostSuffix ¶
func ByHostSuffix(entries []NetworkEntry, suffixes ...string) []NetworkEntry
ByHostSuffix keeps entries whose URL host ends with any of the given suffixes (case-insensitive). Use to split "first-party vs third-party" without writing your own URL parsing.
func ByMethod ¶
func ByMethod(entries []NetworkEntry, methods ...string) []NetworkEntry
ByMethod keeps entries with one of the listed HTTP methods.
func ByResourceType ¶
func ByResourceType(entries []NetworkEntry, types ...string) []NetworkEntry
ByResourceType keeps entries whose resource_type matches any of the given values (case-insensitive). Common values: "document", "script", "stylesheet", "image", "xhr", "fetch", "websocket", "font", "media", "manifest".
func BySizeGreaterThan ¶
func BySizeGreaterThan(entries []NetworkEntry, n int64) []NetworkEntry
BySizeGreaterThan keeps entries whose response_size exceeds n bytes. Useful when iterating JSAssets to skip tiny stubs/empty chunks.
func ByStatusClass ¶
func ByStatusClass(entries []NetworkEntry, classes ...int) []NetworkEntry
ByStatusClass keeps entries whose status code matches one of the listed class digits (1, 2, 3, 4, 5). Cheap shortcut for "show me every redirect" (ByStatusClass(_, 3)) or "every error" (ByStatusClass(_, 4, 5)).
func JSAssets ¶
func JSAssets(r *FetchResult) []NetworkEntry
JSAssets returns every script the browser loaded — both static <script src> and dynamically imported chunks. Used by secrets-scanner / apikey-scanner / sourcemap-finder as the input list to re-fetch and inspect.
Resource types matched: "script", "stylesheet" is intentionally excluded (CSS rarely carries secrets). Eval/data-URL chunks are kept — they often host inline credentials.
func SourcemapCandidates ¶
func SourcemapCandidates(r *FetchResult) []NetworkEntry
SourcemapCandidates returns JSAssets whose response advertises a SourceMap (case-insensitive header `SourceMap:` or `X-SourceMap:`). The actual `//# sourceMappingURL=` marker lives in the JS body — sourcemap-finder still re-fetches; this just narrows the candidate set from "everything" to "things the server already admits have a map."
type Performance ¶
type Performance struct {
// Lifecycle is the set of CDP page-lifecycle events we record:
// firstPaint, firstContentfulPaint, DOMContentLoaded, load, init.
// Values are milliseconds since the unix epoch.
Lifecycle map[string]int64 `json:"lifecycle"`
// Timing is window.performance.timing.toJSON() verbatim — keys like
// navigationStart, responseEnd, loadEventEnd, etc.
Timing map[string]int64 `json:"timing"`
}
Performance groups page-load timings. Two sub-maps because the keyspaces collide (e.g. `load` exists in both CDP lifecycle events and the legacy window.performance.timing API). Splitting them keeps both losslessly.
type ProxyResult ¶
type ProxyResult struct {
FinalURL string `json:"final_url"`
DOMHTML string `json:"dom_html"`
Network []NetworkEntry `json:"network"`
ConsoleLogs []string `json:"console_logs"`
Performance Performance `json:"performance"`
CookiesSet []map[string]string `json:"cookies_set"`
}
ProxyResult is what JSProxy returns. The field tags describe the go-js-proxy-network payload object. The live service wraps that payload in go-common's response.Success envelope ({"status":"success","data":{…}}), so jsProxyNetwork unwraps .data before populating this struct — the tags below match the INNER (.data) object, not the top-level envelope.
func JSProxy ¶
func JSProxy(ctx context.Context, targetURL string) (*ProxyResult, error)
JSProxy renders targetURL through the **network-aware** proxy (go-js-proxy-network) and returns the parsed result including the Network log, ConsoleLogs and Performance fields. Use this when downstream logic needs request-tree telemetry. For just the DOM, prefer JSProxyDOM — it's cheaper and rate-limited less aggressively.
func JSProxyDOM ¶
func JSProxyDOM(ctx context.Context, targetURL string) (*ProxyResult, error)
JSProxyDOM renders targetURL through the **DOM-only** proxy (go-js-proxy) and returns a ProxyResult populated only with the rendered DOM. Network/ConsoleLogs/Performance fields are nil — this proxy does not produce them. Cheaper than JSProxy; use it when you only need the rendered HTML.
type RedirectParam ¶
type RedirectParam struct {
OnURL string `json:"on_url"` // request URL where the param appeared
Key string `json:"key"` // the parameter name (e.g. "next")
Value string `json:"value"` // the observed value (may itself be a URL)
}
RedirectParam is one observed query parameter on a real network request whose name pattern matches a known open-redirect sink.
func RedirectParams ¶
func RedirectParams(r *FetchResult) []RedirectParam
RedirectParams scans every recorded network URL (not just the rendered page) and returns each query parameter whose key matches a known redirect sink. Use this as the seed list for fuzzing instead of guessing parameter names from corpora.
type XHREndpoint ¶
type XHREndpoint struct {
URL string `json:"url"`
Method string `json:"method"`
Status int `json:"status"`
ContentType string `json:"content_type,omitempty"`
Initiator string `json:"initiator,omitempty"`
ResponseSize int64 `json:"response_size"`
}
XHREndpoint is one runtime-observed API call.
func GraphQLEndpoints ¶
func GraphQLEndpoints(r *FetchResult) []XHREndpoint
GraphQLEndpoints returns endpoints likely speaking GraphQL: an XHR/fetch POST whose URL contains "graphql" OR whose Content-Type is application/json AND ResponseSize > 0. The cheap heuristic is intentional — downstream graphql-introspection probes /graphql with a real introspection query to confirm.
func XHREndpoints ¶
func XHREndpoints(r *FetchResult) []XHREndpoint
XHREndpoints returns one entry per (method, normalised-URL) seen as XHR/fetch/WebSocket traffic in the rendered network log. URL normalisation collapses numeric and UUID path segments to {id}/{uuid} so /users/42, /users/43, /users/44 dedupe to a single /users/{id} template — that's the surface a tampering tool wants.
Returns empty slice for nil/empty input.