High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: isolate injected cookies and auto-discover cloakbrowser default
Luigi Agosti83b05320231e
diff --git a/cmd/pinchtab/cmd_audit.go b/cmd/pinchtab/cmd_audit.goindex 64c35579..b533c92c 100644--- a/cmd/pinchtab/cmd_audit.go+++ b/cmd/pinchtab/cmd_audit.go@@ -1,6 +1,8 @@package mainimport (+ "fmt"+browseractions "github.com/pinchtab/pinchtab/internal/cli/actions""github.com/spf13/cobra")@@ -23,18 +25,17 @@ prints the full report to stdout.Pages that fail to load do not fail the run: the command still exits 0 andthe failing page's report entry carries an "error" field.`,Args: cobra.MaximumNArgs(1),- Run: func(cmd *cobra.Command, args []string) {+ RunE: func(cmd *cobra.Command, args []string) error {seaportalReport, _ := cmd.Flags().GetString("seaportal-report")if len(args) == 0 && seaportalReport == "" {- cmd.PrintErrln("audit needs a URL argument or --seaportal-report")- return+ return fmt.Errorf("audit needs a URL argument or --seaportal-report")}target := ""if len(args) > 0 {target = args[0]}- runCLI(func(rt cliRuntime) {- browseractions.Audit(rt.client, rt.base, rt.token, cmd, target)+ return runCLIWithError(func(rt cliRuntime) error {+ return browseractions.Audit(rt.client, rt.base, rt.token, cmd, target)})},}diff --git a/cmd/pinchtab/cmd_cli_runtime.go b/cmd/pinchtab/cmd_cli_runtime.goindex b5d6f4bc..25264bb2 100644--- a/cmd/pinchtab/cmd_cli_runtime.go+++ b/cmd/pinchtab/cmd_cli_runtime.go@@ -25,6 +25,10 @@ func runCLI(fn func(cliRuntime)) {runCLIWith(loadConfig(), fn)}+func runCLIWithError(fn func(cliRuntime) error) error {+ return fn(newCLIRuntime(loadConfig()))+}+func runCLIWith(cfg *config.RuntimeConfig, fn func(cliRuntime)) {fn(newCLIRuntime(cfg))}diff --git a/cmd/pinchtab/cmd_compare.go b/cmd/pinchtab/cmd_compare.goindex c288a31b..4be239a0 100644--- a/cmd/pinchtab/cmd_compare.go+++ b/cmd/pinchtab/cmd_compare.go@@ -20,9 +20,9 @@ Differences are data, not failure: the command exits 0 even when pagesdiffer. Pass --fail-on-diff to exit non-zero when any visual or data diffexists (CI gate).`,Args: cobra.ExactArgs(2),- Run: func(cmd *cobra.Command, args []string) {- runCLI(func(rt cliRuntime) {- browseractions.Compare(rt.client, rt.base, rt.token, cmd, args[0], args[1])+ RunE: func(cmd *cobra.Command, args []string) error {+ return runCLIWithError(func(rt cliRuntime) error {+ return browseractions.Compare(rt.client, rt.base, rt.token, cmd, args[0], args[1])})},}diff --git a/cmd/pinchtab/cmd_scrape.go b/cmd/pinchtab/cmd_scrape.goindex b6c71a1f..3c4bb348 100644--- a/cmd/pinchtab/cmd_scrape.go+++ b/cmd/pinchtab/cmd_scrape.go@@ -30,9 +30,9 @@ exactly those URLs instead of crawling.Pages that fail in both engines do not fail the run: the command stillexits 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])+ RunE: func(cmd *cobra.Command, args []string) error {+ return runCLIWithError(func(rt cliRuntime) error {+ return browseractions.Scrape(rt.client, rt.base, rt.token, cmd, args[0])})},}diff --git a/docs/audit.md b/docs/audit.mdindex 0a5ff23d..16fa62bf 100644--- a/docs/audit.md+++ b/docs/audit.md@@ -54,9 +54,9 @@ no URL argument is needed.| `--output-dir <dir>` | | Write `report.json` and `screenshots/` to this directory || `--format <f>` | json | Report format: `json`, `md`, `html`, or `pdf` || `--json` | false | Print the full report JSON to stdout |-| `--cookie name=value` | | Inject a cookie before the run (repeatable; the cookie jar is cleared afterwards) |-| `--cookies-file <file>` | | Inject cookies from a JSON array of `{name, value, domain, ...}` objects |-| `--profile <name>` | | Run against the instance of this browser profile |+| `--cookie name=value` | | Inject a cookie into an isolated temporary browser instance before the run (repeatable) |+| `--cookies-file <file>` | | Inject cookies into an isolated temporary browser instance from a JSON array of `{name, value, domain, ...}` objects |+| `--profile <name>` | | Run against the instance of this browser profile (cannot be combined with `--cookie` or `--cookies-file`) |Failure contract: a page that fails to load does **not** fail the run — thecommand exits 0 and that page's report entry carries an `error` field. The run@@ -141,10 +141,12 @@ pinchtab audit https://example.com/account --cookies-file cookies.jsonpinchtab audit https://example.com --profile work```-Cookies are injected before the first navigation and scoped to the run: the-browser cookie jar is cleared when the run finishes, so a later audit does-not inherit them. `--profile` routes the run at the instance owning that-browser profile (`pinchtab instance start --profile <name>` to launch one).+Cookies are injected before the first navigation into an isolated temporary+browser instance. The instance and its cookie jar are discarded when the run+finishes, including if the audit request fails, so no persistent profile is+altered. `--cookie` and `--cookies-file` cannot be combined with `--profile`.+Without injected cookies, `--profile` routes the run at the instance owning+that browser profile (`pinchtab instance start --profile <name>` to launch one).## Library mode (Go)diff --git a/docs/guides/cloakbrowser.md b/docs/guides/cloakbrowser.mdindex d4d6463e..e4f3001a 100644--- a/docs/guides/cloakbrowser.md+++ b/docs/guides/cloakbrowser.md@@ -69,7 +69,10 @@ PinchTab's distribution policy for CloakBrowser is:are clear with the upstream CloakBrowser maintainers.The safe default is: install or download CloakBrowser yourself, then point-PinchTab at that local binary path.+PinchTab at that local binary path if it is not discoverable. PinchTab+automatically prefers a discoverable local CloakBrowser installation when+`browsers.default` is omitted, including in a newly generated config. Existing+configs that explicitly choose Chrome continue to use Chrome.Review:diff --git a/docs/reference/config.md b/docs/reference/config.mdindex fd3a851d..29fc19bf 100644--- a/docs/reference/config.md+++ b/docs/reference/config.md@@ -369,12 +369,17 @@ equivalent field is `browsers.default`:}```-`browsers.default` selects the local browser backend:+`browsers.default` explicitly selects the local browser backend:-- `chrome` is the default and uses the normal Chrome/Chromium launch path.+- `chrome` uses the normal Chrome/Chromium launch path.- `ghost-chrome` serves static-friendly reads from a lightweight fetcher andescalates to Chrome when a page needs rendering.-- `cloak` uses a user-installed CloakBrowser Chromium binary from `browser.binary`.+- `cloak` uses a discovered or configured local CloakBrowser Chromium binary.++When `browsers.default` is omitted, PinchTab prefers a discovered local+CloakBrowser installation and otherwise falls back to Chrome. Newly generated+config files make the same choice, while existing configs that explicitly set+`browsers.default` to `chrome` continue to use Chrome.`browsers.available` optionally restricts which browsers requests may select.For multiple named configurations of the same provider (different binaries,@@ -383,9 +388,10 @@ and `browser.fallbackOrder` — see [Terminology](../architecture/terminology.mdThe legacy `browser.provider` field is no longer supported and is rejected atvalidation time.-When the selected browser is `cloak`, `browser.binary` (or the target's-`binary`) must point at the local CloakBrowser Chromium executable. PinchTab-does not download, bundle, or redistribute the CloakBrowser binary.+When the selected browser is `cloak`, PinchTab uses `browser.binary` when set+or searches its normal local CloakBrowser paths. A named CloakBrowser target+must set that target's `binary` explicitly. PinchTab does not download, bundle,+or redistribute the CloakBrowser binary.On **macOS**, prefer a dedicated automation browser over your daily GoogleChrome. Launching `/Applications/Google Chrome.app` headless makes macOS treatdiff --git a/docs/scrape.md b/docs/scrape.mdindex 76e8a2fa..a63ea564 100644--- a/docs/scrape.md+++ b/docs/scrape.md@@ -90,9 +90,9 @@ link-crawls from the root page.| `--output-dir <dir>` | | Write `report.json` (and `report.md` with `--format md`) to this directory || `--format <f>` | json | Report format: `json` or `md` || `--json` | false | Print the full report JSON to stdout |-| `--cookie name=value` | | Inject a cookie before the run (repeatable; the cookie jar is cleared afterwards) |-| `--cookies-file <file>` | | Inject cookies from a JSON array of `{name, value, domain, ...}` objects |-| `--profile <name>` | | Run against the instance of this browser profile |+| `--cookie name=value` | | Inject a cookie into an isolated temporary browser instance before the run (repeatable) |+| `--cookies-file <file>` | | Inject cookies into an isolated temporary browser instance from a JSON array of `{name, value, domain, ...}` objects |+| `--profile <name>` | | Run against the instance of this browser profile (cannot be combined with `--cookie` or `--cookies-file`) |Failure contract: a page that fails in **both** engines does not fail the run —the command exits 0 and that page's report entry carries an `error` field. A@@ -142,8 +142,8 @@ by URL pattern, and each page's content (or its snippet in preview mode).The CLI is a thin client over one endpoint:- `POST /scrape {"url", "preview", "only", "maxPages", "maxPerPattern",- "includePatterns", "excludePatterns", "concurrency", "enrichAll",- "noBrowser", "timeoutSeconds"}` → the scrape report+ "includePatterns", "excludePatterns", "concurrency", "enrichAll",+ "noBrowser", "timeoutSeconds", "browser"}` → the scrape reportEvery crawl fetch and every expand fetch goes through the same SSRF/redirectnavigation guard as browser navigation.diff --git a/internal/cli/actions/actions_audit.go b/internal/cli/actions/actions_audit.goindex 9c15c66a..a79a0050 100644--- a/internal/cli/actions/actions_audit.go+++ b/internal/cli/actions/actions_audit.go@@ -33,78 +33,120 @@ func mustBool(cmd *cobra.Command, name string) bool {}// applyRunAuth resolves --profile routing and injects --cookie /-// --cookies-file cookies before the run. Isolation approach: injected-// cookies live in the shared browser jar, so the returned cleanup clears-// the jar after the run (documented on the audit/compare help).-func applyRunAuth(client *http.Client, base, token string, cmd *cobra.Command, scopeURL string) (string, func()) {- if profile := mustString(cmd, "profile"); profile != "" {- base = resolveProfileBase(client, base, token, profile)- }- cookies := loadRunCookies(cmd)+// --cookies-file cookies before the run. Cookie-authenticated runs receive a+// disposable instance so they never alter a persistent browser profile.+func applyRunAuth(client *http.Client, base, token string, cmd *cobra.Command, scopeURL string) (string, func() error, error) {+ cookies, err := loadRunCookies(cmd)+ if err != nil {+ return "", nil, err+ }if len(cookies) == 0 {- return base, func() {}+ if profile := mustString(cmd, "profile"); profile != "" {+ base, err = resolveProfileBase(client, base, token, profile)+ if err != nil {+ return "", nil, err+ }+ }+ return base, func() error { return nil }, nil+ }+ if mustString(cmd, "profile") != "" {+ return "", nil, fmt.Errorf("--profile cannot be combined with --cookie or --cookies-file; cookie-authenticated runs use an isolated temporary instance")}if scopeURL == "" {- fmt.Fprintln(os.Stderr, "cookie injection requires a URL target")- os.Exit(1)+ return "", nil, fmt.Errorf("cookie injection requires a URL target")+ }++ instanceBase, cleanup, err := startIsolatedInstance(client, base, token)+ if err != nil {+ return "", nil, err+ }+ if err := setRunCookies(client, instanceBase, token, scopeURL, cookies); err != nil {+ if cleanupErr := cleanup(); cleanupErr != nil {+ return "", nil, fmt.Errorf("set run cookies: %w (also failed to stop isolated instance: %v)", err, cleanupErr)+ }+ return "", nil, fmt.Errorf("set run cookies: %w", err)}- setRunCookies(client, base, token, scopeURL, cookies)- return base, func() { clearRunCookies(client, base, token) }+ return instanceBase, cleanup, nil}-func loadRunCookies(cmd *cobra.Command) []audit.Cookie {+func loadRunCookies(cmd *cobra.Command) ([]audit.Cookie, error) {flags, _ := cmd.Flags().GetStringArray("cookie")var fileData []byteif path := mustString(cmd, "cookies-file"); path != "" {data, err := os.ReadFile(path)if err != nil {- fmt.Fprintf(os.Stderr, "read cookies file: %v\n", err)- os.Exit(1)+ return nil, fmt.Errorf("read cookies file: %w", err)}fileData = data}cookies, err := audit.CollectCookies(flags, fileData)if err != nil {- fmt.Fprintf(os.Stderr, "%v\n", err)- os.Exit(1)+ return nil, err}- return cookies+ return cookies, nil}// setRunCookies injects cookies through POST /cookies, using a throwaway// blank tab for the required tab context so it works on a fresh browser.-func setRunCookies(client *http.Client, base, token, url string, cookies []audit.Cookie) {- tab := apiclient.DoPostQuiet(client, base, token, "/tab", map[string]any{"action": "new"})- tabID, _ := tab["tabId"].(string)+func setRunCookies(client *http.Client, base, token, url string, cookies []audit.Cookie) error {+ raw, err := apiclient.DoPostRawE(client, base, token, "/tab", map[string]any{"action": "new"})+ if err != nil {+ return err+ }+ var tab struct {+ TabID string `json:"tabId"`+ }+ if err := json.Unmarshal(raw, &tab); err != nil {+ return fmt.Errorf("parse temporary tab: %w", err)+ }+ if tab.TabID != "" {+ defer func() { _, _ = apiclient.DoPostRawE(client, base, token, "/close", map[string]any{"tabId": tab.TabID}) }()+ }body := map[string]any{"url": url, "cookies": cookies}- if tabID != "" {- body["tabId"] = tabID+ if tab.TabID != "" {+ body["tabId"] = tab.TabID}- apiclient.DoPostQuiet(client, base, token, "/cookies", body)- if tabID != "" {- apiclient.DoPostQuiet(client, base, token, "/close", map[string]any{"tabId": tabID})+ if _, err := apiclient.DoPostRawE(client, base, token, "/cookies", body); err != nil {+ return err}+ return nil}-// clearRunCookies clears the browser cookie jar, quietly and best-effort.-func clearRunCookies(client *http.Client, base, token string) {- req, err := http.NewRequest(http.MethodDelete, base+"/cookies", nil)+// startIsolatedInstance creates an unnamed instance. The orchestrator assigns+// these an instance-* profile and removes its profile directory on stop.+func startIsolatedInstance(client *http.Client, base, token string) (string, func() error, error) {+ raw, err := apiclient.DoPostRawE(client, base, token, "/instances/start", map[string]any{})if err != nil {- return+ return "", nil, fmt.Errorf("start isolated instance: %w", err)}- if token != "" {- req.Header.Set("Authorization", "Bearer "+token)+ var instance struct {+ ID string `json:"id"`+ URL string `json:"url"`+ }+ if err := json.Unmarshal(raw, &instance); err != nil {+ return "", nil, fmt.Errorf("parse isolated instance: %w", err)+ }+ if instance.ID == "" || instance.URL == "" {+ return "", nil, fmt.Errorf("start isolated instance: response omitted id or url")}- if resp, err := client.Do(req); err == nil {- _ = resp.Body.Close()+ cleanup := func() error {+ _, err := apiclient.DoPostRawE(client, base, token, "/instances/"+url.PathEscape(instance.ID)+"/stop", nil)+ if err != nil {+ return fmt.Errorf("stop isolated instance: %w", err)+ }+ return nil}+ return strings.TrimSuffix(instance.URL, "/"), cleanup, nil}// resolveProfileBase routes the run at the instance owning the named// profile: the orchestrator base for the default-routed instance, or the// instance's own URL otherwise.-func resolveProfileBase(client *http.Client, base, token, profile string) string {- raw := apiclient.DoGetRaw(client, base, token, "/instances", nil)+func resolveProfileBase(client *http.Client, base, token, profile string) (string, error) {+ raw, err := apiclient.DoGetRawE(client, base, token, "/instances", nil)+ if err != nil {+ return "", err+ }var instances []struct {ID string `json:"id"`ProfileName string `json:"profileName"`@@ -112,21 +154,18 @@ func resolveProfileBase(client *http.Client, base, token, profile string) stringURL string `json:"url"`}if err := json.Unmarshal(raw, &instances); err != nil {- fmt.Fprintf(os.Stderr, "parse instances: %v\n", err)- os.Exit(1)+ return "", fmt.Errorf("parse instances: %w", err)}for _, inst := range instances {if inst.ProfileName != profile || inst.Status != "running" {continue}if inst.ID == defaultInstanceID(client, base, token) {- return base+ return base, nil}- return strings.TrimSuffix(inst.URL, "/")+ return strings.TrimSuffix(inst.URL, "/"), nil}- fmt.Fprintf(os.Stderr, "no running instance for profile %q (start one: pinchtab instance start --profile %s)\n", profile, profile)- os.Exit(1)- return ""+ return "", fmt.Errorf("no running instance for profile %q (start one: pinchtab instance start --profile %s)", profile, profile)}func defaultInstanceID(client *http.Client, base, token string) string {@@ -157,13 +196,24 @@ func validateAuditFlags(cmd *cobra.Command) error {}// Audit runs a multi-page site audit via POST /audit and writes artifacts.-func Audit(client *http.Client, base, token string, cmd *cobra.Command, target string) {+func Audit(client *http.Client, base, token string, cmd *cobra.Command, target string) (err error) {if err := validateAuditFlags(cmd); err != nil {- fmt.Fprintln(os.Stderr, err)- os.Exit(1)+ return err}- base, cleanupCookies := applyRunAuth(client, base, token, cmd, target)+ base, cleanup, err := applyRunAuth(client, base, token, cmd, target)+ if err != nil {+ return err+ }+ defer func() {+ if cleanupErr := cleanup(); cleanupErr != nil {+ if err == nil {+ err = cleanupErr+ } else {+ err = fmt.Errorf("%w (also %v)", err, cleanupErr)+ }+ }+ }()body := map[string]any{}switch {@@ -171,8 +221,7 @@ func Audit(client *http.Client, base, token string, cmd *cobra.Command, target spath := mustString(cmd, "seaportal-report")data, err := os.ReadFile(path)if err != nil {- fmt.Fprintf(os.Stderr, "read seaportal report: %v\n", err)- os.Exit(1)+ return fmt.Errorf("read seaportal report: %w", err)}body["seaportalResults"] = json.RawMessage(data)body["seaportalFile"] = path@@ -196,13 +245,14 @@ func Audit(client *http.Client, base, token string, cmd *cobra.Command, target s}longClient := &http.Client{Transport: client.Transport, Timeout: auditTimeout}- raw := apiclient.DoPostRaw(longClient, base, token, "/audit", body)- cleanupCookies()+ raw, err := apiclient.DoPostRawE(longClient, base, token, "/audit", body)+ if err != nil {+ return err+ }var report map[string]anyif err := json.Unmarshal(raw, &report); err != nil {- fmt.Fprintf(os.Stderr, "parse audit report: %v\n", err)- os.Exit(1)+ return fmt.Errorf("parse audit report: %w", err)}format := renderFormat(cmd)@@ -214,35 +264,35 @@ func Audit(client *http.Client, base, token string, cmd *cobra.Command, target stypedForPDF = typedAuditReport(report)}if err := writeAuditArtifacts(dir, report); err != nil {- fmt.Fprintf(os.Stderr, "write artifacts: %v\n", err)- os.Exit(1)+ return fmt.Errorf("write artifacts: %w", err)}switch {case format == auditreport.FormatPDF:- exportAuditPDF(client, base, token, dir, typedForPDF)+ if err := exportAuditPDF(client, base, token, dir, typedForPDF); err != nil {+ return err+ }case format != auditreport.FormatJSON:if err := renderAuditReportFile(dir, report, format); err != nil {- fmt.Fprintf(os.Stderr, "render report: %v\n", err)- os.Exit(1)+ return fmt.Errorf("render report: %w", err)}}fmt.Fprintf(os.Stderr, "report written to %s\n", filepath.Join(dir, "report.json"))} else if format != auditreport.FormatJSON {rendered, err := auditreport.Render(typedAuditReport(report), format)if err != nil {- fmt.Fprintf(os.Stderr, "render report: %v\n", err)- os.Exit(1)+ return fmt.Errorf("render report: %w", err)}fmt.Println(string(rendered))- return+ return nil}if v, _ := cmd.Flags().GetBool("json"); v {out, _ := json.MarshalIndent(report, "", " ")fmt.Println(string(out))- return+ return nil}printAuditSummary(report)+ return nil}// renderFormat reads the --format flag, defaulting to json.@@ -267,17 +317,16 @@ func typedAuditReport(report map[string]any) audit.AuditReport {// Graceful-degradation contract: report.json is already on disk by the time// this runs; a print failure surfaces as a warning and a non-zero exit// (pdf being the sole requested format).-func exportAuditPDF(client *http.Client, base, token, dir string, report audit.AuditReport) {+func exportAuditPDF(client *http.Client, base, token, dir string, report audit.AuditReport) error {pdf, err := auditreport.ExportPDF(report, serverPDFPrinter(client, base, token))if err != nil {- fmt.Fprintf(os.Stderr, "warning: PDF export failed: %v (report.json was still written)\n", err)- os.Exit(1)+ return fmt.Errorf("PDF export failed: %w (report.json was still written)", err)}path := filepath.Join(dir, "report.pdf")if err := os.WriteFile(path, pdf, 0o644); err != nil {- fmt.Fprintf(os.Stderr, "warning: write %s: %v (report.json was still written)\n", path, err)- os.Exit(1)+ return fmt.Errorf("write %s: %w (report.json was still written)", path, err)}+ return nil}// serverPDFPrinter prints self-contained HTML through the running server:diff --git a/internal/cli/actions/actions_audit_test.go b/internal/cli/actions/actions_audit_test.goindex 4af02301..b09dd70d 100644--- a/internal/cli/actions/actions_audit_test.go+++ b/internal/cli/actions/actions_audit_test.go@@ -1,10 +1,9 @@package actionsimport (+ "fmt""net/http""net/http/httptest"- "os"- "os/exec""strings""sync/atomic""testing"@@ -60,15 +59,7 @@ func TestValidateAuditFlags(t *testing.T) {}}-// The rejection must happen before any request: this re-execs the test-// binary to absorb Audit's os.Exit and fails if the fake instance receives-// a single hit — i.e. if the validation ever moves back below the POST.-func TestAuditPDFWithoutOutputDirExitsBeforePOST(t *testing.T) {- if os.Getenv("AUDIT_PREFLIGHT_HELPER") == "1" {- Audit(http.DefaultClient, os.Getenv("AUDIT_PREFLIGHT_BASE"), "", newAuditTestCmd("--format", "pdf"), "https://example.com")- return- }-+func TestAuditPDFWithoutOutputDirReturnsBeforePOST(t *testing.T) {var hits atomic.Int32srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {hits.Add(1)@@ -77,17 +68,59 @@ func TestAuditPDFWithoutOutputDirExitsBeforePOST(t *testing.T) {}))defer srv.Close()- cmd := exec.Command(os.Args[0], "-test.run", "TestAuditPDFWithoutOutputDirExitsBeforePOST")- cmd.Env = append(os.Environ(), "AUDIT_PREFLIGHT_HELPER=1", "AUDIT_PREFLIGHT_BASE="+srv.URL)- out, err := cmd.CombinedOutput()-- if err == nil {- t.Fatalf("expected non-zero exit, got success with output:\n%s", out)- }- if !strings.Contains(string(out), "--format pdf requires --output-dir") {- t.Errorf("output should name both flags:\n%s", out)+ err := Audit(http.DefaultClient, srv.URL, "", newAuditTestCmd("--format", "pdf"), "https://example.com")+ if err == nil || !strings.Contains(err.Error(), "--format pdf requires --output-dir") {+ t.Fatalf("Audit() error = %v, want missing output-dir error", err)}if got := hits.Load(); got != 0 {t.Errorf("server received %d request(s); validation ran after server work", got)}}++func TestAuditCookieRunStopsIsolatedInstanceOnFailure(t *testing.T) {+ var stopped atomic.Bool+ var deletedCookies atomic.Bool+ var srv *httptest.Server+ srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/instances/start":+ _, _ = fmt.Fprintf(w, `{"id":"isolated","url":%q}`, srv.URL)+ case "/tab":+ _, _ = w.Write([]byte(`{"tabId":"temporary-tab"}`))+ case "/cookies":+ if r.Method == http.MethodDelete {+ deletedCookies.Store(true)+ }+ _, _ = w.Write([]byte(`{"set":1}`))+ case "/close":+ _, _ = w.Write([]byte(`{}`))+ case "/audit":+ http.Error(w, `{"error":"upstream failed"}`, http.StatusBadGateway)+ case "/instances/isolated/stop":+ stopped.Store(true)+ _, _ = w.Write([]byte(`{"status":"stopped"}`))+ default:+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)+ http.Error(w, "unexpected request", http.StatusInternalServerError)+ }+ }))+ defer srv.Close()++ err := Audit(http.DefaultClient, srv.URL, "", newAuditTestCmd("--cookie", "session=temporary"), "https://example.com")+ if err == nil || !strings.Contains(err.Error(), "upstream failed") {+ t.Fatalf("Audit() error = %v, want upstream failure", err)+ }+ if !stopped.Load() {+ t.Fatal("isolated instance was not stopped after audit failure")+ }+ if deletedCookies.Load() {+ t.Fatal("cookie-authenticated audit cleared cookies instead of discarding its isolated instance")+ }+}++func TestApplyRunAuthRejectsProfileWithCookies(t *testing.T) {+ _, _, err := applyRunAuth(http.DefaultClient, "http://example.invalid", "", newAuditTestCmd("--profile", "work", "--cookie", "session=temporary"), "https://example.com")+ if err == nil || !strings.Contains(err.Error(), "--profile cannot be combined") {+ t.Fatalf("applyRunAuth() error = %v, want profile/cookie conflict", err)+ }+}diff --git a/internal/cli/actions/actions_compare.go b/internal/cli/actions/actions_compare.goindex 135641d7..6e4ec526 100644--- a/internal/cli/actions/actions_compare.go+++ b/internal/cli/actions/actions_compare.go@@ -16,15 +16,27 @@ import (// Compare audits the same pages on two base URLs and reports visual and// data differences per page.-func Compare(client *http.Client, base, token string, cmd *cobra.Command, liveBase, stagingBase string) {+func Compare(client *http.Client, base, token string, cmd *cobra.Command, liveBase, stagingBase string) (err error) {paths := comparePaths(cmd)visual := mustBool(cmd, "visual-diff")concurrency, _ := cmd.Flags().GetInt("concurrency")- base, cleanupCookies := applyRunAuth(client, base, token, cmd, liveBase)+ base, cleanup, err := applyRunAuth(client, base, token, cmd, liveBase)+ if err != nil {+ return err+ }+ defer func() {+ if cleanupErr := cleanup(); cleanupErr != nil {+ if err == nil {+ err = cleanupErr+ } else {+ err = fmt.Errorf("%w (also %v)", err, cleanupErr)+ }+ }+ }()longClient := &http.Client{Transport: client.Transport, Timeout: auditTimeout}- runSide := func(siteBase string) audit.AuditReport {+ runSide := func(siteBase string) (audit.AuditReport, error) {body := map[string]any{"urls": joinPaths(siteBase, paths),"options": map[string]any{"screenshot": visual},@@ -32,29 +44,34 @@ func Compare(client *http.Client, base, token string, cmd *cobra.Command, liveBaif concurrency > 0 {body["concurrency"] = concurrency}- raw := apiclient.DoPostRaw(longClient, base, token, "/audit", body)+ raw, err := apiclient.DoPostRawE(longClient, base, token, "/audit", body)+ if err != nil {+ return audit.AuditReport{}, err+ }var report audit.AuditReportif err := json.Unmarshal(raw, &report); err != nil {- fmt.Fprintf(os.Stderr, "parse audit report for %s: %v\n", siteBase, err)- os.Exit(1)+ return audit.AuditReport{}, fmt.Errorf("parse audit report for %s: %w", siteBase, err)}- return report+ return report, nil}- liveReport := runSide(liveBase)- stagingReport := runSide(stagingBase)- cleanupCookies()+ liveReport, err := runSide(liveBase)+ if err != nil {+ return err+ }+ stagingReport, err := runSide(stagingBase)+ if err != nil {+ return err+ }outcome, err := audit.ComparePages(liveBase, stagingBase, liveReport, stagingReport)if err != nil {- fmt.Fprintf(os.Stderr, "compare: %v\n", err)- os.Exit(1)+ return fmt.Errorf("compare: %w", err)}if dir, _ := cmd.Flags().GetString("output-dir"); dir != "" {if err := writeCompareArtifacts(dir, &outcome); err != nil {- fmt.Fprintf(os.Stderr, "write artifacts: %v\n", err)- os.Exit(1)+ return fmt.Errorf("write artifacts: %w", err)}fmt.Fprintf(os.Stderr, "report written to %s\n", filepath.Join(dir, "report.json"))}@@ -63,13 +80,11 @@ func Compare(client *http.Client, base, token string, cmd *cobra.Command, liveBaif format != auditreport.FormatJSON {rendered, err := auditreport.RenderComparison(outcome.Report, format)if err != nil {- fmt.Fprintf(os.Stderr, "render report: %v\n", err)- os.Exit(1)+ return fmt.Errorf("render report: %w", err)}if dir, _ := cmd.Flags().GetString("output-dir"); dir != "" {if err := os.WriteFile(filepath.Join(dir, "report."+format), rendered, 0o644); err != nil {- fmt.Fprintf(os.Stderr, "write rendered report: %v\n", err)- os.Exit(1)+ return fmt.Errorf("write rendered report: %w", err)}} else {fmt.Println(string(rendered))@@ -84,9 +99,9 @@ func Compare(client *http.Client, base, token string, cmd *cobra.Command, liveBa}if mustBool(cmd, "fail-on-diff") && outcome.Report.HasDiffs {- fmt.Fprintln(os.Stderr, "differences found (--fail-on-diff)")- os.Exit(1)+ return fmt.Errorf("differences found (--fail-on-diff)")}+ return nil}func comparePaths(cmd *cobra.Command) []string {diff --git a/internal/cli/actions/actions_scrape.go b/internal/cli/actions/actions_scrape.goindex dabd321f..f60c1233 100644--- a/internal/cli/actions/actions_scrape.go+++ b/internal/cli/actions/actions_scrape.go@@ -21,14 +21,25 @@ const scrapeTimeout = 15 * time.Minuteconst 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) {+func Scrape(client *http.Client, base, token string, cmd *cobra.Command, target string) (err error) {format := renderFormat(cmd)if format != "json" && format != scrapeFormatMarkdown {- fmt.Fprintf(os.Stderr, "unsupported --format %q (json or md)\n", format)- os.Exit(1)+ return fmt.Errorf("unsupported --format %q (json or md)", format)}- base, cleanupCookies := applyRunAuth(client, base, token, cmd, target)+ base, cleanup, err := applyRunAuth(client, base, token, cmd, target)+ if err != nil {+ return err+ }+ defer func() {+ if cleanupErr := cleanup(); cleanupErr != nil {+ if err == nil {+ err = cleanupErr+ } else {+ err = fmt.Errorf("%w (also %v)", err, cleanupErr)+ }+ }+ }()body := map[string]any{"url": target}if v, _ := cmd.Flags().GetInt("max-pages"); v > 0 {@@ -64,36 +75,37 @@ func Scrape(client *http.Client, base, token string, cmd *cobra.Command, target}longClient := &http.Client{Transport: client.Transport, Timeout: scrapeTimeout}- raw := apiclient.DoPostRaw(longClient, base, token, "/scrape", body)- cleanupCookies()+ raw, err := apiclient.DoPostRawE(longClient, base, token, "/scrape", body)+ if err != nil {+ return err+ }var report scrape.Reportif err := json.Unmarshal(raw, &report); err != nil {- fmt.Fprintf(os.Stderr, "parse scrape report: %v\n", err)- os.Exit(1)+ return fmt.Errorf("parse scrape report: %w", err)}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)+ return fmt.Errorf("write artifacts: %w", err)}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+ return nil}if mustBool(cmd, "json") {out, _ := json.MarshalIndent(report, "", " ")fmt.Println(string(out))- return+ return nil}if preview {printPreviewSummary(report)- return+ return nil}printScrapeSummary(report)+ return nil}// writeScrapeArtifacts writes report.json (the server response, indented)diff --git a/internal/cli/apiclient/client.go b/internal/cli/apiclient/client.goindex 56d3b319..2c2dd7b3 100644--- a/internal/cli/apiclient/client.go+++ b/internal/cli/apiclient/client.go@@ -6,6 +6,7 @@ import ("net/http""net/url""os"+ "strings""time")@@ -62,6 +63,35 @@ func DoPostRaw(client *http.Client, base, token, path string, body map[string]anreturn respBody}+// DoPostRawE sends a POST and returns an error instead of terminating the+// process. Long-running commands use it when they need to release resources+// before reporting a request failure.+func DoPostRawE(client *http.Client, base, token, path string, body map[string]any) ([]byte, error) {+ r := request{method: "POST", url: base + path, body: body}+ statusCode, respBody, err := doRequest(client, token, r)+ if err != nil {+ return nil, fmt.Errorf("request failed: %w", err)+ }+ if statusCode >= http.StatusBadRequest {+ return nil, fmt.Errorf("%s", strings.TrimSpace(renderAPIError(r, statusCode, respBody)))+ }+ return respBody, nil+}++// DoGetRawE sends a GET and returns an error instead of terminating the+// process. See DoPostRawE.+func DoGetRawE(client *http.Client, base, token, path string, params url.Values) ([]byte, error) {+ r := request{method: "GET", url: buildURL(base, path, params)}+ statusCode, respBody, err := doRequest(client, token, r)+ if err != nil {+ return nil, fmt.Errorf("request failed: %w", err)+ }+ if statusCode >= http.StatusBadRequest {+ return nil, fmt.Errorf("%s", strings.TrimSpace(renderAPIError(r, statusCode, respBody)))+ }+ return respBody, nil+}+func DoPostQuietWithStatus(client *http.Client, base, token, path string, body map[string]any) (int, []byte, map[string]any) {return doPostQuietWithStatus(client, base, token, path, body, nil)}diff --git a/internal/config/browser_provider.go b/internal/config/browser_provider.goindex a98f49ab..a36eff7a 100644--- a/internal/config/browser_provider.go+++ b/internal/config/browser_provider.go@@ -13,10 +13,21 @@ const (BrowserGhostChrome = "ghost-chrome")-// NormalizeBrowser maps user-facing config values (browser.provider,-// CLI flags) to canonical browser registry IDs. It is the intentional gateway-// between the config/API layer and browsers.Get during the browser architecture-// migration.+var discoverCloakBrowserBinary = func() string {+ browser, ok := browsers.Get(BrowserCloak)+ if !ok {+ return ""+ }+ return strings.TrimSpace(browser.DiscoverBinary().Found)+}++func DefaultBrowserForSystem() string {+ if discoverCloakBrowserBinary() != "" {+ return BrowserCloak+ }+ return BrowserChrome+}+func NormalizeBrowser(provider string) string {switch strings.ToLower(strings.TrimSpace(provider)) {case BrowserCloak:diff --git a/internal/config/browsers_config_test.go b/internal/config/browsers_config_test.goindex b6f22a73..a6ffb4fc 100644--- a/internal/config/browsers_config_test.go+++ b/internal/config/browsers_config_test.go@@ -175,6 +175,7 @@ func TestValidateBrowsersBlock_EmptyConfigMap(t *testing.T) {func TestBrowsersBlock_DefaultsWhenAbsent(t *testing.T) {clearConfigEnvVars(t)+ setCloakBrowserDiscovery(t, "")dir := t.TempDir()cfgPath := filepath.Join(dir, "config.json")@@ -199,6 +200,56 @@ func TestBrowsersBlock_DefaultsWhenAbsent(t *testing.T) {}}+func TestBrowsersBlock_DefaultsWhenAbsentPrefersInstalledCloakBrowser(t *testing.T) {+ clearConfigEnvVars(t)+ setCloakBrowserDiscovery(t, "/opt/cloakbrowser/chrome")+ dir := t.TempDir()+ cfgPath := filepath.Join(dir, "config.json")++ fc := FileConfig{Server: ServerConfig{Port: "9867"}}+ data, err := json.Marshal(fc)+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(cfgPath, data, 0o644); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", cfgPath)++ cfg := Load()+ if cfg.DefaultBrowser != BrowserCloak {+ t.Errorf("DefaultBrowser = %q, want %q when CloakBrowser is installed", cfg.DefaultBrowser, BrowserCloak)+ }+ if len(cfg.BrowsersAvailable) != 1 || cfg.BrowsersAvailable[0] != BrowserCloak {+ t.Errorf("BrowsersAvailable = %v, want [cloak]", cfg.BrowsersAvailable)+ }+}++func TestBrowsersBlock_ExplicitChromeWinsOverInstalledCloakBrowser(t *testing.T) {+ clearConfigEnvVars(t)+ setCloakBrowserDiscovery(t, "/opt/cloakbrowser/chrome")+ dir := t.TempDir()+ cfgPath := filepath.Join(dir, "config.json")++ fc := FileConfig{+ Server: ServerConfig{Port: "9867"},+ Browsers: BrowsersConfig{Default: BrowserChrome},+ }+ data, err := json.Marshal(fc)+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(cfgPath, data, 0o644); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", cfgPath)++ cfg := Load()+ if cfg.DefaultBrowser != BrowserChrome {+ t.Errorf("DefaultBrowser = %q, want explicit %q", cfg.DefaultBrowser, BrowserChrome)+ }+}+func TestBrowsersBlock_ExplicitValues(t *testing.T) {clearConfigEnvVars(t)dir := t.TempDir()diff --git a/internal/config/config_file.go b/internal/config/config_file.goindex 2f2e7e4f..b6f124f9 100644--- a/internal/config/config_file.go+++ b/internal/config/config_file.go@@ -174,7 +174,7 @@ func DefaultFileConfig() FileConfig {ExtensionPaths: []string{defaultExtensionsDir(userConfigDir())},},Browsers: BrowsersConfig{- Default: BrowserChrome,+ Default: DefaultBrowserForSystem(),},InstanceDefaults: InstanceDefaultsConfig{Mode: "headless",diff --git a/internal/config/config_file_test.go b/internal/config/config_file_test.goindex e3d3572a..84a46f8f 100644--- a/internal/config/config_file_test.go+++ b/internal/config/config_file_test.go@@ -8,6 +8,7 @@ import ()func TestDefaultFileConfig(t *testing.T) {+ setCloakBrowserDiscovery(t, "")fc := DefaultFileConfig()if fc.Schema != CurrentConfigSchemaURL() {t.Errorf("DefaultFileConfig.Schema = %q, want %q", fc.Schema, CurrentConfigSchemaURL())@@ -142,6 +143,13 @@ func TestDefaultFileConfig(t *testing.T) {}}+func TestDefaultFileConfigPrefersInstalledCloakBrowser(t *testing.T) {+ setCloakBrowserDiscovery(t, "/opt/cloakbrowser/chrome")+ if got := DefaultFileConfig().Browsers.Default; got != BrowserCloak {+ t.Errorf("DefaultFileConfig().Browsers.Default = %q, want %q when CloakBrowser is installed", got, BrowserCloak)+ }+}+func TestConfigSchemaURLFallsBackToLatestWhenNoPublishedSchemaMatches(t *testing.T) {originalPublished := publishedConfigSchemaVersionst.Cleanup(func() {diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex 0109cbed..40a11956 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -184,7 +184,7 @@ func LoadConfig() (*RuntimeConfig, []LoadDiagnostic, error) {BlockAds: false,MaxTabs: 20,MaxParallelTabs: 0,- DefaultBrowser: BrowserChrome,+ DefaultBrowser: DefaultBrowserForSystem(),BrowserBinary: "", // Set via config.json onlyBrowserExtraFlags: "",Cloak: CloakBrowserRuntimeConfig{DisableDefaultStealthArgs: true},@@ -535,7 +535,7 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {} else if name := ResolveDefaultTarget(cfg); name != "" && !cfg.TargetsSynthesized && cfg.Targets[name].Provider != "" {cfg.DefaultBrowser = NormalizeBrowser(cfg.Targets[name].Provider)} else {- cfg.DefaultBrowser = "chrome"+ cfg.DefaultBrowser = DefaultBrowserForSystem()}// Apply native-stealth default when the winning provider supports it.diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.goindex f104416e..1c7ebe94 100644--- a/internal/config/config_load_test.go+++ b/internal/config/config_load_test.go@@ -30,6 +30,7 @@ func TestEnvOr(t *testing.T) {func TestLoadConfigDefaults(t *testing.T) {clearConfigEnvVars(t)+ setCloakBrowserDiscovery(t, "")_ = os.Setenv("PINCHTAB_CONFIG", filepath.Join(t.TempDir(), "nonexistent.json"))defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()@@ -176,6 +177,20 @@ func TestLoadConfigDefaults(t *testing.T) {}}+func TestLoadConfigDefaultsPreferInstalledCloakBrowser(t *testing.T) {+ clearConfigEnvVars(t)+ setCloakBrowserDiscovery(t, "/opt/cloakbrowser/chrome")+ t.Setenv("PINCHTAB_CONFIG", filepath.Join(t.TempDir(), "nonexistent.json"))++ cfg, _, err := LoadConfig()+ if err != nil {+ t.Fatalf("LoadConfig() error = %v", err)+ }+ if cfg.DefaultBrowser != BrowserCloak {+ t.Errorf("default DefaultBrowser = %q, want %q when CloakBrowser is installed", cfg.DefaultBrowser, BrowserCloak)+ }+}+// TestLoadConfigDefaultSolvers asserts the default autosolver backend list// advertises only the implemented backends (cloudflare + semantic) and does// NOT include the skeleton-only capsolver/twocaptcha external backends.@@ -967,6 +982,13 @@ func clearConfigEnvVars(t *testing.T) {}}+func setCloakBrowserDiscovery(t *testing.T, binary string) {+ t.Helper()+ original := discoverCloakBrowserBinary+ discoverCloakBrowserBinary = func() string { return binary }+ t.Cleanup(func() { discoverCloakBrowserBinary = original })+}+func writeTestConfig(t *testing.T, body string) {t.Helper()tmpDir := t.TempDir()diff --git a/internal/handlers/scrape.go b/internal/handlers/scrape.goindex 5c2d8b6d..26102459 100644--- a/internal/handlers/scrape.go+++ b/internal/handlers/scrape.go@@ -26,6 +26,7 @@ const (type scrapeRequest struct {URL string `json:"url"`+ Browser string `json:"browser"`MaxPages int `json:"maxPages"`MaxPerPattern int `json:"maxPerPattern"`IncludePatterns []string `json:"includePatterns"`@@ -55,7 +56,7 @@ func (h *Handlers) HandleScrape(w http.ResponseWriter, r *http.Request) {return}- routing, ok := h.resolveNavigateBrowser(w, r, "", "")+ routing, ok := h.resolveNavigateBrowser(w, r, "", strings.TrimSpace(req.Browser))if !ok {return}diff --git a/internal/mcp/handlers_scrape_test.go b/internal/mcp/handlers_scrape_test.goindex c2fa97e5..ce922fbf 100644--- a/internal/mcp/handlers_scrape_test.go+++ b/internal/mcp/handlers_scrape_test.go@@ -39,6 +39,20 @@ func TestHandleScrapeSplitsCommaLists(t *testing.T) {}}+func TestHandleScrapeForwardsBrowser(t *testing.T) {+ srv := mockPinchTab()+ defer srv.Close()++ r := callTool(t, "pinchtab_scrape", map[string]any{+ "url": "https://example.com",+ "browser": "cloak",+ }, srv)++ if text := resultText(t, r); !strings.Contains(text, `"browser":"cloak"`) {+ t.Errorf("browser option not forwarded: %s", text)+ }+}+func TestHandleScrapeMissingURL(t *testing.T) {srv := mockPinchTab()defer srv.Close()