hackbrowser

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: Apache-2.0 Imports: 17 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 hackbrowser is an autonomous web-crawling engine built for offensive security reconnaissance. It drives a real Chromium over CDP (via internal/browser), uses a language model to decide where to click and what to type, and records every HTTP request the page issues as it goes — the raw material the rest of an engagement analyzes for vulnerabilities.

Architecture (ported from the TypeScript hackbrowser library at packages/hackbrowser/src/*.ts):

agent.go     BFS crawl loop, auth-phase transitions, post-login re-discovery
scanner.go   DOM collection of every interactive element on a page, via
             embedded JavaScript executed through Runtime.evaluate
navigator.go LLM-driven page planner — given a page snapshot, decide
             what to click and what to fill in
executor.go  resolve a planned task against the live DOM and run it
capture.go   record Network.* events emitted while an action runs, and
             correlate them with the UI element that triggered them
auth.go      anonymous → register → login → authenticated phase flow
scope.go     which hosts the crawl is allowed to capture
state.go     global + per-page crawl state, fingerprinting
api.go       public RunCrawl entry point and CrawlOptions

The original TS codebase kept the playwright dependency in a worker subprocess because Bun's compiled binary crashed at startup when playwright was imported eagerly. Antares drives Chromium directly over CDP and has no such problem, so the worker subprocess + IPC bridge is collapsed entirely into the parent — the engine runs in-process.

Index

Constants

View Source
const AnyMutation = "*"

AnyMutation is the wildcard keyword — a URL marked with it drains on any successful mutation. Specific keywords (e.g. "user-created") drain only on exact match.

View Source
const MaxActionsInPrompt = 10

MaxActionsInPrompt bounds how many ActionRecords we send to the LLM.

View Source
const MaxFailedElements = 20

MaxFailedElements bounds the failed-element list in the prompt.

View Source
const MaxPlannerOutputTokens = 16384

MaxPlannerOutputTokens caps the planner response. The plan is small JSON; 16K is generous headroom for reasoning models that emit a chain-of-thought prefix before the JSON body.

View Source
const MaxRevisitsPerURL = 2

MaxRevisitsPerURL caps how many times one URL can come back for a re-explore after a mutation. Combined with the fingerprint skip, this makes re-discovery loops impossible.

View Source
const SingleCred = "__single__"

SingleCred is the credential-id sentinel for anonymous or single-credential crawls.

Variables

View Source
var ErrNoModel = errors.New("hackbrowser: no LLM provider configured for the planner")

ErrNoModel is returned when no provider is available for the planner.

View Source
var Log = newLogState()

Log is the package-level logger configuration. Hold the singleton state (current level, current sink) and produce per-service Loggers.

Functions

func AutoLogin

func AutoLogin(ctx context.Context, sess *browser.Session, creds LoginCredentials) error

AutoLogin fills a username and password into the page's login form and submits it. Selector fallbacks cover the common cases (input[type=email], input[name=user], etc.); callers can override with explicit selectors when the form is non-standard.

On failure (form not found, timeout), the caller should fall back to WaitForManualLogin — auto-login is best-effort, not authoritative.

func AvailabilityToRecord

func AvailabilityToRecord(availability map[string][]string) map[string][]string

AvailabilityToRecord converts the availability map to a flat "role:label" keyed record for JSON serialization.

func BuildRawRequest

func BuildRawRequest(method, rawURL string, headers map[string]string, body string) string

BuildRawRequest formats an HTTP request as the raw wire string the rest of the engagement expects:

POST /api/Users?x=1 HTTP/1.1
Host: example.com
Content-Type: application/json

{"name":"alice"}

Mirrors what a browser extension captures, so downstream tooling does not have to know it came from a headless crawler.

func ClassifyAuthURL

func ClassifyAuthURL(rawURL string) string

ClassifyAuthURL returns "register", "login", "logout", or "" if the URL does not look auth-related.

func ComputeElementAvailability

func ComputeElementAvailability(elementsByContext map[string][]RawElement) map[string][]string

ComputeElementAvailability maps "role::label" → list of contexts that have that element. Used for multi-credential page diffing.

func DeriveScope

func DeriveScope(targetURL string) string

DeriveScope produces "*.${eTLD+1}" from a target URL. Examples:

https://test.com          → *.test.com
https://app.test.com      → *.test.com
https://x.example.com.tr  → *.example.com.tr (PSL handles ccTLDs)
https://10.0.0.1          → *.10.0.0.1       (raw IP — PSL cannot resolve)

The fallback is the bare hostname so the agent still works against test setups that have no real eTLD+1.

func DrainEmptyStateQueue

func DrainEmptyStateQueue(state *GlobalState, credID string) []string

DrainEmptyStateQueue is the legacy alias — drains only AnyMutation URLs.

func DrainOnMutation

func DrainOnMutation(state *GlobalState, credID, taskMutation string) []string

DrainOnMutation unqueues empty-state URLs whose expected mutation matches the given keyword (or expects AnyMutation). Matched URLs are pushed onto the front of the page queue and have their revisit counter incremented. Returns the URLs that were drained.

func ExpandDisclosures

func ExpandDisclosures(ctx context.Context, sess *browser.Session)

ExpandDisclosures opens safe-by-ARIA-semantics collapsible regions so their hidden controls become real attack surface in the snapshot, without spending LLM turns on them. Two tiers:

  • native <details> → set .open (no event, zero side effect)
  • [aria-expanded="false"] controls without aria-haspopup → click

Tabs (role=tab) are excluded (selecting one mutates active-panel state). Bounded by expandMax. Non-fatal on mid-expand navigation.

func GenerateFingerprint

func GenerateFingerprint(elements []RawElement) string

GenerateFingerprint produces the input + content-action fingerprint used for post-login re-discovery comparison. Inputs always count; content-area actions (not in site chrome) count too; links never count; sorted.

func GenerateFullFingerprint

func GenerateFullFingerprint(elements []RawElement) string

GenerateFullFingerprint includes buttons and all interactive roles for multi-credential page diffing. Excludes links and info elements (false positives from sidebar/navbar noise). Excludes value (user-specific data).

func Handle2FA

func Handle2FA(ctx context.Context, sess *browser.Session) bool

Handle2FA returns true when an OTP field was found and filled.

func Handle2FAWithPrompt

func Handle2FAWithPrompt(ctx context.Context, sess *browser.Session, prompt PromptFunc) bool

Handle2FAWithPrompt is the testable form. When prompt is nil and an OTP field IS found, the field is left empty and the function returns true — the caller then knows to ask the user out-of-band.

func HasSuccessfulMutation

func HasSuccessfulMutation(httpRequests []string) bool

HasSuccessfulMutation reports whether any line in the httpRequests log shows a 2xx POST/PUT/PATCH/DELETE. Format: "METHOD /path [status]".

func IsViewportCenterBlocked

func IsViewportCenterBlocked(ctx context.Context, sess *browser.Session) bool

IsViewportCenterBlocked reports whether a modal/backdrop overlay is covering the viewport center — the planner uses this to decide whether to plan a "dismiss" task before anything else.

func LoadSession

func LoadSession(ctx context.Context, sess *browser.Session, filePath string) (bool, error)

LoadSession reads cookies from filePath and installs them into the browser. Returns (true, nil) on success; (false, nil) when the file does not exist (first-run case, not an error).

func MarkPageEmpty

func MarkPageEmpty(state *GlobalState, credID, pageURL, expectedMutation string) bool

MarkPageEmpty queues a URL for revisit after a mutation, scoped to one credential. Returns false if the hard limit rejects it.

func NormalizeScope

func NormalizeScope(input string) string

NormalizeScope strips scheme/path/port and lowercases the input. Wildcard "*.foo.com" prefixes are preserved. Empty input → empty output.

func NormalizeURL

func NormalizeURL(rawURL string) string

NormalizeURL canonicalizes a URL for storage and dedup: lowercased origin (via url.Parse), sorted query, no trailing slash, unified hash routing. On parse failure the input is returned unchanged so the caller never loses the URL entirely.

func ParseRequestParams

func ParseRequestParams(body, rawURL string) map[string]string

ParseRequestParams flattens a request's query string and body into a flat key=value map. Tries JSON first (dot-path flattening), then form-encoding. Always also parses the URL query string.

func RecordAction

func RecordAction(page *PageState, elementID, action, value string, result ActionResult)

RecordAction appends one action's outcome to the page state and updates the failed-element set.

func RevealLazyContent

func RevealLazyContent(ctx context.Context, sess *browser.Session)

RevealLazyContent scrolls the page down in viewport-sized steps to trip IntersectionObserver-based lazy loading, then returns to the top. Bounded so an infinite-scroll page cannot trap the crawl. Non-fatal on mid-scroll navigation.

func SaveSession

func SaveSession(ctx context.Context, sess *browser.Session, filePath string, urls []string) error

SaveSession writes the browser's current cookies for one or more URLs to filePath. Existing file is overwritten.

Types

type ActionRecord

type ActionRecord struct {
	ElementID       string   `json:"element_id"`
	Action          string   `json:"action"`
	Value           string   `json:"value,omitempty"`
	Success         bool     `json:"success"`
	HTTPSideEffects []string `json:"http_side_effects,omitempty"` // "POST /api/Users [201]"
}

ActionRecord is one executed action on the current page.

type ActionResult

type ActionResult struct {
	Success      bool     `json:"success"`
	Error        string   `json:"error,omitempty"`
	Navigated    bool     `json:"navigated,omitempty"`
	NewURL       string   `json:"new_url,omitempty"`
	HTTPRequests []string `json:"http_requests,omitempty"` // "POST /api/Users [201]"
	DOMChanged   bool     `json:"dom_changed,omitempty"`
}

ActionResult is fed back to the LLM after each action.

type Agent

type Agent struct {
	Sess     *browser.Session
	Planner  *LLMPlanner
	Executor *Executor
	Scope    ScopeMatcher

	// State accumulates across the whole crawl.
	Global *GlobalState

	// Cred is the credential id tagging this crawl's captures. SingleCred
	// for anonymous; otherwise the credential label.
	Cred string

	// Sink receives captured HTTP requests, scoped by Scope. Nil drops them.
	Sink func(CapturedRequest)

	// EventSink receives telemetry events (page-change, plan-received, ...).
	EventSink func(CSEvent)

	// Done, when closed, signals graceful cancellation. The agent finishes
	// the current step and exits.
	Done <-chan struct{}

	// Usage accumulates LLM token usage across the whole crawl.
	Usage *CrawlUsage
	// contains filtered or unexported fields
}

Agent owns one crawl's mutable state: the BFS queue, the visited set, the planner/executor, the sink for captures, and the event sink for telemetry. Methods are not safe for concurrent use — one crawl per Agent instance.

func (*Agent) Crawl

func (a *Agent) Crawl(ctx context.Context, startURL string, maxSteps int) []string

Crawl runs the BFS loop until the queue empties, MaxSteps is hit, or Done fires. Returns the list of errors encountered (also pushed onto the agent's CrawlResult.Errors via the caller).

type AuthPhase

type AuthPhase string

AuthPhase tracks where the crawl is in its auth journey.

const (
	AuthAnonymous     AuthPhase = "anonymous"
	AuthRegistered    AuthPhase = "registered"
	AuthAuthenticated AuthPhase = "authenticated"
)

type CSEvent

type CSEvent struct {
	Type string `json:"type"`

	// Common fields — populated as relevant per Type.
	Target            string         `json:"target,omitempty"`
	Credentials       []string       `json:"credentials,omitempty"`
	MaxPages          int            `json:"max_pages,omitempty"`
	StartedAt         time.Time      `json:"started_at,omitempty"`
	URL               string         `json:"url,omitempty"`
	PageNum           int            `json:"page_num,omitempty"`
	Credential        string         `json:"credential,omitempty"`
	Tasks             int            `json:"tasks,omitempty"`
	PageState         PageStateKind  `json:"page_state,omitempty"`
	Summary           []EventSummary `json:"summary,omitempty"`
	Kind              string         `json:"kind,omitempty"`
	TargetLabel       string         `json:"target_label,omitempty"`
	Value             string         `json:"value,omitempty"`
	OK                bool           `json:"ok,omitempty"`
	Mutation          bool           `json:"mutation,omitempty"`
	Method            string         `json:"method,omitempty"`
	Path              string         `json:"path,omitempty"`
	Status            int            `json:"status,omitempty"`
	Trigger           string         `json:"trigger,omitempty"`
	IsMutation        bool           `json:"is_mutation,omitempty"`
	Note              string         `json:"note,omitempty"`
	Reason            string         `json:"reason,omitempty"`
	Elements          int            `json:"elements,omitempty"`
	From              string         `json:"from,omitempty"`
	To                string         `json:"to,omitempty"`
	PagesExplored     int            `json:"pages_explored,omitempty"`
	CapturedEndpoints int            `json:"captured_endpoints,omitempty"`
	Mutations         int            `json:"mutations,omitempty"`
}

CSEvent is one telemetry event. The discriminated Type field selects the shape of the rest of the payload. Unknown kinds are ignored by consumers, so new ones can be added without breaking older sinks.

type CapturedRequest

type CapturedRequest struct {
	Raw            string            `json:"raw"`    // wire-format HTTP request
	Scheme         string            `json:"scheme"` // "http" or "https"
	Response       *CapturedResponse `json:"response,omitempty"`
	UIContext      *UIContext        `json:"ui_context,omitempty"`
	TriggerElement string            `json:"trigger_element,omitempty"` // "button:Delete User"
	ElementRoles   []string          `json:"element_roles,omitempty"`
	PageURL        string            `json:"page_url,omitempty"`
	PageVisitedBy  []string          `json:"page_visited_by,omitempty"`
	Timestamp      time.Time         `json:"timestamp"`
}

CapturedRequest is one HTTP request the page issued during a crawl.

type CapturedResponse

type CapturedResponse struct {
	Status  int               `json:"status"`
	Headers map[string]string `json:"headers"`
	Body    string            `json:"body"`
}

CapturedResponse is the HTTP response paired with a CapturedRequest.

type ClickPointProbe

type ClickPointProbe struct {
	Status   string
	Occluder *OccluderInfo
}

ClickPointProbe reports whether an element matching sel can be clicked at its centre, or whether an overlay occludes it. Status is one of:

  • "clickable" — proceed normally
  • "offscreen" — needs a scroll first
  • "occluded" — an unrelated element is on top; the planner should plan a dismiss action first

The probe is best-effort: any failure to resolve the element returns "clickable" so the normal click path runs unchanged.

func ProbeClickPoint

func ProbeClickPoint(ctx context.Context, sess *browser.Session, selector string) ClickPointProbe

ProbeClickPoint runs the occlusion probe for one selector.

type ClickTask

type ClickTask struct {
	Type             string `json:"type"` // always "click"
	Role             string `json:"role"`
	Label            string `json:"label"`
	Reason           string `json:"reason,omitempty"`
	TriggersMutation string `json:"triggers_mutation,omitempty"`
}

ClickTask clicks a button/tab/accordion/interactive element.

type ConfirmFunc

type ConfirmFunc func()

ConfirmFunc resumes a paused manual-login wait.

func WaitForManualLogin

func WaitForManualLogin(ctx context.Context, sess *browser.Session, req ManualLoginRequest) (ConfirmFunc, <-chan struct{})

WaitForManualLogin blocks until the caller signals that the user has finished logging in. v1 of this port has no in-page button UI — the caller (agent loop) asks the user out-of-band, then calls the returned ConfirmFunc.

This is structured so the agent loop can present the request any way it likes (terminal, web dashboard, slash command) without the auth package needing to know about any of those surfaces.

type CrawlOptions

type CrawlOptions struct {
	// Target (required).
	URL string

	// Session that owns the captures, in antares' store. Optional — anonymous
	// dry-runs leave it empty.
	SessionID string

	// CredentialID tags captures with a single identity. Mutually exclusive
	// with MultiCredentials.
	CredentialID string

	// Log level: "DEBUG", "INFO" (default), "WARN", "ERROR".
	LogLevel string

	// EventSink, when set, receives every CSEvent the crawler emits
	// (page-change, capture, crawl-done, ...). Independent of the panel UI.
	EventSink func(event CSEvent)

	// Network scope: hostnames whose requests get captured. Empty → derive
	// from URL via eTLD+1 as "*.{eTLD+1}".
	Scope []string
	// OutOfScope are semantic labels the planner must never plan (e.g.
	// "Delete Account"). Distinct from Scope.
	Exclude []string

	// Crawl behaviour.
	Steps    int // max navigation steps; 0 → 50
	Headless bool

	// Auth.
	SessionFile      string // path to a saved cookies JSON
	Credentials      *LoginCredentials
	Authenticated    bool // manual login via visible browser
	MultiCredentials []CredentialConfig

	// DryRun: crawl without sending captures to the session store; print to log.
	DryRun bool

	// Cancellation. When fired, the agent finishes the current step and exits
	// the BFS loop gracefully.
	Done <-chan struct{}
}

CrawlOptions is the public entry point's argument shape. Flat on purpose — the nested AgentConfig is internal.

type CrawlResult

type CrawlResult struct {
	SessionID         string     `json:"session_id"`
	CapturedEndpoints int        `json:"captured_endpoints"`
	PagesExplored     int        `json:"pages_explored"`
	TotalSteps        int        `json:"total_steps"`
	Errors            []string   `json:"errors"`
	Usage             CrawlUsage `json:"usage"`
}

CrawlResult is what RunCrawl returns. Errors are aggregated here rather than thrown — caller decides how to surface them.

func RunCrawl

func RunCrawl(ctx context.Context, opts CrawlOptions, model llm.Client) (CrawlResult, error)

RunCrawl is the single public entry point. It is blocking — the caller is expected to wrap it in a goroutine if it needs to run in the background. Cancellation is via opts.Done; the agent finishes the current step and exits.

type CrawlUsage

type CrawlUsage struct {
	InputTokens      int `json:"input_tokens"`
	OutputTokens     int `json:"output_tokens"`
	CacheReadTokens  int `json:"cache_read_tokens"`
	CacheWriteTokens int `json:"cache_write_tokens"`
}

CrawlUsage is the LLM token usage for the whole crawl.

type CredentialConfig

type CredentialConfig struct {
	ID string `json:"id"` // "admin", "user", "manager", ...
}

CredentialConfig is one identity in a multi-credential crawl.

type DeferredAuthPage

type DeferredAuthPage struct {
	URL  string `json:"url"`
	Type string `json:"type"` // "register" | "login" | "logout"
}

DeferredAuthPage is an auth-related URL discovered during the anonymous phase and queued for processing later, in pentester order: register → login → logout.

type EventSummary

type EventSummary struct {
	Kind  string `json:"kind"` // "form" | "click"
	Label string `json:"label"`
}

EventSummary is one entry in a plan-received event's task list.

type Executor

type Executor struct {
	Sess *browser.Session
}

Executor runs one planned task (click or form) against the page.

func (*Executor) ExecuteTask

func (e *Executor) ExecuteTask(ctx context.Context, task PageTask, elements []RawElement) ActionResult

ExecuteTask runs one PageTask. Returns the per-element ActionResult (success/failure, navigation, dom change indicator). The caller owns draining Network events around the call.

type FormFieldPlan

type FormFieldPlan struct {
	Role  string `json:"role"`  // "textbox"|"combobox"|"checkbox"|"radio"|"slider"
	Label string `json:"label"` // semantic key — executor resolves to live element
	Value string `json:"value"` // computed by LLM
}

FormFieldPlan is one field in a FormTask — role+label identifies the element, value is what to write.

type FormSubmitRef

type FormSubmitRef struct {
	Role  string `json:"role"`
	Label string `json:"label"`
}

FormSubmitRef identifies the submit button by role+label.

type FormTask

type FormTask struct {
	Type             string          `json:"type"` // always "form"
	Fields           []FormFieldPlan `json:"fields"`
	Submit           FormSubmitRef   `json:"submit"`
	TriggersMutation string          `json:"triggers_mutation,omitempty"`
}

FormTask fills a form completely and submits it.

type GlobalState

type GlobalState struct {
	VisitedPages       map[string]bool
	CapturedPaths      map[string]bool // "METHOD /path" dedup
	AuthPhase          AuthPhase
	TotalSteps         int
	PageQueue          []string
	DeferredAuth       []DeferredAuthPage
	PendingReDiscovery bool
	PathPatternCount   map[string]int
	OutOfScope         []string
	// Credential-scoped intelligence, keyed by credential id. Single-cred
	// crawls use the SingleCred sentinel key.
	IntelligenceByCredential map[string]*IntelligenceState
}

GlobalState is the cross-credential state of a crawl.

func CreateGlobalState

func CreateGlobalState(outOfScope []string) *GlobalState

CreateGlobalState builds an empty GlobalState with the given out-of-scope labels snapshotted in. The caller's slice is not retained.

type IntelligenceState

type IntelligenceState struct {
	// URL → mutation keyword to match. "*" means any-mutation (legacy fallback).
	EmptyStateQueue map[string]string
	// URL → revisit count (hard cap: 2 per URL per credential).
	RevisitCount map[string]int
	// URL → element fingerprint, for re-visit comparison.
	PageFingerprints map[string]string
}

IntelligenceState is credential-scoped crawl metadata: empty-state signals, revisit counters, and DOM fingerprints. Each credential in a multi-cred crawl owns its own instance so signals cannot leak between identities.

func GetIntelligence

func GetIntelligence(state *GlobalState, credID string) *IntelligenceState

GetIntelligence returns (lazily creating) the credential-scoped intelligence state. Pass SingleCred in single-credential mode.

type LLMPlanner

type LLMPlanner struct {
	Model llm.Client
	Usage *CrawlUsage // optional accumulator
}

LLMPlanner is the production planner — wraps an llm.Client.

func (*LLMPlanner) Plan

func (p *LLMPlanner) Plan(ctx context.Context, snapshot PlannerSnapshot) (PagePlan, error)

Plan implements Planner. One LLM call per page.

func (*LLMPlanner) PlanUnexplored

func (p *LLMPlanner) PlanUnexplored(ctx context.Context, snapshot PlannerSnapshot, unexplored []string) (PagePlan, error)

PlanUnexplored asks the model to plan only for elements the first pass skipped. The agent uses this as a follow-up when the first plan left elements untouched (System Observes, LLM Interprets).

type LogExtra

type LogExtra struct {
	Key   string
	Value any
}

LogExtra is one key/value pair for structured logging. Construct with F("key", value) and pass variadically: log.Info("login detected", F("user", name), F("after", elapsed)).

func F

func F(key string, value any) LogExtra

F builds one LogExtra. The single-letter name keeps call sites readable.

type LogLevel

type LogLevel string

LogLevel orders severity. Priority grows top-to-bottom.

const (
	LevelDebug LogLevel = "DEBUG"
	LevelInfo  LogLevel = "INFO"
	LevelWarn  LogLevel = "WARN"
	LevelError LogLevel = "ERROR"
)

type LogRecord

type LogRecord struct {
	Level     LogLevel       `json:"level"`
	Service   string         `json:"service"`
	Message   string         `json:"message"`
	Extra     map[string]any `json:"extra,omitempty"`
	Timestamp time.Time      `json:"timestamp"`
}

LogRecord is one structured log entry.

type LogSink

type LogSink func(record LogRecord)

LogSink receives records. Replace via SetSink.

type Logger

type Logger interface {
	Debug(message string, extra ...LogExtra)
	Info(message string, extra ...LogExtra)
	Warn(message string, extra ...LogExtra)
	Error(message string, extra ...LogExtra)
}

Logger is the per-service handle.

type LoginCredentials

type LoginCredentials struct {
	Username         string
	Password         string
	UsernameSelector string // optional CSS override
	PasswordSelector string
}

LoginCredentials auto-fills a login form.

type ManualLoginRequest

type ManualLoginRequest struct {
	Label string // "admin", "user", ... — empty for single-credential
	URL   string // page the user should be on
	Step  int    // 1-based step in a multi-credential sequence
	Total int    // total steps in the sequence
}

ManualLoginRequest is what an auth flow returns when it needs the user to log in by hand. The agent surfaces this to the user (terminal prompt or ask_user tool) and calls ConfirmManualLogin once the user is ready.

type OccluderInfo

type OccluderInfo struct {
	Tag  string `json:"tag"`
	Role string `json:"role"`
	Text string `json:"text"`
}

OccluderInfo describes the element covering a click target.

type OcclusionSignal

type OcclusionSignal struct {
	Label        string
	Role         string
	OccluderText string
}

OcclusionSignal is one element found covered by an overlay at click time.

type OcclusionState

type OcclusionState struct {
	Pending  []OcclusionSignal
	Signaled map[string]bool
}

OcclusionState threads through a page visit to bound dismiss loops.

type PagePlan

type PagePlan struct {
	Tasks         []PageTask    `json:"tasks"`
	PageState     PageStateKind `json:"page_state,omitempty"`
	RevisitAfter  string        `json:"revisit_after,omitempty"` // "any-mutation" or ""
	RevisitReason string        `json:"revisit_reason,omitempty"`
	RevisitOn     string        `json:"revisit_on,omitempty"` // mutation keyword
}

PagePlan is the LLM's analysis of a page: what to do, when to revisit.

type PageState

type PageState struct {
	CurrentURL            string
	Elements              []RawElement
	ViewportCenterBlocked bool
	ActionsThisPage       []ActionRecord
	FailedElementIDs      map[string]bool
	LastActionResult      *ActionResult
	Step                  int
}

PageState is everything that resets on every page transition.

func CreatePageState

func CreatePageState(url string) *PageState

CreatePageState builds an empty PageState for one URL.

type PageStateKind

type PageStateKind string

PageStateKind is the planner's classification of a page's content.

const (
	PageStatePopulated PageStateKind = "populated"
	PageStateEmpty     PageStateKind = "empty"
	PageStateUnknown   PageStateKind = "unknown"
)

type PageTask

type PageTask struct {
	Type             string          `json:"type"`
	Fields           []FormFieldPlan `json:"fields,omitempty"` // for "form"
	Submit           *FormSubmitRef  `json:"submit,omitempty"` // for "form"
	Role             string          `json:"role,omitempty"`   // for "click"
	Label            string          `json:"label,omitempty"`  // for "click"
	Reason           string          `json:"reason,omitempty"` // for "click"
	TriggersMutation string          `json:"triggers_mutation,omitempty"`
}

PageTask is the discriminated union of FormTask and ClickTask. The Type field discriminates: "form" or "click".

type Planner

type Planner interface {
	// Plan asks the model what to do with the current page snapshot.
	// Returns a validated PagePlan; an empty plan when the model declines.
	Plan(ctx context.Context, snapshot PlannerSnapshot) (PagePlan, error)
}

Planner is the contract a per-page planner satisfies. Implementations wrap an llm.Client; tests can substitute a stub.

type PlannerSnapshot

type PlannerSnapshot struct {
	URL                   string          `json:"url"`
	ViewportCenterBlocked bool            `json:"viewport_center_blocked"`
	TotalPagesVisited     int             `json:"total_pages_visited"`
	Elements              []PromptElement `json:"elements"`
	OutOfScope            []string        `json:"out_of_scope,omitempty"`
	PendingMutations      []string        `json:"pending_mutations,omitempty"`
}

PlannerSnapshot is the minimal view the planner needs — no action history.

func BuildPlannerSnapshot

func BuildPlannerSnapshot(
	pageURL string,
	elements []RawElement,
	state *GlobalState,
	credID string,
	viewportCenterBlocked bool,
	occlusions []OcclusionSignal,
) PlannerSnapshot

BuildPlannerSnapshot produces the minimal model-facing view of one page.

type PromptElement

type PromptElement struct {
	ID          string `json:"id"`
	Role        string `json:"role"`
	Label       string `json:"label"`
	Type        string `json:"type,omitempty"`
	Value       string `json:"value,omitempty"`
	Placeholder string `json:"placeholder,omitempty"`
	Href        string `json:"href,omitempty"`
	Options     string `json:"options,omitempty"`
	Constraints string `json:"constraints,omitempty"`
	Enabled     *bool  `json:"enabled,omitempty"` // pointer so omitted when true
	OccludedBy  string `json:"occluded_by,omitempty"`
}

PromptElement is the model-facing view of a RawElement: id/role/label and selected hints, but never the selector.

type PromptFunc

type PromptFunc func(ctx context.Context, prompt string) (string, error)

Handle2FA detects a visible OTP/MFA input and prompts the user for a code via the provided PromptFunc. If no MFA field is visible, returns false immediately.

In v1 the prompt is terminal-based. The caller passes a function that knows how to ask the user (the agent tool surfaces this as an ask_user step).

type PromptPayload

type PromptPayload struct {
	URL                   string          `json:"url"`
	ViewportCenterBlocked bool            `json:"viewport_center_blocked"`
	TotalPagesVisited     int             `json:"total_pages_visited"`
	UnvisitedLinksOnPage  int             `json:"unvisited_links_on_page"`
	LastAction            *ActionRecord   `json:"last_action,omitempty"`
	RecentActions         []ActionRecord  `json:"recent_actions"`
	FailedElements        []string        `json:"failed_elements"`
	Elements              []PromptElement `json:"elements"`
}

PromptPayload is the structured user-message body the planner LLM sees.

func BuildPromptPayload

func BuildPromptPayload(page *PageState, state *GlobalState) PromptPayload

BuildPromptPayload assembles the structured user message body sent to the per-step LLM (the legacy per-action planner).

type RawElement

type RawElement struct {
	ID          string `json:"id"`      // "E1", "E2", ... assigned by scanner
	Tag         string `json:"tag"`     // "button", "input", "a", ...
	Role        string `json:"role"`    // ARIA role or implicit role
	Label       string `json:"label"`   // aria-label || label[for] || innerText || placeholder || name
	Value       string `json:"value"`   // current value (input/select/aria-valuenow)
	Enabled     bool   `json:"enabled"` // !disabled
	Href        string `json:"href"`    // for links
	Type        string `json:"type"`    // input type
	Placeholder string `json:"placeholder"`
	Options     string `json:"options"`     // comma-separated <option> values for <select>
	Constraints string `json:"constraints"` // "min:0 max:1000 step:10", "maxlength:160", ...
	Selector    string `json:"selector"`    // CSS or role selector — never shown to the LLM
	InChrome    bool   `json:"in_chrome"`   // inside nav/header/footer/aside landmark
}

RawElement is one interactive element collected from the DOM by the scanner. The model sees id/role/label/value but never sees the selector — selectors are private to the executor so the model cannot be tricked into producing an injection via selector.

func CollectElements

func CollectElements(ctx context.Context, sess *browser.Session) ([]RawElement, error)

CollectElements runs the scanner in the page and returns the prepared element list. Pure — no caching, no mutations outside the page.

func FilterVisitedLinks(elements []RawElement, currentURL string, visited map[string]bool) []RawElement

FilterVisitedLinks drops links whose target points at a page that has already been visited (or is the current page). Non-link elements and unparseable hrefs are always kept.

func FindElement

func FindElement(page *PageState, elementID string) *RawElement

FindElement returns the RawElement with the given ID, or nil.

type ScopeMatcher

type ScopeMatcher func(host string) bool

ScopeMatcher returns true when a host matches ANY of the patterns (OR). A pattern may be a wildcard ("*.foo.com") or a bare host ("foo.com") — both match foo.com itself plus any subdomain. Empty pattern list → matcher that rejects everything (safe default).

func MakeMatcher

func MakeMatcher(scopes []string) ScopeMatcher

MakeMatcher builds a ScopeMatcher from one or more patterns. Inputs are normalized; wildcard prefixes stripped; the matcher is a tight loop over a slice of bases so it can be called per request without allocating.

type SessionFile

type SessionFile struct {
	Cookies []browser.Cookie `json:"cookies"`
	SavedAt time.Time        `json:"saved_at"`
}

SessionFile is the JSON shape persisted to disk by SaveSession and read back by LoadSession. It is intentionally a thin wrapper around a slice of browser.Cookie — local-storage and IndexedDB persistence would require CDP Storage domain calls and add complexity without much real benefit (most authenticated SPAs rely on cookies, not localStorage).

type UIContext

type UIContext struct {
	PageURL       string    `json:"page_url"`
	PageTitle     string    `json:"page_title"`
	ComponentPath string    `json:"component_path"` // "Settings > Profile > Edit Form"
	FormName      string    `json:"form_name"`
	Fields        []UIField `json:"fields"`
	HiddenParams  []string  `json:"hidden_params"`
}

UIContext is what was visible on the page when a request fired.

func CorrelateWithUI

func CorrelateWithUI(ui *UIContext, requestParams map[string]string) *UIContext

CorrelateWithUI flags request parameters that are NOT present in the UI snapshot — hidden fields the page did not surface to the user. These are candidates for tampering attacks (CSRF tokens, legacy ids, debug flags).

The match is case-insensitive on field name. requestParams is the flat key=value map parsed from the request body or query string.

func SnapshotPageUI

func SnapshotPageUI(
	ctx context.Context,
	sess *browser.Session,
	triggerSel, componentPath string,
) (*UIContext, error)

SnapshotPageUI collects form fields visible on the page, scoped to the form or dialog that contains the trigger element. The returned UIContext is what gets attached to HTTP captures for later correlation.

triggerSel is a CSS selector for the element that triggered the action (typically the submit button); pass empty for a full-page scan. The componentPath is cosmetic — used as a hint in the captured UIContext.

type UIField

type UIField struct {
	Name          string `json:"name"`
	Label         string `json:"label"`
	Value         string `json:"value"`
	Type          string `json:"type"`
	Options       string `json:"options,omitempty"`
	IsReadOnly    bool   `json:"is_read_only"`
	IsDisabled    bool   `json:"is_disabled"`
	IsHidden      bool   `json:"is_hidden"`
	HiddenReason  string `json:"hidden_reason,omitempty"`
	IsDisplayOnly bool   `json:"is_display_only"`
	Validation    struct {
		Min       string `json:"min,omitempty"`
		Max       string `json:"max,omitempty"`
		MaxLength string `json:"max_length,omitempty"`
		Pattern   string `json:"pattern,omitempty"`
		Required  bool   `json:"required,omitempty"`
	} `json:"validation"`
}

UIField is one form field visible in the page UI at capture time. Used to correlate HTTP request parameters with the controls a user actually sees.

Jump to

Keyboard shortcuts

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