Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

feat: add POST /audit/page single-page browser enrichment engine

Luigi Agosti29dc0edbeaa4
diff --git a/internal/audit/enrich.go b/internal/audit/enrich.go
new file mode 100644
index 00000000..f843b011
--- /dev/null
+++ b/internal/audit/enrich.go
@@ -0,0 +1,212 @@
+package audit
+
+import (
+ "encoding/base64"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/bridge/observe"
+)
+
+// PageOptions selects which collectors run when enriching a page.
+type PageOptions struct {
+ Screenshot bool `json:"screenshot"`
+ Network bool `json:"network"`
+ Console bool `json:"console"`
+ A11y bool `json:"a11y"`
+ Timing bool `json:"timing"`
+ Elements bool `json:"elements"`
+}
+
+// DefaultPageOptions enables every collector.
+func DefaultPageOptions() PageOptions {
+ return PageOptions{Screenshot: true, Network: true, Console: true, A11y: true, Timing: true, Elements: true}
+}
+
+// Collectors are the browser-backed data sources EnrichPage composes. Hooks
+// for disabled options may be nil.
+type Collectors struct {
+ Title func() (string, error)
+ Screenshot func() ([]byte, error)
+ Console func() ([]bridge.LogEntry, error)
+ Network func() ([]observe.NetworkEntry, error)
+ Snapshot func() ([]observe.A11yNode, error)
+ PageFacts func() (PageFacts, error)
+ Timing func() (*observe.TimingMetrics, error)
+}
+
+// PageAudit is the audit result for one page. Collector failures are data,
+// not errors: they land in Error while the remaining fields stay populated.
+type PageAudit struct {
+ // URL is the audited page URL as requested.
+ URL string `json:"url"`
+ // Title is the page title after navigation.
+ Title string `json:"title,omitempty"`
+ // Error describes navigation or collector failures, empty on success.
+ Error string `json:"error,omitempty"`
+ // Screenshot is the base64-encoded PNG when screenshot capture is on.
+ Screenshot string `json:"screenshot,omitempty"`
+ // A11yFindings are the accessibility rule violations behind AccessibilityScore.
+ A11yFindings []A11yFinding `json:"a11yFindings,omitempty"`
+ BrowserPageData
+}
+
+// NewPageAuditError returns the structured entry for a page that could not
+// be navigated at all.
+func NewPageAuditError(url string, err error) PageAudit {
+ return PageAudit{URL: url, Error: err.Error()}
+}
+
+// EnrichPage assembles a PageAudit from an already-navigated page via the
+// given collectors, honoring opts. Individual collector failures never abort
+// the audit; they are recorded in the Error field.
+func EnrichPage(url string, opts PageOptions, c Collectors) PageAudit {
+ pa := PageAudit{URL: url}
+ var errs []string
+ fail := func(stage string, err error) { errs = append(errs, stage+": "+err.Error()) }
+
+ if c.Title != nil {
+ if title, err := c.Title(); err == nil {
+ pa.Title = title
+ }
+ }
+
+ if opts.Console && c.Console != nil {
+ if logs, err := c.Console(); err != nil {
+ fail("console", err)
+ } else {
+ pa.ConsoleLogs = MapConsoleLogs(logs)
+ }
+ }
+
+ if opts.Network && c.Network != nil {
+ if entries, err := c.Network(); err != nil {
+ fail("network", err)
+ } else {
+ pa.NetworkRequests = MapNetworkRequests(entries)
+ pa.BrokenAssets = MapBrokenAssets(observe.BrokenAssets(entries))
+ }
+ }
+
+ var nodes []observe.A11yNode
+ if (opts.Elements || opts.A11y) && c.Snapshot != nil {
+ var err error
+ if nodes, err = c.Snapshot(); err != nil {
+ fail("snapshot", err)
+ nodes = nil
+ }
+ }
+ if opts.Elements {
+ pa.InteractiveElements = MapInteractiveElements(nodes)
+ }
+ if opts.A11y && c.PageFacts != nil {
+ if facts, err := c.PageFacts(); err != nil {
+ fail("a11y", err)
+ } else {
+ report := EvaluateA11y(nodes, facts)
+ pa.AccessibilityScore = report.Score
+ pa.A11yFindings = report.Findings
+ }
+ }
+
+ if opts.Timing && c.Timing != nil {
+ if timing, err := c.Timing(); err != nil {
+ fail("timing", err)
+ } else if timing != nil {
+ pa.TimingMetrics = MapTimingMetrics(*timing)
+ }
+ }
+
+ if opts.Screenshot && c.Screenshot != nil {
+ if png, err := c.Screenshot(); err != nil {
+ fail("screenshot", err)
+ } else {
+ pa.Screenshot = base64.StdEncoding.EncodeToString(png)
+ }
+ }
+
+ pa.Error = strings.Join(errs, "; ")
+ return pa
+}
+
+// MapConsoleLogs converts bridge console entries to the audit schema.
+func MapConsoleLogs(logs []bridge.LogEntry) []ConsoleLogEntry {
+ out := make([]ConsoleLogEntry, 0, len(logs))
+ for _, l := range logs {
+ out = append(out, ConsoleLogEntry{
+ Timestamp: l.Timestamp,
+ Level: l.Level,
+ Message: l.Message,
+ Source: l.Source,
+ })
+ }
+ return out
+}
+
+// MapNetworkRequests converts observed network entries to the audit schema.
+func MapNetworkRequests(entries []observe.NetworkEntry) []NetworkRequest {
+ out := make([]NetworkRequest, 0, len(entries))
+ for _, e := range entries {
+ out = append(out, NetworkRequest{
+ URL: e.URL,
+ Method: e.Method,
+ Status: e.Status,
+ StatusText: e.StatusText,
+ ResourceType: e.ResourceType,
+ MimeType: e.MimeType,
+ StartTime: e.StartTime,
+ Duration: e.Duration,
+ Size: e.Size,
+ Failed: e.Failed || e.Status >= 400,
+ Error: e.Error,
+ })
+ }
+ return out
+}
+
+// MapBrokenAssets converts observe broken-asset entries to the audit schema.
+func MapBrokenAssets(assets []observe.BrokenAsset) []BrokenAsset {
+ out := make([]BrokenAsset, 0, len(assets))
+ for _, a := range assets {
+ out = append(out, BrokenAsset{
+ URL: a.URL,
+ ResourceType: a.ResourceType,
+ Status: a.StatusCode,
+ Error: a.Error,
+ })
+ }
+ return out
+}
+
+// MapInteractiveElements extracts the visible interactive elements from a
+// full accessibility snapshot.
+func MapInteractiveElements(nodes []observe.A11yNode) []InteractiveElement {
+ out := make([]InteractiveElement, 0)
+ for _, n := range nodes {
+ if n.Hidden || !observe.InteractiveRoles[n.Role] {
+ continue
+ }
+ out = append(out, InteractiveElement{
+ Ref: n.Ref,
+ Role: n.Role,
+ Name: n.Name,
+ Tag: n.Tag,
+ Label: n.Label,
+ Disabled: n.Disabled,
+ Visible: !n.Hidden,
+ })
+ }
+ return out
+}
+
+// MapTimingMetrics converts observe timing metrics to the audit schema.
+func MapTimingMetrics(t observe.TimingMetrics) BrowserTimingMetrics {
+ return BrowserTimingMetrics{
+ TimeToFirstByte: t.TTFBMs,
+ DOMContentLoaded: t.DOMContentLoadedMs,
+ Load: t.LoadMs,
+ FirstContentfulPaint: t.FCPMs,
+ LargestContentfulPaint: t.LCPMs,
+ CumulativeLayoutShift: t.CLS,
+ }
+}
diff --git a/internal/audit/enrich_test.go b/internal/audit/enrich_test.go
new file mode 100644
index 00000000..a61819d5
--- /dev/null
+++ b/internal/audit/enrich_test.go
@@ -0,0 +1,172 @@
+package audit
+
+import (
+ "encoding/json"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/bridge/observe"
+)
+
+var enrichTS = time.Date(2026, 7, 4, 10, 0, 0, 0, time.UTC)
+
+func fullCollectors() Collectors {
+ return Collectors{
+ Title: func() (string, error) { return "Fixture", nil },
+ Screenshot: func() ([]byte, error) { return []byte{0x89, 0x50}, nil },
+ Console: func() ([]bridge.LogEntry, error) {
+ return []bridge.LogEntry{{Timestamp: enrichTS, Level: "error", Message: "boom", Source: "app.js"}}, nil
+ },
+ Network: func() ([]observe.NetworkEntry, error) {
+ return []observe.NetworkEntry{
+ {URL: "http://fixtures/page.html", Method: "GET", Status: 200, ResourceType: "Document", Finished: true},
+ {URL: "http://fixtures/missing.png", Method: "GET", Status: 404, ResourceType: "Image", Finished: true},
+ }, nil
+ },
+ Snapshot: func() ([]observe.A11yNode, error) {
+ return []observe.A11yNode{
+ {Ref: "e1", Role: "link", Name: "Home", Tag: "a"},
+ {Ref: "e2", Role: "image"},
+ {Role: "paragraph", Name: "text"},
+ {Ref: "e3", Role: "button", Name: "Hidden", Hidden: true},
+ }, nil
+ },
+ PageFacts: func() (PageFacts, error) {
+ return PageFacts{Title: "Fixture", Lang: "en", HeadingLevels: []int{1}}, nil
+ },
+ Timing: func() (*observe.TimingMetrics, error) {
+ return &observe.TimingMetrics{TTFBMs: 5, LoadMs: 120, FCPMs: 40, LCPMs: 80, CLS: 0.01, DOMContentLoadedMs: 90}, nil
+ },
+ }
+}
+
+func TestEnrichPageAllCollectors(t *testing.T) {
+ pa := EnrichPage("http://fixtures/page.html", DefaultPageOptions(), fullCollectors())
+ if pa.Error != "" {
+ t.Fatalf("Error = %q, want empty", pa.Error)
+ }
+ if pa.Title != "Fixture" {
+ t.Errorf("Title = %q", pa.Title)
+ }
+ if len(pa.ConsoleLogs) != 1 || pa.ConsoleLogs[0].Level != "error" {
+ t.Errorf("ConsoleLogs = %+v", pa.ConsoleLogs)
+ }
+ if len(pa.NetworkRequests) != 2 {
+ t.Errorf("NetworkRequests = %+v", pa.NetworkRequests)
+ }
+ if len(pa.BrokenAssets) != 1 || pa.BrokenAssets[0].URL != "http://fixtures/missing.png" || pa.BrokenAssets[0].Status != 404 {
+ t.Errorf("BrokenAssets = %+v", pa.BrokenAssets)
+ }
+ if len(pa.InteractiveElements) != 1 || pa.InteractiveElements[0].Ref != "e1" {
+ t.Errorf("InteractiveElements = %+v (want only the visible link)", pa.InteractiveElements)
+ }
+ if pa.AccessibilityScore != 90 {
+ t.Errorf("AccessibilityScore = %d, want 90 (one missing-alt)", pa.AccessibilityScore)
+ }
+ if len(pa.A11yFindings) != 1 || pa.A11yFindings[0].Rule != "missing-alt" {
+ t.Errorf("A11yFindings = %+v", pa.A11yFindings)
+ }
+ if pa.TimingMetrics.Load != 120 || pa.TimingMetrics.TimeToFirstByte != 5 {
+ t.Errorf("TimingMetrics = %+v", pa.TimingMetrics)
+ }
+ if pa.Screenshot == "" {
+ t.Error("Screenshot should be populated")
+ }
+}
+
+func TestEnrichPageOptionToggles(t *testing.T) {
+ opts := DefaultPageOptions()
+ opts.Screenshot = false
+ opts.Network = false
+ pa := EnrichPage("http://fixtures/page.html", opts, fullCollectors())
+ if pa.Screenshot != "" {
+ t.Error("Screenshot should be empty when disabled")
+ }
+ if len(pa.NetworkRequests) != 0 {
+ t.Errorf("NetworkRequests = %+v, want none", pa.NetworkRequests)
+ }
+ if len(pa.BrokenAssets) != 0 {
+ t.Errorf("BrokenAssets = %+v, want none", pa.BrokenAssets)
+ }
+
+ data, err := json.Marshal(pa)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ var fields map[string]any
+ _ = json.Unmarshal(data, &fields)
+ for _, absent := range []string{"screenshot", "networkRequests", "brokenAssets"} {
+ if _, ok := fields[absent]; ok {
+ t.Errorf("field %q should be omitted when disabled", absent)
+ }
+ }
+}
+
+func TestEnrichPageCollectorFailureIsData(t *testing.T) {
+ c := fullCollectors()
+ c.Timing = func() (*observe.TimingMetrics, error) { return nil, errors.New("timing exploded") }
+ pa := EnrichPage("http://fixtures/page.html", DefaultPageOptions(), c)
+ if !strings.Contains(pa.Error, "timing: timing exploded") {
+ t.Errorf("Error = %q, want timing failure recorded", pa.Error)
+ }
+ if len(pa.ConsoleLogs) != 1 {
+ t.Error("other collectors should still populate")
+ }
+}
+
+func TestNewPageAuditError(t *testing.T) {
+ pa := NewPageAuditError("http://down.invalid/", errors.New("connection refused"))
+ if pa.URL != "http://down.invalid/" || pa.Error != "connection refused" {
+ t.Errorf("PageAudit = %+v", pa)
+ }
+ data, _ := json.Marshal(pa)
+ var fields map[string]any
+ _ = json.Unmarshal(data, &fields)
+ if fields["error"] != "connection refused" {
+ t.Errorf("error JSON field = %v", fields["error"])
+ }
+}
+
+func TestMapConsoleLogs(t *testing.T) {
+ got := MapConsoleLogs([]bridge.LogEntry{{Timestamp: enrichTS, Level: "warn", Message: "careful", Source: "s"}})
+ want := []ConsoleLogEntry{{Timestamp: enrichTS, Level: "warn", Message: "careful", Source: "s"}}
+ if len(got) != 1 || got[0] != want[0] {
+ t.Errorf("MapConsoleLogs = %+v, want %+v", got, want)
+ }
+}
+
+func TestMapNetworkRequestsMarksHTTPErrorsFailed(t *testing.T) {
+ got := MapNetworkRequests([]observe.NetworkEntry{
+ {URL: "a", Status: 200, Finished: true},
+ {URL: "b", Status: 500, Finished: true},
+ {URL: "c", Failed: true, Error: "net::ERR_FAILED"},
+ })
+ if got[0].Failed || !got[1].Failed || !got[2].Failed {
+ t.Errorf("Failed flags = %v %v %v", got[0].Failed, got[1].Failed, got[2].Failed)
+ }
+ if got[2].Error != "net::ERR_FAILED" {
+ t.Errorf("Error = %q", got[2].Error)
+ }
+}
+
+func TestMapInteractiveElementsFiltersRolesAndHidden(t *testing.T) {
+ got := MapInteractiveElements([]observe.A11yNode{
+ {Ref: "e1", Role: "button", Name: "Go"},
+ {Ref: "e2", Role: "paragraph", Name: "text"},
+ {Ref: "e3", Role: "link", Name: "x", Hidden: true},
+ })
+ if len(got) != 1 || got[0].Ref != "e1" || !got[0].Visible {
+ t.Errorf("MapInteractiveElements = %+v", got)
+ }
+}
+
+func TestMapTimingMetrics(t *testing.T) {
+ got := MapTimingMetrics(observe.TimingMetrics{TTFBMs: 1, FCPMs: 2, LCPMs: 3, CLS: 0.4, DOMContentLoadedMs: 5, LoadMs: 6})
+ want := BrowserTimingMetrics{TimeToFirstByte: 1, FirstContentfulPaint: 2, LargestContentfulPaint: 3, CumulativeLayoutShift: 0.4, DOMContentLoaded: 5, Load: 6}
+ if got != want {
+ t.Errorf("MapTimingMetrics = %+v, want %+v", got, want)
+ }
+}
diff --git a/internal/audit/types.go b/internal/audit/types.go
index 54cb3fc9..5976976d 100644
--- a/internal/audit/types.go
+++ b/internal/audit/types.go
@@ -84,20 +84,21 @@ type InteractiveElement struct {
}
// BrowserTimingMetrics holds browser-level performance timings for a page,
-// in milliseconds unless noted otherwise.
+// in milliseconds unless noted otherwise. JSON field names match the
+// GET /timing endpoint.
type BrowserTimingMetrics struct {
// TimeToFirstByte is the navigation time-to-first-byte.
- TimeToFirstByte float64 `json:"timeToFirstByte,omitempty"`
+ TimeToFirstByte float64 `json:"ttfbMs,omitempty"`
// DOMContentLoaded is the DOMContentLoaded event time.
- DOMContentLoaded float64 `json:"domContentLoaded,omitempty"`
+ DOMContentLoaded float64 `json:"domContentLoadedMs,omitempty"`
// Load is the load event time.
- Load float64 `json:"load,omitempty"`
+ Load float64 `json:"loadMs,omitempty"`
// FirstContentfulPaint is the FCP Core Web Vital.
- FirstContentfulPaint float64 `json:"firstContentfulPaint,omitempty"`
+ FirstContentfulPaint float64 `json:"fcpMs,omitempty"`
// LargestContentfulPaint is the LCP Core Web Vital.
- LargestContentfulPaint float64 `json:"largestContentfulPaint,omitempty"`
+ LargestContentfulPaint float64 `json:"lcpMs,omitempty"`
// CumulativeLayoutShift is the CLS Core Web Vital (unitless score).
- CumulativeLayoutShift float64 `json:"cumulativeLayoutShift,omitempty"`
+ CumulativeLayoutShift float64 `json:"cls,omitempty"`
}
// VisualDiffResult is the outcome of comparing a page screenshot against a
diff --git a/internal/bridge/observe/timing.go b/internal/bridge/observe/timing.go
index 45b554d5..80fa0433 100644
--- a/internal/bridge/observe/timing.go
+++ b/internal/bridge/observe/timing.go
@@ -36,6 +36,15 @@ const TimingScript = `(() => {
const whenLoaded = document.readyState === 'complete'
? Promise.resolve()
: new Promise((resolve) => window.addEventListener('load', resolve, { once: true }));
+ const whenLoadTimed = () => new Promise((resolve) => {
+ const started = performance.now();
+ const check = () => {
+ const nav = performance.getEntriesByType('navigation')[0];
+ if ((nav && nav.loadEventEnd > 0) || performance.now() - started > 2000) resolve();
+ else setTimeout(check, 50);
+ };
+ check();
+ });
const whenPainted = () => new Promise((resolve) => {
try {
const po = new PerformanceObserver(() => { po.disconnect(); resolve(); });
@@ -52,6 +61,7 @@ const TimingScript = `(() => {
} catch (err) { resolve(entries); }
});
return whenLoaded
+ .then(whenLoadTimed)
.then(whenPainted)
.then(() => new Promise((resolve) => setTimeout(resolve, 60)))
.then(() => Promise.all([collect('largest-contentful-paint'), collect('layout-shift')]))
diff --git a/internal/handlers/audit_page.go b/internal/handlers/audit_page.go
new file mode 100644
index 00000000..6627ed77
--- /dev/null
+++ b/internal/handlers/audit_page.go
@@ -0,0 +1,186 @@
+package handlers
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/audit"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/bridge/observe"
+ "github.com/pinchtab/pinchtab/internal/httpx"
+)
+
+const auditCollectTimeout = 60 * time.Second
+
+type auditPageRequest struct {
+ URL string `json:"url"`
+ Options *struct {
+ Screenshot *bool `json:"screenshot"`
+ Network *bool `json:"network"`
+ Console *bool `json:"console"`
+ A11y *bool `json:"a11y"`
+ Timing *bool `json:"timing"`
+ Elements *bool `json:"elements"`
+ } `json:"options"`
+}
+
+func (req auditPageRequest) pageOptions() audit.PageOptions {
+ opts := audit.DefaultPageOptions()
+ if req.Options == nil {
+ return opts
+ }
+ apply := func(dst *bool, src *bool) {
+ if src != nil {
+ *dst = *src
+ }
+ }
+ apply(&opts.Screenshot, req.Options.Screenshot)
+ apply(&opts.Network, req.Options.Network)
+ apply(&opts.Console, req.Options.Console)
+ apply(&opts.A11y, req.Options.A11y)
+ apply(&opts.Timing, req.Options.Timing)
+ apply(&opts.Elements, req.Options.Elements)
+ return opts
+}
+
+// @Endpoint POST /audit/page
+func (h *Handlers) HandleAuditPage(w http.ResponseWriter, r *http.Request) {
+ var req auditPageRequest
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
+ req.URL = strings.TrimSpace(req.URL)
+ if req.URL == "" {
+ httpx.Error(w, 400, fmt.Errorf("url required"))
+ return
+ }
+
+ routing, ok := h.resolveNavigateBrowser(w, r, "", "")
+ if !ok {
+ return
+ }
+ targets, ok := h.validateNavigateTargets(w, r, "", req.URL, routing.EffectiveCfg)
+ if !ok {
+ return
+ }
+ if !h.ensureBrowserOrRespond(w, routing.EffectiveCfg) {
+ return
+ }
+
+ tabID, tabCtx, _, err := h.Bridge.CreateTab("")
+ if err != nil {
+ httpx.Error(w, 500, fmt.Errorf("new tab: %w", err))
+ return
+ }
+ defer func() { _ = h.Bridge.CloseTab(tabID) }()
+
+ navTimeout := routing.EffectiveCfg.NavigateTimeout
+ if navTimeout <= 0 {
+ navTimeout = 30 * time.Second
+ }
+ navCtx, navCancel := context.WithTimeout(tabCtx, navTimeout)
+ defer navCancel()
+
+ navGuard, err := installNavigateRuntimeGuardWithBridge(h.Bridge, navCtx, navCancel, targets.target, targets.trustedCIDRs)
+ if err != nil {
+ httpx.Error(w, 500, fmt.Errorf("navigation guard: %w", err))
+ return
+ }
+
+ // Per-page failures are data, not crashes: navigation errors come back
+ // as a structured entry with the error field set, never a 5xx.
+ if _, navErr := h.Bridge.Navigate(navCtx, req.URL, bridge.NavigateParams{MaxRedirects: routing.EffectiveCfg.MaxRedirects}); navErr != nil {
+ if navGuard != nil {
+ if blockedErr := navGuard.blocked(); blockedErr != nil {
+ navErr = blockedErr
+ }
+ }
+ httpx.JSON(w, 200, audit.NewPageAuditError(req.URL, navErr))
+ return
+ }
+
+ // Chrome renders net-level failures (connection refused, DNS) as an
+ // error page without failing the navigation; detect it and report the
+ // underlying net error from the network capture as page data.
+ if cur, urlErr := h.Bridge.CurrentURL(navCtx); urlErr == nil && strings.HasPrefix(cur, "chrome-error://") {
+ httpx.JSON(w, 200, audit.NewPageAuditError(req.URL, h.documentNetError(tabID, req.URL)))
+ return
+ }
+
+ // Paint metrics only fire on visible pages.
+ _ = h.Bridge.FocusTab(tabID)
+
+ cCtx, cCancel := context.WithTimeout(tabCtx, auditCollectTimeout)
+ defer cCancel()
+ go httpx.CancelOnClientDone(r.Context(), cCancel)
+
+ // Let late subresources (async fetches, images) land before collecting.
+ _, _ = observe.WaitForQuietWindow(cCtx, 500*time.Millisecond, 5*time.Second)
+
+ pageAudit := audit.EnrichPage(req.URL, req.pageOptions(), h.auditCollectors(cCtx, tabID))
+ httpx.JSON(w, 200, pageAudit)
+}
+
+// documentNetError recovers the document request's net error from the
+// network capture, falling back to a generic message.
+func (h *Handlers) documentNetError(tabID, url string) error {
+ if nm := h.Bridge.NetworkMonitor(); nm != nil {
+ if buf := nm.GetBuffer(tabID); buf != nil {
+ for _, e := range buf.List(bridge.NetworkFilter{}) {
+ if e.URL == url && e.Failed && e.Error != "" {
+ return fmt.Errorf("navigation failed: %s", e.Error)
+ }
+ }
+ }
+ }
+ return fmt.Errorf("navigation failed: %s could not be loaded", url)
+}
+
+// auditCollectors wires the audit collectors to this tab's bridge data.
+func (h *Handlers) auditCollectors(tCtx context.Context, tabID string) audit.Collectors {
+ return audit.Collectors{
+ Title: func() (string, error) {
+ return h.Bridge.CurrentTitle(tCtx)
+ },
+ Screenshot: func() ([]byte, error) {
+ return h.Bridge.CaptureScreenshot(tCtx, "png", 0, nil)
+ },
+ Console: func() ([]bridge.LogEntry, error) {
+ return h.Bridge.GetConsoleLogs(tabID, 0), nil
+ },
+ Network: func() ([]observe.NetworkEntry, error) {
+ nm := h.Bridge.NetworkMonitor()
+ if nm == nil {
+ return nil, nil
+ }
+ buf := nm.GetBuffer(tabID)
+ if buf == nil {
+ return nil, nil
+ }
+ return buf.List(bridge.NetworkFilter{}), nil
+ },
+ Snapshot: func() ([]observe.A11yNode, error) {
+ rawNodes, err := bridge.FetchAXTree(tCtx)
+ if err != nil {
+ return nil, err
+ }
+ nodes, _ := bridge.BuildSnapshot(rawNodes, "", -1)
+ return nodes, nil
+ },
+ PageFacts: func() (audit.PageFacts, error) {
+ var facts audit.PageFacts
+ err := h.Bridge.Evaluate(tCtx, audit.PageFactsScript, &facts, bridge.EvalOpts{})
+ return facts, err
+ },
+ Timing: func() (*observe.TimingMetrics, error) {
+ return observe.CollectTiming(func(expression string, result any) error {
+ return h.Bridge.Evaluate(tCtx, expression, result, bridge.EvalOpts{AwaitPromise: true})
+ })
+ },
+ }
+}
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index 46be76d2..efef1762 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -322,6 +322,7 @@ func (h *Handlers) bridgeBindings() []routeBinding {
{pattern: "GET /metrics", root: h.HandleMetrics, tab: h.HandleTabMetrics},
{pattern: "GET /timing", root: h.HandleTiming, tab: h.HandleTabTiming},
{pattern: "GET /a11y/audit", root: h.HandleA11yAudit, tab: h.HandleTabA11yAudit},
+ {pattern: "POST /audit/page", root: h.HandleAuditPage},
{pattern: "GET /network", root: h.HandleNetwork, tab: h.HandleTabNetwork},
{pattern: "GET /network/stream", root: h.HandleNetworkStream, tab: h.HandleTabNetworkStream},
{pattern: "GET /network/export", root: h.HandleNetworkExport, tab: h.HandleTabNetworkExport},
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 9f88bb33..845386c8 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -124,6 +124,7 @@ var coreEndpoints = []Endpoint{
{"GET", "/metrics", "Runtime metrics", CapNone, true},
{"GET", "/timing", "Page timing and Core Web Vitals", CapNone, true},
{"GET", "/a11y/audit", "Accessibility findings and score", CapNone, true},
+ {"POST", "/audit/page", "Audit a single page with browser enrichment", CapNone, false},
{"GET", "/network", "Network log", CapNone, true},
{"GET", "/network/stream", "Network SSE stream", CapNone, true},
diff --git a/tests/e2e/scenarios/api/audit-page-basic.sh b/tests/e2e/scenarios/api/audit-page-basic.sh
new file mode 100755
index 00000000..d90eeb89
--- /dev/null
+++ b/tests/e2e/scenarios/api/audit-page-basic.sh
@@ -0,0 +1,109 @@
+#!/bin/bash
+# audit-page-basic.sh — POST /audit/page single-page browser enrichment.
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../../helpers/api.sh"
+
+# ─────────────────────────────────────────────────────────────────
+start_test "broken-assets page: broken entries and network requests"
+
+pt_post /audit/page -d "{\"url\":\"${FIXTURES_URL}/audit-site/broken-assets.html\"}"
+assert_ok "audit broken-assets.html"
+assert_json_length "$RESULT" '.brokenAssets' 4 "4 broken entries (3 assets + fetch)"
+assert_json_length_gte "$RESULT" '.networkRequests' 1 "non-empty networkRequests"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "console-errors page: error and warning console entries"
+
+pt_post /audit/page -d "{\"url\":\"${FIXTURES_URL}/audit-site/console-errors.html\"}"
+assert_ok "audit console-errors.html"
+
+for level in error warning; do
+ if echo "$RESULT" | jq -e --arg level "$level" '.consoleLogs[] | select(.level == $level)' >/dev/null 2>&1; then
+ pass_assert "consoleLogs contain a $level entry"
+ else
+ fail_assert "consoleLogs contain a $level entry (got: $(echo "$RESULT" | jq -c '[.consoleLogs[]?.level]'))"
+ fi
+done
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "a11y-issues page: accessibility score below 100"
+
+pt_post /audit/page -d "{\"url\":\"${FIXTURES_URL}/audit-site/a11y-issues.html\"}"
+assert_ok "audit a11y-issues.html"
+
+SCORE=$(echo "$RESULT" | jq '.accessibilityScore')
+if [ "$SCORE" -lt 100 ] 2>/dev/null; then
+ pass_assert "accessibilityScore < 100 (got: $SCORE)"
+else
+ fail_assert "accessibilityScore < 100 (got: $SCORE)"
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "clean page: full collector set populated"
+
+pt_post /audit/page -d "{\"url\":\"${FIXTURES_URL}/audit-site/clean.html\"}"
+assert_ok "audit clean.html"
+
+BROKEN=$(echo "$RESULT" | jq '.brokenAssets | length')
+if [ "$BROKEN" -eq 0 ]; then
+ pass_assert "zero brokenAssets"
+else
+ fail_assert "zero brokenAssets (got: $BROKEN)"
+fi
+assert_json_eq "$RESULT" '.accessibilityScore' "100" "accessibility score 100"
+
+LOAD_MS=$(echo "$RESULT" | jq '.timingMetrics.loadMs')
+if echo "$RESULT" | jq -e '.timingMetrics.loadMs > 0' >/dev/null 2>&1; then
+ pass_assert "timingMetrics.loadMs > 0 (got: $LOAD_MS)"
+else
+ fail_assert "timingMetrics.loadMs > 0 (got: $LOAD_MS)"
+fi
+
+assert_json_length_gte "$RESULT" '.interactiveElements' 1 "at least one interactiveElement"
+
+SCREENSHOT_LEN=$(echo "$RESULT" | jq '.screenshot | length')
+if [ "$SCREENSHOT_LEN" -gt 0 ] 2>/dev/null; then
+ pass_assert "non-empty screenshot (${SCREENSHOT_LEN} base64 chars)"
+else
+ fail_assert "non-empty screenshot (got length: $SCREENSHOT_LEN)"
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "options toggles omit screenshot and network fields"
+
+pt_post /audit/page -d "{\"url\":\"${FIXTURES_URL}/audit-site/clean.html\",\"options\":{\"screenshot\":false,\"network\":false}}"
+assert_ok "audit with disabled collectors"
+
+for absent in screenshot networkRequests; do
+ if echo "$RESULT" | jq -e "has(\"$absent\") | not" >/dev/null 2>&1; then
+ pass_assert "$absent omitted"
+ else
+ fail_assert "$absent omitted (got: $(echo "$RESULT" | jq -c ".$absent | length"))"
+ fi
+done
+
+assert_json_eq "$RESULT" '.accessibilityScore' "100" "other collectors still run"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "unreachable URL: structured error entry, server healthy"
+
+pt_post /audit/page -d "{\"url\":\"http://fixtures:9/unreachable.html\"}"
+assert_ok "audit unreachable URL returns 200"
+assert_json_exists "$RESULT" '.error' "has error field"
+assert_json_contains "$RESULT" '.url' "http://fixtures:9/unreachable.html" "echoes the url"
+
+pt_get /health
+assert_ok "server healthy after failed audit"
+
+end_test