Skip to content

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

feat: add site scrape with preview and expand modes

Luigi Agosti75ac1ad20369
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
index f7a38984..1f8eee02 100644
--- a/cmd/pinchtab/cmd_cli_register.go
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -25,7 +25,7 @@ func browserRootCommands() []*cobra.Command {
downloadCmd, uploadCmd, findCmd, selectCmd, checkCmd, uncheckCmd, networkCmd, waitCmd,
keyboardCmd, keydownCmd, keyupCmd, scrollintoviewCmd, dialogCmd, consoleCmd, errorsCmd,
clipboardCmd, cacheCmd, cookiesCmd, setCmd, storageCmd, stateCmd, closeCmd, handoffCmd,
- resumeCmd, handoffStatusCmd, recordCmd, auditCmd, compareCmd,
+ resumeCmd, handoffStatusCmd, recordCmd, auditCmd, compareCmd, scrapeCmd,
}
}
@@ -369,6 +369,23 @@ func configureBrowserFlags() {
auditCmd.Flags().String("cookies-file", "", "Inject cookies from a JSON array of {name, value, domain, ...} objects")
auditCmd.Flags().String("profile", "", "Run against the instance of this browser profile")
+ scrapeCmd.Flags().Int("max-pages", 0, "Maximum pages sampled across the site (default 50)")
+ scrapeCmd.Flags().Int("max-per-pattern", 0, "Maximum pages sampled per URL pattern group (default 8)")
+ scrapeCmd.Flags().StringArray("include", nil, "Only crawl URLs matching this regex (repeatable)")
+ scrapeCmd.Flags().StringArray("exclude", nil, "Skip URLs matching this regex (repeatable)")
+ scrapeCmd.Flags().Int("concurrency", 0, "Pages browser-rendered in parallel (default 2, max 8)")
+ scrapeCmd.Flags().Bool("enrich-all", false, "Browser-render every reachable page, ignoring routing")
+ scrapeCmd.Flags().Bool("no-browser", false, "HTTP crawl only; record routing verdicts without browser rendering")
+ scrapeCmd.Flags().Bool("preview", false, "Outline only: page tree, sizes, and snippets, no browser rendering or full bodies — survey a large site before expanding")
+ scrapeCmd.Flags().StringArray("only", nil, "Expand exactly these URLs at full fidelity instead of crawling (repeatable; drill down after --preview)")
+ scrapeCmd.Flags().Int("timeout", 0, "Overall HTTP crawl timeout in seconds (default 60)")
+ scrapeCmd.Flags().Bool("json", false, "Print the full report JSON to stdout")
+ scrapeCmd.Flags().String("format", "json", "Report format: json or md")
+ scrapeCmd.Flags().String("output-dir", "", "Write report.json (and report.md with --format md) to this directory")
+ scrapeCmd.Flags().StringArray("cookie", nil, "Inject a cookie as name=value before the run (repeatable; the cookie jar is cleared afterwards)")
+ scrapeCmd.Flags().String("cookies-file", "", "Inject cookies from a JSON array of {name, value, domain, ...} objects")
+ scrapeCmd.Flags().String("profile", "", "Run against the instance of this browser profile")
+
compareCmd.Flags().String("pages", "", "Comma-separated relative paths to compare (default: the base URLs)")
compareCmd.Flags().Bool("visual-diff", true, "Capture screenshots and compute visual diffs")
compareCmd.Flags().String("output-dir", "", "Write report.json and diffs/ to this directory")
diff --git a/cmd/pinchtab/cmd_scrape.go b/cmd/pinchtab/cmd_scrape.go
new file mode 100644
index 00000000..b6c71a1f
--- /dev/null
+++ b/cmd/pinchtab/cmd_scrape.go
@@ -0,0 +1,38 @@
+package main
+
+import (
+ browseractions "github.com/pinchtab/pinchtab/internal/cli/actions"
+ "github.com/spf13/cobra"
+)
+
+var scrapeCmd = &cobra.Command{
+ Use: "scrape <url>",
+ Short: "Scrape a site: HTTP crawl first, browser-render only pages that need it",
+ Long: `Scrape a whole site into a page tree with markdown content. Pages are
+discovered and extracted over plain HTTP first (via SeaPortal: sitemap or
+link crawl, URL-pattern sampling). Pages whose HTTP extraction came back
+thin, blocked, or failed are then re-rendered in the real browser (whatever
+provider the instance runs — chrome, cloak, ghost-chrome) and re-extracted
+from the rendered HTML, so JS-only content still lands in the report.
+
+Each page records its content source (http or browser) and the routing
+verdict. Pass --enrich-all to browser-render every page, or --no-browser
+for the HTTP crawl alone. With --output-dir the report is written to
+<dir>/report.json (and report.md with --format md); --json prints the full
+report to stdout.
+
+For a large site, survey it first with --preview: an outline of every page
+(title, size, snippet, routing verdict) with the full bodies withheld and no
+browser rendering, so it stays cheap to read. Then drill into the pages you
+care about at full fidelity with --only <url> (repeatable), which scrapes
+exactly those URLs instead of crawling.
+
+Pages that fail in both engines do not fail the run: the command still
+exits 0 and the failing page's report entry carries an "error" field.`,
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Scrape(rt.client, rt.base, rt.token, cmd, args[0])
+ })
+ },
+}
diff --git a/internal/audit/seaportal.go b/internal/audit/seaportal.go
index aa5848f1..9b042b7b 100644
--- a/internal/audit/seaportal.go
+++ b/internal/audit/seaportal.go
@@ -56,10 +56,13 @@ func ParseSeaportalReport(data []byte) ([]SeaportalPage, error) {
}
// FlattenSitemapURLs discovers page URLs from a sitemap (recursively for
-// sitemap indexes) via seaportal.FlattenSitemap.
-func FlattenSitemapURLs(ctx context.Context, sitemapURL string) ([]string, error) {
+// sitemap indexes) via seaportal.FlattenSitemap. security gates every
+// sitemap fetch — child sitemaps of an index are attacker-controlled URLs,
+// so only the root sitemap URL being pre-validated is not enough.
+func FlattenSitemapURLs(ctx context.Context, sitemapURL string, security *seaportal.SecurityPolicy) ([]string, error) {
entries, err := seaportal.FlattenSitemap(ctx, sitemapURL, seaportal.FlattenSitemapOptions{
- Timeout: 15 * time.Second,
+ Timeout: 15 * time.Second,
+ Security: security,
})
if err != nil {
return nil, err
diff --git a/internal/audit/seaportal_test.go b/internal/audit/seaportal_test.go
index 7e8dd6af..3cf08ae5 100644
--- a/internal/audit/seaportal_test.go
+++ b/internal/audit/seaportal_test.go
@@ -7,6 +7,8 @@ import (
"os"
"reflect"
"testing"
+
+ seaportal "github.com/pinchtab/seaportal"
)
func TestParseSeaportalReport(t *testing.T) {
@@ -50,7 +52,7 @@ func TestFlattenSitemapURLsAgainstFixture(t *testing.T) {
}))
defer srv.Close()
- urls, err := FlattenSitemapURLs(context.Background(), srv.URL+"/sitemap.xml")
+ urls, err := FlattenSitemapURLs(context.Background(), srv.URL+"/sitemap.xml", nil)
if err != nil {
t.Fatalf("FlattenSitemapURLs: %v", err)
}
@@ -60,6 +62,13 @@ func TestFlattenSitemapURLsAgainstFixture(t *testing.T) {
if urls[0] != "http://fixtures/audit-site/index.html" {
t.Errorf("first url = %q", urls[0])
}
+
+ // The security policy gates the sitemap fetch itself: the httptest
+ // server sits on 127.0.0.1, so BlockPrivateIPs must stop the flatten.
+ if _, err := FlattenSitemapURLs(context.Background(), srv.URL+"/sitemap.xml",
+ &seaportal.SecurityPolicy{BlockPrivateIPs: true}); err == nil {
+ t.Error("blocked sitemap fetch must surface an error")
+ }
}
func TestRunAuditSeaportalRouting(t *testing.T) {
diff --git a/internal/cli/actions/actions_scrape.go b/internal/cli/actions/actions_scrape.go
new file mode 100644
index 00000000..dabd321f
--- /dev/null
+++ b/internal/cli/actions/actions_scrape.go
@@ -0,0 +1,153 @@
+package actions
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
+ "github.com/pinchtab/pinchtab/internal/scrape"
+ "github.com/spf13/cobra"
+)
+
+// scrapeTimeout bounds a whole site scrape: the HTTP crawl plus every
+// browser-rendered page, well above the default per-request client timeout.
+const scrapeTimeout = 15 * time.Minute
+
+const scrapeFormatMarkdown = "md"
+
+// Scrape runs a site scrape via POST /scrape and prints or writes the report.
+func Scrape(client *http.Client, base, token string, cmd *cobra.Command, target string) {
+ format := renderFormat(cmd)
+ if format != "json" && format != scrapeFormatMarkdown {
+ fmt.Fprintf(os.Stderr, "unsupported --format %q (json or md)\n", format)
+ os.Exit(1)
+ }
+
+ base, cleanupCookies := applyRunAuth(client, base, token, cmd, target)
+
+ body := map[string]any{"url": target}
+ if v, _ := cmd.Flags().GetInt("max-pages"); v > 0 {
+ body["maxPages"] = v
+ }
+ if v, _ := cmd.Flags().GetInt("max-per-pattern"); v > 0 {
+ body["maxPerPattern"] = v
+ }
+ if v, _ := cmd.Flags().GetStringArray("include"); len(v) > 0 {
+ body["includePatterns"] = v
+ }
+ if v, _ := cmd.Flags().GetStringArray("exclude"); len(v) > 0 {
+ body["excludePatterns"] = v
+ }
+ if v, _ := cmd.Flags().GetInt("concurrency"); v > 0 {
+ body["concurrency"] = v
+ }
+ if v, _ := cmd.Flags().GetInt("timeout"); v > 0 {
+ body["timeoutSeconds"] = v
+ }
+ if mustBool(cmd, "enrich-all") {
+ body["enrichAll"] = true
+ }
+ if mustBool(cmd, "no-browser") {
+ body["noBrowser"] = true
+ }
+ preview := mustBool(cmd, "preview")
+ if preview {
+ body["preview"] = true
+ }
+ if v, _ := cmd.Flags().GetStringArray("only"); len(v) > 0 {
+ body["only"] = v
+ }
+
+ longClient := &http.Client{Transport: client.Transport, Timeout: scrapeTimeout}
+ raw := apiclient.DoPostRaw(longClient, base, token, "/scrape", body)
+ cleanupCookies()
+
+ var report scrape.Report
+ if err := json.Unmarshal(raw, &report); err != nil {
+ fmt.Fprintf(os.Stderr, "parse scrape report: %v\n", err)
+ os.Exit(1)
+ }
+
+ if dir := mustString(cmd, "output-dir"); dir != "" {
+ if err := writeScrapeArtifacts(dir, raw, report, format); err != nil {
+ fmt.Fprintf(os.Stderr, "write artifacts: %v\n", err)
+ os.Exit(1)
+ }
+ fmt.Fprintf(os.Stderr, "report written to %s\n", filepath.Join(dir, "report.json"))
+ } else if format == scrapeFormatMarkdown {
+ fmt.Println(string(scrape.RenderMarkdown(report)))
+ return
+ }
+
+ if mustBool(cmd, "json") {
+ out, _ := json.MarshalIndent(report, "", " ")
+ fmt.Println(string(out))
+ return
+ }
+ if preview {
+ printPreviewSummary(report)
+ return
+ }
+ printScrapeSummary(report)
+}
+
+// writeScrapeArtifacts writes report.json (the server response, indented)
+// and, for --format md, the rendered report.md next to it.
+func writeScrapeArtifacts(dir string, raw []byte, report scrape.Report, format string) error {
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return err
+ }
+ var indented json.RawMessage = raw
+ if out, err := json.MarshalIndent(json.RawMessage(raw), "", " "); err == nil {
+ indented = out
+ }
+ if err := os.WriteFile(filepath.Join(dir, "report.json"), indented, 0o644); err != nil {
+ return err
+ }
+ if format == scrapeFormatMarkdown {
+ return os.WriteFile(filepath.Join(dir, "report.md"), scrape.RenderMarkdown(report), 0o644)
+ }
+ return nil
+}
+
+// printPreviewSummary prints the outline: one line per page with its size,
+// routing verdict, and a snippet, so the caller can pick pages to expand with
+// `scrape <url> --only <picked-urls>`.
+func printPreviewSummary(report scrape.Report) {
+ fmt.Printf("Preview: %d page(s) discovered of %d · pick pages to expand with --only\n",
+ len(report.Pages), report.Site.TotalDiscovered)
+ for _, p := range report.Pages {
+ verdict := ""
+ if p.BrowserRecommended {
+ verdict = " · needs browser: " + strings.Join(p.BrowserReasons, ",")
+ }
+ if p.Error != "" {
+ fmt.Printf(" %s · error: %s\n", p.URL, p.Error)
+ continue
+ }
+ fmt.Printf(" %s · %d chars%s\n", p.URL, p.CharCount, verdict)
+ if p.Snippet != "" {
+ fmt.Printf(" %s\n", p.Snippet)
+ }
+ }
+}
+
+func printScrapeSummary(report scrape.Report) {
+ fmt.Printf("Scraped %d page(s) · %d http · %d browser-rendered · %d failed\n",
+ len(report.Pages), report.Summary.HTTPPages, report.Summary.BrowserPages, report.Summary.FailedPages)
+ for _, p := range report.Pages {
+ status := "source: " + p.Source
+ if p.BrowserError != "" {
+ status += " · browser failed: " + p.BrowserError
+ }
+ if p.Error != "" {
+ status = "error: " + p.Error
+ }
+ fmt.Printf(" %s · %s\n", p.URL, status)
+ }
+}
diff --git a/internal/handlers/audit.go b/internal/handlers/audit.go
index eaff2aa7..3ed1b004 100644
--- a/internal/handlers/audit.go
+++ b/internal/handlers/audit.go
@@ -51,6 +51,9 @@ func (h *Handlers) HandleAudit(w http.ResponseWriter, r *http.Request) {
return
}
+ // A multi-page audit legitimately outlives the server's WriteTimeout.
+ httpx.ExtendWriteDeadline(w, auditRunTimeout)
+
auditor := func(url string, opts audit.PageOptions) audit.PageAudit {
targets, err := h.validateAuditTarget(url, routing.EffectiveCfg)
if err != nil {
@@ -80,12 +83,13 @@ func (h *Handlers) HandleAudit(w http.ResponseWriter, r *http.Request) {
// fetchSitemap returns a SitemapFetcher that applies the same URL/IDPI/SSRF
// validation as page navigation, then discovers pages through
-// seaportal.FlattenSitemap (recursive sitemap-index support).
+// seaportal.FlattenSitemap (recursive sitemap-index support). The crawl
+// guard also gates every child-sitemap fetch inside the flattening.
func (h *Handlers) fetchSitemap(cfg *config.RuntimeConfig) audit.SitemapFetcher {
return func(sitemapURL string) ([]string, error) {
if _, err := h.validateAuditTarget(sitemapURL, cfg); err != nil {
return nil, err
}
- return audit.FlattenSitemapURLs(context.Background(), sitemapURL)
+ return audit.FlattenSitemapURLs(context.Background(), sitemapURL, h.crawlGuard(cfg).Policy())
}
}
diff --git a/internal/handlers/audit_page.go b/internal/handlers/audit_page.go
index e7f23a5f..8984c062 100644
--- a/internal/handlers/audit_page.go
+++ b/internal/handlers/audit_page.go
@@ -16,7 +16,17 @@ import (
"github.com/pinchtab/pinchtab/internal/navguard"
)
-const auditCollectTimeout = 60 * time.Second
+const (
+ auditCollectTimeout = 60 * time.Second
+ // auditRunTimeout is how far POST /audit extends the response write
+ // deadline past the server's default WriteTimeout: a multi-page run
+ // (navigation + collectors per page, bounded concurrency) legitimately
+ // takes minutes. Matches the CLI's client-side audit timeout.
+ auditRunTimeout = 10 * time.Minute
+ // auditPageDeadline covers a single-page audit: navigation plus the
+ // collector window, with headroom.
+ auditPageDeadline = 3 * time.Minute
+)
// auditPageOptionsBody is the JSON options shape shared by POST /audit/page
// and POST /audit. Unset fields keep their defaults (all collectors on).
@@ -80,6 +90,7 @@ func (h *Handlers) HandleAuditPage(w http.ResponseWriter, r *http.Request) {
return
}
+ httpx.ExtendWriteDeadline(w, auditPageDeadline)
httpx.JSON(w, 200, h.auditPage(r.Context(), req.URL, req.Options.pageOptions(), routing.EffectiveCfg, targets))
}
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index d45c2dff..b24c6675 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -324,6 +324,7 @@ func (h *Handlers) bridgeBindings() []routeBinding {
{pattern: "GET /a11y/audit", root: h.HandleA11yAudit, tab: h.HandleTabA11yAudit},
{pattern: "POST /audit/page", root: h.HandleAuditPage},
{pattern: "POST /audit", root: h.HandleAudit},
+ {pattern: "POST /scrape", root: h.HandleScrape},
{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/handlers/scrape.go b/internal/handlers/scrape.go
new file mode 100644
index 00000000..5c2d8b6d
--- /dev/null
+++ b/internal/handlers/scrape.go
@@ -0,0 +1,190 @@
+package handlers
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/bridge/observe"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/httpx"
+ "github.com/pinchtab/pinchtab/internal/scrape"
+)
+
+const (
+ scrapeRenderTimeout = 60 * time.Second
+ // scrapeRunTimeout bounds a whole scrape run (HTTP crawl plus every
+ // browser-rendered page) and is how far the response write deadline is
+ // extended past the server's default WriteTimeout. Matches the CLI's
+ // client-side scrape timeout.
+ scrapeRunTimeout = 15 * time.Minute
+)
+
+type scrapeRequest struct {
+ URL string `json:"url"`
+ MaxPages int `json:"maxPages"`
+ MaxPerPattern int `json:"maxPerPattern"`
+ IncludePatterns []string `json:"includePatterns"`
+ ExcludePatterns []string `json:"excludePatterns"`
+ Concurrency int `json:"concurrency"`
+ EnrichAll bool `json:"enrichAll"`
+ NoBrowser bool `json:"noBrowser"`
+ TimeoutSeconds int `json:"timeoutSeconds"`
+ // Preview returns an outline (routing verdicts, per-page snippet and
+ // charCount) without browser rendering or full page bodies.
+ Preview bool `json:"preview"`
+ // Only, when set, expands exactly these URLs at full fidelity instead of
+ // discovering the site — the drill-down half of a preview.
+ Only []string `json:"only"`
+}
+
+// @Endpoint POST /scrape
+func (h *Handlers) HandleScrape(w http.ResponseWriter, r *http.Request) {
+ var req scrapeRequest
+ 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
+ }
+ if _, err := h.validateAuditTarget(req.URL, routing.EffectiveCfg); err != nil {
+ httpx.Error(w, 400, err)
+ return
+ }
+ for _, u := range req.Only {
+ if strings.TrimSpace(u) == "" {
+ continue
+ }
+ if _, err := h.validateAuditTarget(u, routing.EffectiveCfg); err != nil {
+ httpx.Error(w, 400, fmt.Errorf("expand target %q: %w", u, err))
+ return
+ }
+ }
+ // A preview never renders, so it needs no browser; expand and full runs do.
+ if !req.NoBrowser && !req.Preview && !h.ensureBrowserOrRespond(w, routing.EffectiveCfg) {
+ return
+ }
+
+ // A multi-page run legitimately outlives the server's WriteTimeout;
+ // extend the write deadline and bound the whole run to the same window.
+ httpx.ExtendWriteDeadline(w, scrapeRunTimeout)
+ runCtx, runCancel := context.WithTimeout(r.Context(), scrapeRunTimeout)
+ defer runCancel()
+
+ input := scrape.Input{
+ URL: req.URL,
+ MaxPages: req.MaxPages,
+ MaxPerPattern: req.MaxPerPattern,
+ IncludePatterns: req.IncludePatterns,
+ ExcludePatterns: req.ExcludePatterns,
+ }
+ guard := h.crawlGuard(routing.EffectiveCfg)
+ renderer := func(url string) (string, error) {
+ targets, err := h.validateAuditTarget(url, routing.EffectiveCfg)
+ if err != nil {
+ return "", err
+ }
+ return h.renderPageHTML(runCtx, url, routing.EffectiveCfg, targets)
+ }
+
+ // Expand a chosen URL set instead of discovering the site when --only is
+ // given; otherwise crawl from the base URL.
+ timeout := time.Duration(req.TimeoutSeconds) * time.Second
+ crawler := scrape.SiteCrawler(input, timeout, guard)
+ if len(req.Only) > 0 {
+ crawler = scrape.URLListCrawler(req.Only, timeout, guard)
+ }
+
+ report, err := scrape.Run(
+ runCtx,
+ input,
+ scrape.RunOptions{
+ Concurrency: req.Concurrency,
+ EnrichAll: req.EnrichAll,
+ NoBrowser: req.NoBrowser,
+ Preview: req.Preview,
+ },
+ crawler,
+ renderer,
+ )
+ if err != nil {
+ httpx.Error(w, 400, err)
+ return
+ }
+ httpx.JSON(w, 200, report)
+}
+
+// crawlGuard adapts this instance's navigation security stack (navguard
+// resolution checks + IDPI domain rules + trusted CIDRs) into the guard the
+// seaportal HTTP crawl applies to every fetch and redirect hop.
+func (h *Handlers) crawlGuard(cfg *config.RuntimeConfig) scrape.CrawlGuard {
+ return scrape.CrawlGuard{
+ ValidateURL: func(url string) error {
+ _, err := h.validateAuditTarget(url, cfg)
+ return err
+ },
+ TrustedResolveCIDRs: cfg.TrustedResolveCIDRs,
+ MaxRedirects: cfg.MaxRedirects,
+ }
+}
+
+// renderPageHTML navigates a fresh tab to url and returns the rendered
+// document HTML after the page settles. The same navigation guard and
+// error-page detection as auditPage apply; the tab is always closed.
+func (h *Handlers) renderPageHTML(clientCtx context.Context, url string, cfg *config.RuntimeConfig, targets navTargets) (string, error) {
+ tabID, tabCtx, _, err := h.Bridge.CreateTab("")
+ if err != nil {
+ return "", fmt.Errorf("new tab: %w", err)
+ }
+ defer func() { _ = h.Bridge.CloseTab(tabID) }()
+
+ navTimeout := cfg.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 {
+ return "", fmt.Errorf("navigation guard: %w", err)
+ }
+
+ if _, navErr := h.Bridge.Navigate(navCtx, url, bridge.NavigateParams{MaxRedirects: cfg.MaxRedirects}); navErr != nil {
+ if navGuard != nil {
+ if blockedErr := navGuard.blocked(); blockedErr != nil {
+ navErr = blockedErr
+ }
+ }
+ return "", navErr
+ }
+
+ if cur, urlErr := h.Bridge.CurrentURL(navCtx); urlErr == nil && strings.HasPrefix(cur, "chrome-error://") {
+ return "", h.documentNetError(tabID, url)
+ }
+
+ cCtx, cCancel := context.WithTimeout(tabCtx, scrapeRenderTimeout)
+ defer cCancel()
+ go httpx.CancelOnClientDone(clientCtx, cCancel)
+
+ // Let JS rendering and late subresources land before reading the DOM.
+ _, _ = observe.WaitForQuietWindow(cCtx, 500*time.Millisecond, 5*time.Second)
+
+ var html string
+ if err := h.Bridge.Evaluate(cCtx, "document.documentElement.outerHTML", &html, bridge.EvalOpts{}); err != nil {
+ return "", fmt.Errorf("read rendered html: %w", err)
+ }
+ return html, nil
+}
diff --git a/internal/httpx/httpx.go b/internal/httpx/httpx.go
index 46033de1..11d27547 100644
--- a/internal/httpx/httpx.go
+++ b/internal/httpx/httpx.go
@@ -9,6 +9,7 @@ import (
"log/slog"
"net"
"net/http"
+ "time"
"github.com/pinchtab/pinchtab/internal/sanitize"
)
@@ -116,6 +117,14 @@ func CancelOnClientDone(reqCtx context.Context, cancel context.CancelFunc) {
cancel()
}
+// ExtendWriteDeadline pushes the connection's write deadline d into the
+// future so a long-running handler (multi-page audit/scrape) is not killed
+// by the server's default WriteTimeout before it can write its response.
+// Best-effort: an unsupported ResponseWriter keeps the server default.
+func ExtendWriteDeadline(w http.ResponseWriter, d time.Duration) {
+ _ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(d))
+}
+
type StatusWriter struct {
http.ResponseWriter
Code int
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 2bcb3b46..30650db1 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -126,6 +126,7 @@ var coreEndpoints = []Endpoint{
{"GET", "/a11y/audit", "Accessibility findings and score", CapNone, true},
{"POST", "/audit/page", "Audit a single page with browser enrichment", CapNone, false},
{"POST", "/audit", "Run a multi-page site audit", CapNone, false},
+ {"POST", "/scrape", "Scrape a site: HTTP crawl plus browser enrichment", CapNone, false},
{"GET", "/network", "Network log", CapNone, true},
{"GET", "/network/stream", "Network SSE stream", CapNone, true},
diff --git a/internal/scrape/render.go b/internal/scrape/render.go
new file mode 100644
index 00000000..3f24ba59
--- /dev/null
+++ b/internal/scrape/render.go
@@ -0,0 +1,70 @@
+package scrape
+
+import (
+ "fmt"
+ "strings"
+)
+
+// RenderMarkdown renders the report as a single Markdown digest: site
+// overview, the page tree by URL pattern, then each page's content.
+func RenderMarkdown(r Report) []byte {
+ var b strings.Builder
+ title := r.Site.Title
+ if title == "" {
+ title = r.Site.BaseURL
+ }
+ fmt.Fprintf(&b, "# Scrape Report — %s\n\n", title)
+ fmt.Fprintf(&b, "- Base URL: %s\n", r.Site.BaseURL)
+ fmt.Fprintf(&b, "- Pages: %d sampled of %d discovered\n", r.Site.SampledPages, r.Site.TotalDiscovered)
+ fmt.Fprintf(&b, "- Sources: %d http · %d browser-rendered · %d failed\n",
+ r.Summary.HTTPPages, r.Summary.BrowserPages, r.Summary.FailedPages)
+ fmt.Fprintf(&b, "- Generated: %s\n\n", r.GeneratedAt.Format("2006-01-02 15:04:05 UTC"))
+
+ if len(r.Summary.Recommendations) > 0 {
+ b.WriteString("## Recommendations\n\n")
+ for _, rec := range r.Summary.Recommendations {
+ fmt.Fprintf(&b, "- %s\n", rec)
+ }
+ b.WriteString("\n")
+ }
+
+ if len(r.PageGroups) > 0 {
+ b.WriteString("## Page Tree\n\n")
+ for _, g := range r.PageGroups {
+ fmt.Fprintf(&b, "- `%s` (%d sampled of %d)\n", g.Pattern, g.Sampled, g.Total)
+ for _, u := range g.URLs {
+ fmt.Fprintf(&b, " - %s\n", u)
+ }
+ }
+ b.WriteString("\n")
+ }
+
+ b.WriteString("## Pages\n\n")
+ for _, p := range r.Pages {
+ heading := p.Title
+ if heading == "" {
+ heading = p.URL
+ }
+ fmt.Fprintf(&b, "### %s\n\n", heading)
+ fmt.Fprintf(&b, "%s · source: %s", p.URL, p.Source)
+ if p.StatusCode != 0 {
+ fmt.Fprintf(&b, " · status: %d", p.StatusCode)
+ }
+ b.WriteString("\n\n")
+ if p.Error != "" {
+ fmt.Fprintf(&b, "> Failed: %s\n\n", p.Error)
+ continue
+ }
+ if p.BrowserError != "" {
+ fmt.Fprintf(&b, "> Browser enrichment failed (HTTP content kept): %s\n\n", p.BrowserError)
+ }
+ if md := strings.TrimSpace(p.Markdown); md != "" {
+ b.WriteString(md)
+ b.WriteString("\n\n")
+ } else if p.Snippet != "" {
+ // Preview: the body was withheld — show its size and a snippet.
+ fmt.Fprintf(&b, "_Preview · %d chars_\n\n> %s\n\n", p.CharCount, p.Snippet)
+ }
+ }
+ return []byte(b.String())
+}
diff --git a/internal/scrape/run.go b/internal/scrape/run.go
new file mode 100644
index 00000000..9f3ef9ac
--- /dev/null
+++ b/internal/scrape/run.go
@@ -0,0 +1,389 @@
+package scrape
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+ "unicode/utf8"
+
+ seaportal "github.com/pinchtab/seaportal"
+)
+
+// DefaultConcurrency is the number of pages browser-rendered in parallel
+// when the caller does not choose one; MaxConcurrency caps what a caller may
+// request (each worker drives its own browser tab).
+const (
+ DefaultConcurrency = 2
+ MaxConcurrency = 8
+)
+
+// MinContentChars mirrors seaportal's static-ok confidence threshold: an
+// HTTP extraction shorter than this is treated as a probable JS shell and
+// the page is routed to the browser.
+const MinContentChars = 500
+
+// Crawler produces the seaportal site crawl for Run. Isolated behind a
+// function type so tests can fake the crawl and handlers can bake in
+// timeouts without Run knowing about seaportal options.
+type Crawler func(ctx context.Context) (*seaportal.ScrapeResult, error)
+
+// BrowserRenderer returns the rendered HTML for url from a real browser
+// tab. Failures come back as errors and are recorded per page, never
+// aborting the run.
+type BrowserRenderer func(url string) (string, error)
+
+// RunOptions configures a scrape run.
+type RunOptions struct {
+ // Concurrency is the number of pages browser-rendered in parallel,
+ // clamped to [1, MaxConcurrency].
+ Concurrency int
+ // EnrichAll browser-renders every reachable page, overriding routing.
+ EnrichAll bool
+ // NoBrowser skips browser enrichment entirely (HTTP crawl only);
+ // routing verdicts are still recorded on each page.
+ NoBrowser bool
+ // Preview produces an outline: the HTTP crawl and routing verdicts, but
+ // no browser enrichment and no full page bodies. Each page's Markdown is
+ // withheld and replaced by CharCount plus a leading Snippet, so a caller
+ // can survey a large site cheaply and then expand chosen pages (Input.URL
+ // list) at full fidelity.
+ Preview bool
+}
+
+// SnippetChars is how many characters of a page's content the preview keeps
+// as a stand-in for the withheld body.
+const SnippetChars = 240
+
+// CrawlGuard applies pinchtab's navigation security stack to the HTTP crawl
+// so seaportal's fetches (robots.txt, sitemaps, discovered links, pages) go
+// through the same URL vetting as browser navigation.
+type CrawlGuard struct {
+ // ValidateURL is pinchtab's per-URL gate (navguard resolution checks +
+ // IDPI domain rules). It runs before every crawl fetch and on every
+ // redirect hop, and must be safe for concurrent use.
+ ValidateURL func(url string) error
+ // TrustedResolveCIDRs mirrors the runtime config escape hatch for hosts
+ // that legitimately resolve to non-public addresses.
+ TrustedResolveCIDRs []string
+ // MaxRedirects caps redirect hops when > 0; otherwise seaportal's
+ // default cap applies (a crawl never inherits "unlimited").
+ MaxRedirects int
+}
+
+// Policy renders the guard as a seaportal SecurityPolicy: the secure
+// defaults (scheme allowlist, redirect cap + per-hop revalidation, body and
+// decompression caps) with private-IP enforcement delegated to ValidateURL,
+// which owns pinchtab's richer semantics (IDPI-allowed internal domains,
+// trusted CIDRs).
+func (g CrawlGuard) Policy() *seaportal.SecurityPolicy {
+ p := seaportal.DefaultSecurityPolicy()
+ p.TrustedResolveCIDRs = g.TrustedResolveCIDRs
+ if g.MaxRedirects > 0 {
+ p.MaxRedirects = g.MaxRedirects
+ }
+ if g.ValidateURL != nil {
+ p.BlockPrivateIPs = false
+ p.URLFilter = func(_ context.Context, rawURL string) error {
+ return g.ValidateURL(rawURL)
+ }
+ }
+ return p
+}
+
+// SiteCrawler is the default Crawler: seaportal.ScrapeSite over input with
+// every fetch gated by guard. timeout <= 0 keeps seaportal's default
+// overall deadline.
+func SiteCrawler(input Input, timeout time.Duration, guard CrawlGuard) Crawler {
+ return func(ctx context.Context) (*seaportal.ScrapeResult, error) {
+ opts := &seaportal.ScrapeOptions{
+ BaseURL: input.URL,
+ MaxPages: input.MaxPages,
+ MaxPerPattern: input.MaxPerPattern,
+ IncludePatterns: input.IncludePatterns,
+ ExcludePatterns: input.ExcludePatterns,
+ Timeout: timeout,
+ Security: guard.Policy(),
+ }
+ return seaportal.ScrapeSite(ctx, opts)
+ }
+}
+
+// URLListCrawler is the Crawler for expand mode: instead of discovering a
+// site, it fetches an explicit set of URLs over HTTP and extracts each, so
+// Run can route and browser-render exactly the pages a caller chose from a
+// prior preview. Every fetch goes through guard.Policy() — the same SSRF and
+// redirect protection as the crawl. Per-URL fetch failures become failed
+// pages, never aborting the run; the crawl only errors when the list is empty.
+func URLListCrawler(urls []string, timeout time.Duration, guard CrawlGuard) Crawler {
+ return func(ctx context.Context) (*seaportal.ScrapeResult, error) {
+ clean := dedupeURLs(urls)
+ if len(clean) == 0 {
+ return nil, errors.New("no urls to expand")
+ }
+ policy := guard.Policy()
+ pages := make([]seaportal.PageObject, 0, len(clean))
+ for _, u := range clean {
+ pages = append(pages, fetchOne(ctx, u, timeout, policy))
+ }
+ return &seaportal.ScrapeResult{
+ Site: seaportal.SiteInfo{BaseURL: originOf(clean[0]), TotalURLsInSitemap: len(clean)},
+ Pages: pages,
+ }, nil
+ }
+}
+
+// fetchOne HTTP-fetches url through the security policy and extracts it into
+// a PageObject. Fetch or extraction failures are recorded on the page's Error
+// so the run continues and the page can still route to the browser.
+func fetchOne(ctx context.Context, url string, timeout time.Duration, policy *seaportal.SecurityPolicy) seaportal.PageObject {
+ body, hdr, status, err := seaportal.FetchBytes(ctx, url, seaportal.FetchBytesOptions{
+ Security: policy,
+ Timeout: timeout,
+ })
+ if err != nil {
+ return seaportal.PageObject{URL: url, Status: status, Error: err.Error()}
+ }
+ r := seaportal.FromHTML(string(body), url)
+ p := seaportal.PageObject{
+ URL: url,
+ Status: status,
+ ContentType: hdr.Get("Content-Type"),
+ Title: r.Title,
+ Markdown: r.Content,
+ Error: r.Error,
+ }
+ if r.Description != "" {
+ p.Meta = map[string]string{"description": r.Description}
+ }
+ return p
+}
+
+// blockedStatuses are HTTP statuses where a real browser (with its stealth
+// and challenge handling) may succeed where a plain HTTP client was refused.
+var blockedStatuses = map[int]bool{401: true, 403: true, 407: true, 429: true, 503: true}
+
+// NeedsBrowser is the routing verdict for one HTTP-extracted page: whether
+// the browser should re-render it, and why. Not-found pages never route to
+// the browser — re-rendering a 404 cannot recover content.
+func NeedsBrowser(p Page) (bool, []string) {
+ if p.StatusCode == 404 || p.StatusCode == 410 {
+ return false, nil
+ }
+ var reasons []string
+ if p.Error != "" {
+ reasons = append(reasons, "fetch-error")
+ }
+ if blockedStatuses[p.StatusCode] {
+ reasons = append(reasons, fmt.Sprintf("blocked-status:%d", p.StatusCode))
+ }
+ if len(reasons) == 0 && len(strings.TrimSpace(p.Markdown)) < MinContentChars {
+ reasons = append(reasons, "thin-content")
+ }
+ return len(reasons) > 0, reasons
+}
+
+// Run executes the scrape pipeline: crawl the site over HTTP, route each
+// page, then browser-render the routed pages with bounded concurrency and
+// re-extract their content from the rendered HTML. Page failures are report
+// data, not errors — Run only errors when the crawl itself fails or finds
+// nothing.
+func Run(ctx context.Context, input Input, opts RunOptions, crawl Crawler, render BrowserRenderer) (Report, error) {
+ res, err := crawl(ctx)
+ if err != nil {
+ return Report{}, fmt.Errorf("site crawl: %w", err)
+ }
+ if len(res.Pages) == 0 {
+ return Report{}, errors.New("no pages discovered")
+ }
+
+ pages := make([]Page, len(res.Pages))
+ enrich := make([]bool, len(res.Pages))
+ for i, sp := range res.Pages {
+ p := fromSeaportal(sp)
+ needs, reasons := NeedsBrowser(p)
+ p.BrowserRecommended = needs
+ p.BrowserReasons = reasons
+ if opts.EnrichAll && !needs && p.StatusCode != 404 && p.StatusCode != 410 {
+ needs, p.BrowserReasons = true, []string{"enrich-all"}
+ }
+ if opts.Preview {
+ p.CharCount = utf8.RuneCountInString(p.Markdown)
+ p.Snippet = snippet(p.Markdown, SnippetChars)
+ p.Markdown = ""
+ }
+ pages[i] = p
+ enrich[i] = needs && !opts.NoBrowser && !opts.Preview && render != nil
+ }
+
+ sem := make(chan struct{}, clampConcurrency(opts.Concurrency))
+ var wg sync.WaitGroup
+ for i := range pages {
+ if !enrich[i] {
+ continue
+ }
+ wg.Add(1)
+ go func(p *Page) {
+ defer wg.Done()
+ sem <- struct{}{}
+ defer func() { <-sem }()
+ enrichPage(p, render)
+ }(&pages[i])
+ }
+ wg.Wait()
+
+ return Report{
+ SchemaVersion: SchemaVersion,
+ GeneratedAt: time.Now().UTC(),
+ Input: input,
+ Site: SiteInfo{
+ BaseURL: res.Site.BaseURL,
+ Title: res.Site.Title,
+ SitemapFound: res.Site.SitemapFound,
+ TotalDiscovered: res.Site.TotalURLsInSitemap,
+ SampledPages: len(pages),
+ },
+ PageGroups: fromSeaportalGroups(res.PageGroups),
+ Pages: pages,
+ Summary: summarize(pages, res.Summary.Recommendations),
+ }, nil
+}
+
+// enrichPage renders p in the browser and replaces its content with the
+// extraction over the rendered HTML. The HTTP extraction is kept whenever
+// the browser path fails or yields nothing.
+func enrichPage(p *Page, render BrowserRenderer) {
+ html, err := render(p.URL)
+ if err != nil {
+ p.BrowserError = err.Error()
+ return
+ }
+ r := seaportal.FromHTML(html, p.URL)
+ if r.Error != "" {
+ p.BrowserError = r.Error
+ return
+ }
+ if strings.TrimSpace(r.Content) == "" {
+ p.BrowserError = "browser extraction produced no content"
+ return
+ }
+ p.Markdown = r.Content
+ p.Source = SourceBrowser
+ // The browser reached the page and produced content, so an HTTP fetch
+ // failure no longer marks the page as failed.
+ p.Error = ""
+ if r.Title != "" {
+ p.Title = r.Title
+ }
+ if p.Meta == nil && r.Description != "" {
+ p.Meta = map[string]string{"description": r.Description}
+ }
+}
+
+func fromSeaportal(sp seaportal.PageObject) Page {
+ return Page{
+ URL: sp.URL,
+ Title: sp.Title,
+ StatusCode: sp.Status,
+ ContentType: sp.ContentType,
+ Markdown: sp.Markdown,
+ Meta: sp.Meta,
+ Schema: sp.Schema,
+ InternalLinks: sp.InternalLinks,
+ ExternalLinks: sp.ExternalLinks,
+ Source: SourceHTTP,
+ Error: sp.Error,
+ }
+}
+
+// fromSeaportalGroups keeps the site tree as URL references; page content
+// lives once in Report.Pages.
+func fromSeaportalGroups(groups []seaportal.PageGroup) []PageGroup {
+ out := make([]PageGroup, 0, len(groups))
+ for _, g := range groups {
+ urls := make([]string, 0, len(g.Pages))
+ for _, p := range g.Pages {
+ urls = append(urls, p.URL)
+ }
+ out = append(out, PageGroup{
+ Pattern: g.Pattern,
+ Total: g.TotalInSitemap,
+ Sampled: g.Sampled,
+ URLs: urls,
+ })
+ }
+ return out
+}
+
+func summarize(pages []Page, recommendations []string) Summary {
+ s := Summary{ContentTypes: map[string]int{}, Recommendations: recommendations}
+ for _, p := range pages {
+ if p.ContentType != "" {
+ s.ContentTypes[p.ContentType]++
+ }
+ switch {
+ case p.Error != "":
+ s.FailedPages++
+ case p.Source == SourceBrowser:
+ s.BrowserPages++
+ default:
+ s.HTTPPages++
+ }
+ }
+ if len(s.ContentTypes) == 0 {
+ s.ContentTypes = nil
+ }
+ return s
+}
+
+// clampConcurrency normalizes a requested concurrency into [1, MaxConcurrency].
+func clampConcurrency(n int) int {
+ switch {
+ case n < 1:
+ return DefaultConcurrency
+ case n > MaxConcurrency:
+ return MaxConcurrency
+ default:
+ return n
+ }
+}
+
+// snippet returns the first max characters of s with runs of whitespace
+// collapsed to single spaces, appending an ellipsis when it truncated.
+func snippet(s string, max int) string {
+ s = strings.Join(strings.Fields(s), " ")
+ if utf8.RuneCountInString(s) <= max {
+ return s
+ }
+ runes := []rune(s)
+ return strings.TrimSpace(string(runes[:max])) + "…"
+}
+
+// dedupeURLs trims, drops blanks, and removes duplicate URLs while keeping
+// first-seen order.
+func dedupeURLs(urls []string) []string {
+ seen := make(map[string]bool, len(urls))
+ out := make([]string, 0, len(urls))
+ for _, u := range urls {
+ u = strings.TrimSpace(u)
+ if u == "" || seen[u] {
+ continue
+ }
+ seen[u] = true
+ out = append(out, u)
+ }
+ return out
+}
+
+// originOf returns the scheme://host of a URL, or the raw string when it does
+// not parse — used only to label the expand result's base URL.
+func originOf(raw string) string {
+ u, err := url.Parse(raw)
+ if err != nil || u.Host == "" {
+ return raw
+ }
+ return u.Scheme + "://" + u.Host
+}
diff --git a/internal/scrape/run_test.go b/internal/scrape/run_test.go
new file mode 100644
index 00000000..64071123
--- /dev/null
+++ b/internal/scrape/run_test.go
@@ -0,0 +1,364 @@
+package scrape
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+ "unicode/utf8"
+
+ seaportal "github.com/pinchtab/seaportal"
+)
+
+var longMarkdown = strings.Repeat("Plenty of extracted article prose. ", 30)
+
+// renderedHTML is rich enough for seaportal's readability extraction to
+// produce non-empty markdown in enrichPage.
+const renderedHTML = `<html><head><title>Rendered Title</title></head><body><article>
+<h1>Rendered Title</h1>
+<p>This paragraph only exists after JavaScript rendered the application shell into real content.</p>
+<p>It repeats enough prose that the readability extractor keeps it as the main article body of the page.</p>
+<p>Browser rendering recovered this content where the plain HTTP fetch saw an empty root element only.</p>
+</article></body></html>`
+
+func fakeCrawl(pages ...seaportal.PageObject) Crawler {
+ return func(context.Context) (*seaportal.ScrapeResult, error) {
+ return &seaportal.ScrapeResult{
+ Site: seaportal.SiteInfo{BaseURL: "https://example.com", TotalURLsInSitemap: len(pages)},
+ Pages: pages,
+ PageGroups: []seaportal.PageGroup{
+ {Pattern: "/*", TotalInSitemap: len(pages), Sampled: len(pages), Pages: pages},
+ },
+ }, nil
+ }
+}
+
+func TestNeedsBrowser(t *testing.T) {
+ tests := []struct {
+ name string
+ page Page
+ want bool
+ reason string
+ }{
+ {"rich static page", Page{StatusCode: 200, Markdown: longMarkdown}, false, ""},
+ {"thin spa shell", Page{StatusCode: 200, Markdown: "Loading…"}, true, "thin-content"},
+ {"fetch error", Page{Error: "tls handshake failure", Markdown: longMarkdown}, true, "fetch-error"},
+ {"blocked status", Page{StatusCode: 403, Markdown: longMarkdown}, true, "blocked-status:403"},
+ {"not found never routes", Page{StatusCode: 404, Markdown: ""}, false, ""},
+ {"gone never routes", Page{StatusCode: 410, Error: "x"}, false, ""},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, reasons := NeedsBrowser(tt.page)
+ if got != tt.want {
+ t.Fatalf("NeedsBrowser() = %v, want %v (reasons %v)", got, tt.want, reasons)
+ }
+ if tt.reason != "" && (len(reasons) == 0 || reasons[0] != tt.reason) {
+ t.Fatalf("reasons = %v, want first %q", reasons, tt.reason)
+ }
+ })
+ }
+}
+
+func TestRunRoutesThinPagesThroughBrowser(t *testing.T) {
+ crawl := fakeCrawl(
+ seaportal.PageObject{URL: "https://example.com/", Title: "Home", Status: 200, Markdown: longMarkdown, ContentType: "page"},
+ seaportal.PageObject{URL: "https://example.com/app", Title: "App", Status: 200, Markdown: "Loading…", ContentType: "page"},
+ seaportal.PageObject{URL: "https://example.com/missing", Status: 404, Error: "not found"},
+ )
+ var rendered []string
+ render := func(url string) (string, error) {
+ rendered = append(rendered, url)
+ return renderedHTML, nil
+ }
+
+ report, err := Run(context.Background(), Input{URL: "https://example.com"}, RunOptions{}, crawl, render)
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+
+ if len(rendered) != 1 || rendered[0] != "https://example.com/app" {
+ t.Fatalf("browser rendered %v, want only the thin page", rendered)
+ }
+
+ home, app, missing := report.Pages[0], report.Pages[1], report.Pages[2]
+ if home.Source != SourceHTTP || home.Markdown != longMarkdown {
+ t.Errorf("rich page should keep http content, got source=%q", home.Source)
+ }
+ if app.Source != SourceBrowser {
+ t.Errorf("thin page source = %q, want browser (browserError=%q)", app.Source, app.BrowserError)
+ }
+ if !strings.Contains(app.Markdown, "JavaScript rendered") {
+ t.Errorf("thin page markdown not replaced by rendered extraction: %q", app.Markdown)
+ }
+ if app.Title != "Rendered Title" {
+ t.Errorf("thin page title = %q, want rendered title", app.Title)
+ }
+ if !app.BrowserRecommended || len(app.BrowserReasons) == 0 {
+ t.Errorf("thin page should record routing verdict, got %v %v", app.BrowserRecommended, app.BrowserReasons)
+ }
+ if missing.Source != SourceHTTP || missing.Error == "" {
+ t.Errorf("404 page must stay http-sourced with its error, got source=%q error=%q", missing.Source, missing.Error)
+ }
+
+ if report.Summary.HTTPPages != 1 || report.Summary.BrowserPages != 1 || report.Summary.FailedPages != 1 {
+ t.Errorf("summary = %+v, want 1 http / 1 browser / 1 failed", report.Summary)
+ }
+ if report.SchemaVersion != SchemaVersion {
+ t.Errorf("schemaVersion = %q", report.SchemaVersion)
+ }
+ if len(report.PageGroups) != 1 || len(report.PageGroups[0].URLs) != 3 {
+ t.Errorf("page tree not preserved: %+v", report.PageGroups)
+ }
+}
+
+func TestRunBrowserFailureKeepsHTTPContent(t *testing.T) {
+ crawl := fakeCrawl(seaportal.PageObject{URL: "https://example.com/app", Status: 200, Markdown: "Loading…"})
+ render := func(string) (string, error) { return "", errors.New("tab crashed") }
+
+ report, err := Run(context.Background(), Input{URL: "https://example.com"}, RunOptions{}, crawl, render)
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ p := report.Pages[0]
+ if p.Source != SourceHTTP || p.Markdown != "Loading…" {
+ t.Errorf("failed enrichment must keep http content, got source=%q markdown=%q", p.Source, p.Markdown)
+ }
+ if p.BrowserError != "tab crashed" {
+ t.Errorf("browserError = %q", p.BrowserError)
+ }
+}
+
+func TestRunBrowserSuccessClearsFetchError(t *testing.T) {
+ crawl := fakeCrawl(seaportal.PageObject{URL: "https://example.com/blocked", Status: 403, Error: "403 Forbidden"})
+ render := func(string) (string, error) { return renderedHTML, nil }
+
+ report, err := Run(context.Background(), Input{URL: "https://example.com"}, RunOptions{}, crawl, render)
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ p := report.Pages[0]
+ if p.Error != "" || p.Source != SourceBrowser {
+ t.Errorf("browser recovery should clear the fetch error, got error=%q source=%q", p.Error, p.Source)
+ }
+ if report.Summary.FailedPages != 0 || report.Summary.BrowserPages != 1 {
+ t.Errorf("summary = %+v", report.Summary)
+ }
+}
+
+func TestRunNoBrowserSkipsEnrichmentButRecordsVerdict(t *testing.T) {
+ crawl := fakeCrawl(seaportal.PageObject{URL: "https://example.com/app", Status: 200, Markdown: "Loading…"})
+ render := func(string) (string, error) {
+ t.Fatal("render must not be called with NoBrowser")
+ return "", nil
+ }
+
+ report, err := Run(context.Background(), Input{URL: "https://example.com"}, RunOptions{NoBrowser: true}, crawl, render)
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ p := report.Pages[0]
+ if p.Source != SourceHTTP {
+ t.Errorf("source = %q", p.Source)
+ }
+ if !p.BrowserRecommended {
+ t.Error("routing verdict should still be recorded")
+ }
+}
+
+func TestRunEnrichAllRendersRichPagesToo(t *testing.T) {
+ crawl := fakeCrawl(
+ seaportal.PageObject{URL: "https://example.com/", Status: 200, Markdown: longMarkdown},
+ seaportal.PageObject{URL: "https://example.com/missing", Status: 404},
+ )
+ var rendered []string
+ render := func(url string) (string, error) {
+ rendered = append(rendered, url)
+ return renderedHTML, nil
+ }
+
+ report, err := Run(context.Background(), Input{URL: "https://example.com"}, RunOptions{EnrichAll: true}, crawl, render)
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ if len(rendered) != 1 || rendered[0] != "https://example.com/" {
+ t.Fatalf("enrich-all rendered %v, want the rich page but never the 404", rendered)
+ }
+ p := report.Pages[0]
+ if p.BrowserRecommended {
+ t.Error("enrich-all must not fake the routing verdict")
+ }
+ if len(p.BrowserReasons) != 1 || p.BrowserReasons[0] != "enrich-all" {
+ t.Errorf("reasons = %v", p.BrowserReasons)
+ }
+}
+
+func TestRunPreviewWithholdsBodiesAndSkipsBrowser(t *testing.T) {
+ crawl := fakeCrawl(
+ seaportal.PageObject{URL: "https://example.com/", Status: 200, Markdown: longMarkdown, ContentType: "page"},
+ seaportal.PageObject{URL: "https://example.com/app", Status: 200, Markdown: "Loading…"},
+ )
+ render := func(string) (string, error) {
+ t.Fatal("preview must not render in the browser")
+ return "", nil
+ }
+
+ report, err := Run(context.Background(), Input{URL: "https://example.com"}, RunOptions{Preview: true}, crawl, render)
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+
+ home := report.Pages[0]
+ if home.Markdown != "" {
+ t.Errorf("preview must withhold the body, got %q", home.Markdown)
+ }
+ if home.CharCount != utf8.RuneCountInString(longMarkdown) {
+ t.Errorf("charCount = %d, want %d", home.CharCount, utf8.RuneCountInString(longMarkdown))
+ }
+ if !strings.HasPrefix(home.Snippet, "Plenty of extracted") {
+ t.Errorf("snippet = %q", home.Snippet)
+ }
+ if app := report.Pages[1]; !app.BrowserRecommended || len(app.BrowserReasons) == 0 {
+ t.Error("preview should still record the routing verdict per page")
+ }
+ if report.Summary.BrowserPages != 0 {
+ t.Errorf("preview renders nothing, browserPages = %d", report.Summary.BrowserPages)
+ }
+}
+
+func TestURLListCrawlerFetchesExplicitURLsSecurely(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/a", func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ _, _ = fmt.Fprint(w, renderedHTML)
+ })
+ mux.HandleFunc("/missing", func(w http.ResponseWriter, _ *http.Request) {
+ http.Error(w, "nope", http.StatusNotFound)
+ })
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+
+ var vetted []string
+ guard := CrawlGuard{ValidateURL: func(u string) error { vetted = append(vetted, u); return nil }}
+ // Duplicate /a proves dedupe; --no-browser keeps the test hermetic.
+ crawl := URLListCrawler([]string{srv.URL + "/a", srv.URL + "/missing", srv.URL + "/a"}, 5*time.Second, guard)
+
+ report, err := Run(context.Background(), Input{URL: srv.URL}, RunOptions{NoBrowser: true}, crawl, nil)
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ if len(report.Pages) != 2 {
+ t.Fatalf("got %d pages, want 2 after dedupe", len(report.Pages))
+ }
+ if len(vetted) == 0 {
+ t.Error("expand fetches must pass through the security URLFilter")
+ }
+
+ a := report.Pages[0]
+ if a.Title != "Rendered Title" || !strings.Contains(a.Markdown, "JavaScript rendered") {
+ t.Errorf("page /a not extracted: title=%q md=%q", a.Title, a.Markdown)
+ }
+ if missing := report.Pages[1]; missing.StatusCode != http.StatusNotFound && missing.Error == "" {
+ t.Errorf("missing page should carry a 404 or error, got status=%d error=%q", missing.StatusCode, missing.Error)
+ }
+}
+
+func TestURLListCrawlerEmptyErrors(t *testing.T) {
+ crawl := URLListCrawler([]string{" ", ""}, 0, CrawlGuard{})
+ if _, err := crawl(context.Background()); err == nil {
+ t.Error("an empty expand list must error")
+ }
+}
+
+func TestSnippet(t *testing.T) {
+ if got := snippet(" hello\n\n world ", 100); got != "hello world" {
+ t.Errorf("whitespace collapse = %q, want %q", got, "hello world")
+ }
+ got := snippet(strings.Repeat("a", 300), 10)
+ if utf8.RuneCountInString(got) != 11 || !strings.HasSuffix(got, "…") {
+ t.Errorf("truncation = %q (len %d), want 10 chars + ellipsis", got, utf8.RuneCountInString(got))
+ }
+}
+
+func TestRunErrors(t *testing.T) {
+ failCrawl := func(context.Context) (*seaportal.ScrapeResult, error) { return nil, errors.New("dns failure") }
+ if _, err := Run(context.Background(), Input{}, RunOptions{}, failCrawl, nil); err == nil || !strings.Contains(err.Error(), "site crawl") {
+ t.Errorf("crawl failure must surface, got %v", err)
+ }
+ if _, err := Run(context.Background(), Input{}, RunOptions{}, fakeCrawl(), nil); err == nil || !strings.Contains(err.Error(), "no pages") {
+ t.Errorf("empty crawl must error, got %v", err)
+ }
+}
+
+func TestCrawlGuardPolicy(t *testing.T) {
+ var checked []string
+ guard := CrawlGuard{
+ ValidateURL: func(url string) error {
+ checked = append(checked, url)
+ if strings.Contains(url, "blocked") {
+ return errors.New("blocked by navguard")
+ }
+ return nil
+ },
+ TrustedResolveCIDRs: []string{"172.16.0.0/12"},
+ MaxRedirects: 4,
+ }
+ p := guard.Policy()
+
+ if p.BlockPrivateIPs {
+ t.Error("private-IP enforcement must be delegated to ValidateURL")
+ }
+ if p.MaxRedirects != 4 || !p.RevalidateRedirects {
+ t.Errorf("redirect policy = %d/%v, want 4/true", p.MaxRedirects, p.RevalidateRedirects)
+ }
+ if len(p.TrustedResolveCIDRs) != 1 {
+ t.Errorf("trusted CIDRs not threaded: %v", p.TrustedResolveCIDRs)
+ }
+ if p.MaxResponseBytes == 0 || len(p.AllowedSchemes) == 0 {
+ t.Error("secure defaults (size caps, scheme allowlist) must be kept")
+ }
+
+ if err := p.ValidateURL(context.Background(), "https://ok.example.com/"); err != nil {
+ t.Errorf("allowed URL rejected: %v", err)
+ }
+ if err := p.ValidateURL(context.Background(), "https://blocked.example.com/"); err == nil {
+ t.Error("navguard veto must propagate through the policy")
+ }
+ if len(checked) != 2 {
+ t.Errorf("ValidateURL saw %v, want both URLs", checked)
+ }
+}
+
+func TestCrawlGuardPolicyWithoutValidatorFailsClosed(t *testing.T) {
+ p := CrawlGuard{}.Policy()
+ if !p.BlockPrivateIPs {
+ t.Error("without a ValidateURL hook the policy must keep BlockPrivateIPs")
+ }
+ if p.MaxRedirects <= 0 {
+ t.Errorf("MaxRedirects = %d, a crawl must never be unlimited", p.MaxRedirects)
+ }
+}
+
+func TestRunConcurrencyIsBounded(t *testing.T) {
+ var pages []seaportal.PageObject
+ for i := 0; i < 20; i++ {
+ pages = append(pages, seaportal.PageObject{URL: fmt.Sprintf("https://example.com/p%d", i), Status: 200, Markdown: "x"})
+ }
+ active := make(chan struct{}, MaxConcurrency) // buffered at the cap: overflow panics via select default
+ render := func(string) (string, error) {
+ select {
+ case active <- struct{}{}:
+ default:
+ t.Error("more concurrent renders than MaxConcurrency")
+ }
+ defer func() { <-active }()
+ return renderedHTML, nil
+ }
+ if _, err := Run(context.Background(), Input{}, RunOptions{Concurrency: 99}, fakeCrawl(pages...), render); err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+}
diff --git a/internal/scrape/types.go b/internal/scrape/types.go
new file mode 100644
index 00000000..03055c71
--- /dev/null
+++ b/internal/scrape/types.go
@@ -0,0 +1,101 @@
+// Package scrape implements the site scrape pipeline: a fast seaportal HTTP
+// crawl builds the page tree and markdown content, then pages whose HTTP
+// extraction came back thin, blocked, or failed are re-rendered in a real
+// browser (whatever provider the instance runs — chrome, cloak, ghost-chrome)
+// and re-extracted from the rendered HTML.
+package scrape
+
+import "time"
+
+// SchemaVersion is the current scrape report schema version, embedded in
+// every report so consumers can detect format changes.
+const SchemaVersion = "1.0"
+
+// Page sources: how a page's content was obtained.
+const (
+ SourceHTTP = "http"
+ SourceBrowser = "browser"
+)
+
+// Input records what was asked for, echoed back in the report.
+type Input struct {
+ URL string `json:"url"`
+ MaxPages int `json:"maxPages,omitempty"`
+ MaxPerPattern int `json:"maxPerPattern,omitempty"`
+ IncludePatterns []string `json:"includePatterns,omitempty"`
+ ExcludePatterns []string `json:"excludePatterns,omitempty"`
+}
+
+// Page is one scraped page: seaportal's HTTP extraction, possibly replaced
+// by a browser-rendered extraction when routing decided HTTP was not enough.
+type Page struct {
+ URL string `json:"url"`
+ Title string `json:"title,omitempty"`
+ StatusCode int `json:"statusCode,omitempty"`
+ ContentType string `json:"contentType,omitempty"`
+ Markdown string `json:"markdown,omitempty"`
+ Meta map[string]string `json:"meta,omitempty"`
+
+ // CharCount is the length in characters of the extracted content. It is
+ // set in preview mode (where Markdown is withheld) so a caller can gauge
+ // how heavy a full expand of this page would be.
+ CharCount int `json:"charCount,omitempty"`
+ // Snippet is the leading, whitespace-collapsed slice of the extracted
+ // content, set only in preview mode as a stand-in for the withheld
+ // Markdown so a caller can tell what the page is about.
+ Snippet string `json:"snippet,omitempty"`
+ Schema []map[string]any `json:"schema,omitempty"`
+ InternalLinks int `json:"internalLinks,omitempty"`
+ ExternalLinks int `json:"externalLinks,omitempty"`
+
+ // Source is where Markdown came from: SourceHTTP or SourceBrowser.
+ Source string `json:"source"`
+ // BrowserRecommended is the routing verdict for this page, recorded
+ // even when enrichment was skipped (--no-browser) or forced (--enrich-all).
+ BrowserRecommended bool `json:"browserRecommended,omitempty"`
+ // BrowserReasons explains why the page was routed to the browser.
+ BrowserReasons []string `json:"browserReasons,omitempty"`
+ // BrowserError is a failed browser enrichment; the HTTP extraction is
+ // kept and the run does not fail.
+ BrowserError string `json:"browserError,omitempty"`
+ // Error is the page-level failure when no engine produced content.
+ Error string `json:"error,omitempty"`
+}
+
+// PageGroup is one URL-pattern cluster of the site tree. Pages appear once
+// in Report.Pages; groups reference them by URL.
+type PageGroup struct {
+ Pattern string `json:"pattern"`
+ Total int `json:"total"`
+ Sampled int `json:"sampled"`
+ URLs []string `json:"urls"`
+}
+
+// SiteInfo describes the crawled site.
+type SiteInfo struct {
+ BaseURL string `json:"baseUrl"`
+ Title string `json:"title,omitempty"`
+ SitemapFound bool `json:"sitemapFound"`
+ TotalDiscovered int `json:"totalDiscovered"`
+ SampledPages int `json:"sampledPages"`
+}
+
+// Summary is the run roll-up.
+type Summary struct {
+ ContentTypes map[string]int `json:"contentTypes,omitempty"`
+ HTTPPages int `json:"httpPages"`
+ BrowserPages int `json:"browserPages"`
+ FailedPages int `json:"failedPages"`
+ Recommendations []string `json:"recommendations,omitempty"`
+}
+
+// Report is the versioned scrape output.
+type Report struct {
+ SchemaVersion string `json:"schemaVersion"`
+ GeneratedAt time.Time `json:"generatedAt"`
+ Input Input `json:"input"`
+ Site SiteInfo `json:"site"`
+ PageGroups []PageGroup `json:"pageGroups"`
+ Pages []Page `json:"pages"`
+ Summary Summary `json:"summary"`
+}