Skip to content

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

feat: add target-aware browser orchestration

Luigi Agosti0116638085c9
diff --git a/Dockerfile b/Dockerfile
index a73c69f6..59a9ddc3 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -35,7 +35,16 @@ FROM alpine:3.23
LABEL org.opencontainers.image.source="https://github.com/pinchtab/pinchtab"
LABEL org.opencontainers.image.description="High-performance browser automation bridge"
-# Chromium and its runtime dependencies for headless operation
+# Chromium and its runtime dependencies for headless operation.
+#
+# This image is intentionally headless-only: no X11, Wayland, Xvfb, or display
+# server packages are installed. Headed mode (a visible browser window) is not
+# supported inside this image and PinchTab will refuse / fail to launch headed
+# instances here. Keeping the image headless-only keeps it small, CI-friendly,
+# and avoids dragging in a graphical stack that has no use in containers.
+#
+# For manual local headed workflows on a developer workstation see
+# docs/guides/headed-mode.md.
RUN apk add --no-cache \
chromium \
nss \
diff --git a/README.md b/README.md
index e83ec574..85f9221e 100644
--- a/README.md
+++ b/README.md
@@ -161,6 +161,7 @@ Most users should not need to think about `pinchtab bridge` directly, and only n
- **Self-contained** — ~15MB binary, no external dependencies
- **Accessibility-first** — Stable element refs instead of fragile coordinates
- **ARM64-optimized** — First-class Raspberry Pi support with automatic Chromium detection
+- **CloakBrowser support** — Optional drop-in provider for sites that fingerprint stock Chromium. PinchTab launches a user-supplied CloakBrowser binary; no CloakBrowser is bundled in released artifacts. See [docs/guides/cloakbrowser.md](docs/guides/cloakbrowser.md).
---
@@ -405,6 +406,15 @@ cd pinchtab
go build ./cmd/pinchtab # Build pinchtab binary
```
+For runtime diagnostics against your installed PinchTab + browser config (binary exists, executes, fingerprint flags accepted, CDP reachable), use:
+
+```bash
+pinchtab doctor # human-readable report
+pinchtab doctor --json # machine-readable
+pinchtab doctor --target <name> # scope to one browser.targets entry
+pinchtab doctor --check <name> # run a single check by name
+```
+
---
## License
diff --git a/cmd/pinchtab/cmd_bridge.go b/cmd/pinchtab/cmd_bridge.go
index 6561be03..30508ed8 100644
--- a/cmd/pinchtab/cmd_bridge.go
+++ b/cmd/pinchtab/cmd_bridge.go
@@ -2,22 +2,38 @@ package main
import (
"fmt"
+ "net/url"
"strings"
+ "github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/server"
"github.com/spf13/cobra"
)
var (
- bridgeEngine string
- bridgeCDPAttach string
- bridgeBind string
- bridgePort string
+ bridgeEngine string
+ bridgeCDPAttach string
+ bridgeBrowserProvider string
+ bridgeRemoteBrowserName string
+ bridgeBind string
+ bridgePort string
)
var bridgeCmd = &cobra.Command{
Use: "bridge",
Short: "Start single-instance bridge-only server",
+ Long: `Start a single-instance bridge server.
+
+By default, the bridge launches Chrome itself. Use --cdp-attach to attach the
+bridge to an already-running browser process (Chrome or CloakBrowser) via
+its remote debugging URL — the external process is never killed by PinchTab.
+
+Examples:
+ pinchtab bridge
+ pinchtab bridge --cdp-attach ws://127.0.0.1:9222/devtools/browser/<id>
+ pinchtab bridge --cdp-attach http://127.0.0.1:9222 \
+ --browser-provider cloak --remote-browser-name cloak-manager-profile
+`,
RunE: func(cmd *cobra.Command, args []string) error {
cfg := loadConfig()
engineMode, err := resolveBridgeEngine(bridgeEngine, cfg.Engine)
@@ -26,7 +42,12 @@ var bridgeCmd = &cobra.Command{
}
cfg.Engine = engineMode
if v := strings.TrimSpace(bridgeCDPAttach); v != "" {
- cfg.CDPAttachURL = v
+ cdpURL, err := validateBridgeCDPURL(v)
+ if err != nil {
+ return err
+ }
+ cfg.CDPAttachURL = cdpURL
+ cfg.RemoteCDPURL = cdpURL
}
if v := strings.TrimSpace(bridgeBind); v != "" {
cfg.Bind = v
@@ -34,11 +55,54 @@ var bridgeCmd = &cobra.Command{
if v := strings.TrimSpace(bridgePort); v != "" {
cfg.Port = v
}
+
+ if v := strings.TrimSpace(bridgeBrowserProvider); v != "" {
+ provider, err := config.ParseBrowserProvider(v)
+ if err != nil {
+ return err
+ }
+ cfg.BrowserProvider = provider
+ }
+ if v := strings.TrimSpace(bridgeRemoteBrowserName); v != "" {
+ cfg.RemoteBrowserName = v
+ }
+
server.RunBridgeServer(cfg, version)
return nil
},
}
+func validateBridgeCDPURL(raw string) (string, error) {
+ trimmed := strings.TrimSpace(raw)
+ parsed, err := url.Parse(trimmed)
+ if err != nil {
+ return "", fmt.Errorf("invalid --cdp-attach %q: %w", raw, err)
+ }
+ if parsed.Scheme == "" {
+ return "", fmt.Errorf("invalid --cdp-attach %q: missing scheme", raw)
+ }
+ if parsed.Host == "" {
+ return "", fmt.Errorf("invalid --cdp-attach %q: missing host", raw)
+ }
+
+ switch strings.ToLower(parsed.Scheme) {
+ case "ws", "wss":
+ if strings.Contains(parsed.Path, "/devtools/page/") {
+ return "", fmt.Errorf("invalid --cdp-attach %q: page-level CDP URLs are not supported; use a browser-level URL", raw)
+ }
+ if !strings.Contains(parsed.Path, "/devtools/browser/") {
+ return "", fmt.Errorf("invalid --cdp-attach %q: expected browser-level path /devtools/browser/<id>", raw)
+ }
+ case "http", "https":
+ if parsed.Path != "" && parsed.Path != "/" && !strings.HasSuffix(parsed.Path, "/json/version") {
+ return "", fmt.Errorf("invalid --cdp-attach %q: HTTP URL must be the DevTools origin or /json/version", raw)
+ }
+ default:
+ return "", fmt.Errorf("invalid --cdp-attach %q: expected ws, wss, http, or https", raw)
+ }
+ return trimmed, nil
+}
+
func resolveBridgeEngine(flagValue, configValue string) (string, error) {
engineMode := strings.ToLower(strings.TrimSpace(configValue))
if strings.TrimSpace(flagValue) != "" {
@@ -56,8 +120,10 @@ func resolveBridgeEngine(flagValue, configValue string) (string, error) {
func init() {
bridgeCmd.GroupID = "primary"
bridgeCmd.Flags().StringVar(&bridgeEngine, "engine", "", "Bridge engine: chrome, lite, or auto (overrides config)")
- bridgeCmd.Flags().StringVar(&bridgeCDPAttach, "cdp-attach", "", "Attach to an existing Chrome via its browser-level CDP URL (e.g. ws://127.0.0.1:9222/devtools/browser/abc). Skips launching Chrome; the external Chrome is left alive on shutdown.")
+ bridgeCmd.Flags().StringVar(&bridgeCDPAttach, "cdp-attach", "", "Attach to an existing browser via this CDP URL (ws://... browser-level, or http://... DevTools origin)")
bridgeCmd.Flags().StringVar(&bridgeBind, "bind", "", "Bind address for the bridge HTTP server (overrides config server.bind)")
bridgeCmd.Flags().StringVar(&bridgePort, "port", "", "Port for the bridge HTTP server (overrides config server.port)")
+ bridgeCmd.Flags().StringVar(&bridgeBrowserProvider, "browser-provider", "", "Browser provider for remote attach: chrome or cloak (default: from config)")
+ bridgeCmd.Flags().StringVar(&bridgeRemoteBrowserName, "remote-browser-name", "", "Opaque label for the externally-managed browser; surfaces in /stealth/status")
rootCmd.AddCommand(bridgeCmd)
}
diff --git a/cmd/pinchtab/cmd_bridge_test.go b/cmd/pinchtab/cmd_bridge_test.go
index a9c789ca..e4f44aef 100644
--- a/cmd/pinchtab/cmd_bridge_test.go
+++ b/cmd/pinchtab/cmd_bridge_test.go
@@ -34,3 +34,32 @@ func TestResolveBridgeEngine(t *testing.T) {
})
}
}
+
+func TestValidateBridgeCDPURL(t *testing.T) {
+ tests := []struct {
+ name string
+ raw string
+ wantErr bool
+ }{
+ {name: "browser websocket", raw: "ws://127.0.0.1:9222/devtools/browser/abc"},
+ {name: "http origin", raw: "http://127.0.0.1:9222"},
+ {name: "json version", raw: "https://cdp.example/json/version"},
+ {name: "page websocket rejected", raw: "ws://127.0.0.1:9222/devtools/page/abc", wantErr: true},
+ {name: "websocket without browser path rejected", raw: "ws://127.0.0.1:9222", wantErr: true},
+ {name: "missing scheme rejected", raw: "127.0.0.1:9222", wantErr: true},
+ {name: "unsupported scheme rejected", raw: "ftp://127.0.0.1:9222", wantErr: true},
+ {name: "bad http path rejected", raw: "http://127.0.0.1:9222/devtools/page/abc", wantErr: true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ _, err := validateBridgeCDPURL(tt.raw)
+ if tt.wantErr && err == nil {
+ t.Fatal("expected error")
+ }
+ if !tt.wantErr && err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ })
+ }
+}
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
index 5c199a5f..fcacdd23 100644
--- a/cmd/pinchtab/cmd_cli_register.go
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -500,6 +500,8 @@ func configureManagementFlags() {
startInstanceCmd.Flags().String("port", "", "Port number")
startInstanceCmd.Flags().StringArray("extension", nil, "Load browser extension (repeatable)")
startInstanceCmd.Flags().StringArray("allow-domain", nil, "Add an instance-scoped IDPI allowed domain (repeatable)")
+ startInstanceCmd.Flags().String("browser", "", "Named browser target to use (e.g. chrome, cloak)")
+ startInstanceCmd.Flags().StringArray("browser-fallback", nil, "Named browser target to fall back to if the primary fails (repeatable; overrides config browser.fallbackOrder)")
activityCmd.PersistentFlags().Int("limit", 200, "Maximum number of events to return")
activityCmd.PersistentFlags().Int("age-sec", 0, "Only include events from the last N seconds")
diff --git a/cmd/pinchtab/cmd_doctor.go b/cmd/pinchtab/cmd_doctor.go
new file mode 100644
index 00000000..83eb28c4
--- /dev/null
+++ b/cmd/pinchtab/cmd_doctor.go
@@ -0,0 +1,100 @@
+package main
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/doctor"
+ "github.com/spf13/cobra"
+)
+
+var (
+ doctorJSON bool
+ doctorTarget string
+ doctorCheck string
+)
+
+var doctorCmd = &cobra.Command{
+ Use: "doctor",
+ Short: "Run discovery and health checks against the configured browser",
+ Long: `Run a series of read-only diagnostic checks against the current
+PinchTab configuration. Initially focused on CloakBrowser discovery
+(binary exists, executes, exposes CDP, accepts fingerprint flags),
+but the framework is provider-neutral.
+
+The doctor command does not require a running PinchTab server. It works
+directly against the on-disk config and may launch a short-lived browser
+subprocess (which is always torn down).
+
+Exit codes:
+ 0 all checks passed or were skipped
+ 1 at least one check failed
+ 2 usage or setup error (e.g. config could not be loaded)`,
+ Example: ` pinchtab doctor
+ pinchtab doctor --json
+ pinchtab doctor --target cloak-eu
+ pinchtab doctor --check binary_exists`,
+ RunE: runDoctor,
+ SilenceUsage: true,
+ SilenceErrors: true,
+}
+
+func runDoctor(cmd *cobra.Command, _ []string) error {
+ cfg, err := loadDoctorConfig()
+ if err != nil {
+ return newCommandExitError(2, fmt.Errorf("pinchtab doctor: %w", err))
+ }
+
+ target := strings.TrimSpace(doctorTarget)
+ check := strings.TrimSpace(doctorCheck)
+
+ if target != "" {
+ resolved, err := config.ResolveExplicitBrowserTarget(cfg, target)
+ if err != nil {
+ return newCommandExitError(2, fmt.Errorf("pinchtab doctor: %w", err))
+ }
+ cfg = resolved.Config
+ }
+
+ if check != "" {
+ if !doctor.KnownCheck(cfg, check) {
+ return newCommandExitError(2, fmt.Errorf("pinchtab doctor: unknown check %q for provider=%s", check, cfg.BrowserProvider))
+ }
+ }
+
+ results := doctor.Run(cmd.Context(), cfg, check)
+ provider := config.NormalizeBrowserProvider(cfg.BrowserProvider)
+ out := cmd.OutOrStdout()
+
+ if doctorJSON {
+ if err := doctor.WriteJSON(out, provider, target, results); err != nil {
+ return fmt.Errorf("write json: %w", err)
+ }
+ } else {
+ doctor.WriteText(out, provider, target, results)
+ }
+
+ summary := doctor.Summarize(results)
+ code := doctor.ExitCode(summary)
+ if code != 0 {
+ return newCommandExitError(code, fmt.Errorf("pinchtab doctor: %d check(s) failed", summary.Failed))
+ }
+ return nil
+}
+
+func loadDoctorConfig() (*config.RuntimeConfig, error) {
+ cfg := config.Load()
+ if cfg == nil {
+ return nil, fmt.Errorf("no configuration found")
+ }
+ return cfg, nil
+}
+
+func init() {
+ doctorCmd.GroupID = "config"
+ doctorCmd.Flags().BoolVar(&doctorJSON, "json", false, "Emit machine-readable JSON")
+ doctorCmd.Flags().StringVar(&doctorTarget, "target", "", "Scope checks to a single browser.targets entry")
+ doctorCmd.Flags().StringVar(&doctorCheck, "check", "", "Run a single check by name (e.g. binary_exists)")
+ rootCmd.AddCommand(doctorCmd)
+}
diff --git a/cmd/pinchtab/cmd_doctor_test.go b/cmd/pinchtab/cmd_doctor_test.go
new file mode 100644
index 00000000..9e033c5b
--- /dev/null
+++ b/cmd/pinchtab/cmd_doctor_test.go
@@ -0,0 +1,117 @@
+package main
+
+import (
+ "bytes"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/spf13/cobra"
+)
+
+func TestRunDoctorReturnsUsageErrorWithoutMutatingTargetFlag(t *testing.T) {
+ writeDoctorTestConfig(t, func(fc *config.FileConfig) {
+ fc.Browser.Targets = config.BrowserTargetsConfig{
+ "chrome": {Provider: config.BrowserProviderChrome},
+ }
+ fc.Browser.DefaultTarget = "chrome"
+ })
+ restore := setDoctorGlobals(" missing ", " ", false)
+ t.Cleanup(restore)
+
+ var out bytes.Buffer
+ err := runDoctor(doctorTestCommand(&out), nil)
+ if err == nil {
+ t.Fatal("runDoctor() expected error")
+ }
+ if got := commandExitCode(err); got != 2 {
+ t.Fatalf("exit code = %d, want 2; err=%v", got, err)
+ }
+ if !strings.Contains(err.Error(), `target "missing" not found`) {
+ t.Fatalf("expected missing target error, got %q", err.Error())
+ }
+ if doctorTarget != " missing " {
+ t.Fatalf("doctorTarget mutated to %q", doctorTarget)
+ }
+ if doctorCheck != " " {
+ t.Fatalf("doctorCheck mutated to %q", doctorCheck)
+ }
+}
+
+func TestRunDoctorReturnsUsageErrorWithoutMutatingCheckFlag(t *testing.T) {
+ writeDoctorTestConfig(t, nil)
+ restore := setDoctorGlobals("", " nope ", false)
+ t.Cleanup(restore)
+
+ var out bytes.Buffer
+ err := runDoctor(doctorTestCommand(&out), nil)
+ if err == nil {
+ t.Fatal("runDoctor() expected error")
+ }
+ if got := commandExitCode(err); got != 2 {
+ t.Fatalf("exit code = %d, want 2; err=%v", got, err)
+ }
+ if !strings.Contains(err.Error(), `unknown check "nope"`) {
+ t.Fatalf("expected unknown check error, got %q", err.Error())
+ }
+ if doctorCheck != " nope " {
+ t.Fatalf("doctorCheck mutated to %q", doctorCheck)
+ }
+}
+
+func TestRunDoctorReturnsFailureCodeWithoutExiting(t *testing.T) {
+ missingBinary := filepath.Join(t.TempDir(), "missing-browser")
+ writeDoctorTestConfig(t, func(fc *config.FileConfig) {
+ fc.Browser.ChromeBinary = missingBinary
+ })
+ restore := setDoctorGlobals("", "binary_exists", false)
+ t.Cleanup(restore)
+
+ var out bytes.Buffer
+ err := runDoctor(doctorTestCommand(&out), nil)
+ if err == nil {
+ t.Fatal("runDoctor() expected error")
+ }
+ if got := commandExitCode(err); got != 1 {
+ t.Fatalf("exit code = %d, want 1; err=%v", got, err)
+ }
+ if !strings.Contains(out.String(), "binary_exists") {
+ t.Fatalf("expected doctor output to include binary_exists, got %q", out.String())
+ }
+ if doctorCheck != "binary_exists" {
+ t.Fatalf("doctorCheck mutated to %q", doctorCheck)
+ }
+}
+
+func writeDoctorTestConfig(t *testing.T, mutate func(*config.FileConfig)) {
+ t.Helper()
+ configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+
+ fc := config.DefaultFileConfig()
+ if mutate != nil {
+ mutate(&fc)
+ }
+ if err := config.SaveFileConfig(&fc, configPath); err != nil {
+ t.Fatalf("SaveFileConfig() error = %v", err)
+ }
+}
+
+func setDoctorGlobals(target, check string, json bool) func() {
+ oldTarget, oldCheck, oldJSON := doctorTarget, doctorCheck, doctorJSON
+ doctorTarget = target
+ doctorCheck = check
+ doctorJSON = json
+ return func() {
+ doctorTarget = oldTarget
+ doctorCheck = oldCheck
+ doctorJSON = oldJSON
+ }
+}
+
+func doctorTestCommand(out *bytes.Buffer) *cobra.Command {
+ cmd := &cobra.Command{}
+ cmd.SetOut(out)
+ return cmd
+}
diff --git a/cmd/pinchtab/root.go b/cmd/pinchtab/root.go
index 411bc9c6..44272542 100644
--- a/cmd/pinchtab/root.go
+++ b/cmd/pinchtab/root.go
@@ -2,6 +2,7 @@ package main
import (
"encoding/json"
+ "errors"
"fmt"
"net/http"
"os"
@@ -185,10 +186,45 @@ func Execute() {
safelog.InstallDefault()
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
- os.Exit(1)
+ os.Exit(commandExitCode(err))
}
}
+type commandExitError struct {
+ code int
+ err error
+}
+
+func newCommandExitError(code int, err error) error {
+ return &commandExitError{code: code, err: err}
+}
+
+func (e *commandExitError) Error() string {
+ if e.err == nil {
+ return fmt.Sprintf("exit status %d", e.code)
+ }
+ return e.err.Error()
+}
+
+func (e *commandExitError) Unwrap() error {
+ return e.err
+}
+
+func (e *commandExitError) ExitCode() int {
+ return e.code
+}
+
+func commandExitCode(err error) int {
+ if err == nil {
+ return 0
+ }
+ var coded *commandExitError
+ if errors.As(err, &coded) {
+ return coded.ExitCode()
+ }
+ return 1
+}
+
// serverURL is the global --server flag for CLI commands
var serverURL string
var cliAgentID string
diff --git a/dashboard/src/generated/types.ts b/dashboard/src/generated/types.ts
index 57086afe..445ee286 100644
--- a/dashboard/src/generated/types.ts
+++ b/dashboard/src/generated/types.ts
@@ -52,6 +52,17 @@ export interface Instance {
attachType?: string;
cdpUrl?: string; // CDP WebSocket URL (for CDP-attached instances)
securityPolicy?: SecurityPolicy;
+ /**
+ * BrowserTarget is the resolved named target; empty on legacy configs.
+ */
+ browserTarget?: string;
+ browserProvider?: string;
+ /**
+ * FallbackFrom/FallbackReason are reserved for a future phase (always
+ * empty in P2.4a).
+ */
+ fallbackFrom?: string;
+ fallbackReason?: string;
}
/**
* Agent represents a connected AI agent.
diff --git a/dev b/dev
index cc154e0f..f097b1e1 100755
--- a/dev
+++ b/dev
@@ -26,10 +26,10 @@ COMMANDS=(
"test unit:🔬:Go unit tests"
"test dashboard:🔬:Dashboard unit tests"
"test plugin:🔬:Plugin unit tests"
- "e2e:🐳:E2E suites"
+ "e2e:🐳:E2E suites (add --provider=chrome|cloak to swap browser; default chrome)"
" basic:🐳:Basic suite (api + cli + infra)"
" extended:🐳:Extended suite (all extended)"
- " smoke:🐳:Smoke suite with Docker checks"
+ " smoke:🐳:Alias for smoke ci (CI-backed subset)"
" smoke-plugin:🐳:OpenClaw plugin Docker smoke"
" api:🐳:API basic tests"
" cli:🐳:CLI basic tests"
@@ -39,8 +39,11 @@ COMMANDS=(
" cli-extended:🐳:CLI extended tests"
" infra-extended:🐳:Infra extended (multi-instance)"
" test <name>:🐳:Run a single E2E test by start_test name"
- "smoke:💨:Manual smoke checks"
- " cloakbrowser:💨:CloakBrowser Docker image smoke"
+ "smoke:💨:All local smoke checks (use --provider=chrome|cloak|all or filter names)"
+ " ci:💨:CI-backed smoke subset only"
+ " cloakbrowser:💨:Browser parity / CloakBrowser smoke"
+ " cdp-attach:💨:CDP attach smoke"
+ " live-detection:💨:Advisory live detection-site probe (external network)"
"opt:⚡:Optimization baseline"
" baseline:⚡:Run optimization baseline lane"
"bench:📊:Benchmark lanes"
@@ -50,7 +53,7 @@ COMMANDS=(
"doctor:🩺:Setup dev environment"
"zombie:🧟:Run long Docker zombie-process soak smoke"
"install:📦:Build & install to ~/.local/bin (override with PINCHTAB_INSTALL_DIR)"
- " skills:📦:Symlink ./skills/* into ~/.claude/skills (override with CLAUDE_SKILLS_DIR)"
+ " skills:📦:Symlink ./skills/* into ./.claude/skills (override with CLAUDE_SKILLS_DIR)"
"pack plugin:🎁:Build a ClawHub-ready plugin tarball (optionally pass <version>)"
"check go:🧪:Go only"
"check dashboard:🧪:Dashboard only"
@@ -259,23 +262,14 @@ run_command() {
local bench_args="${target#bench }"
exec bash scripts/dev-bench.sh ${bench_args}
;;
- "smoke")
- echo " ${ACCENT}${BOLD}💨 Manual smoke checks${NC}"
- echo ""
- echo " Usage:"
- echo " ./dev smoke cloakbrowser [pinchtab-image]"
- echo ""
- echo " ${MUTED}CloakBrowser smoke checks are opt-in and Docker-backed. By default this builds pinchtab-cloakbrowser:test from tests/tools/docker/cloakbrowser-smoke.Dockerfile.${NC}"
- exit 1
- ;;
- "smoke cloakbrowser"|"smoke cloakbrowser "*)
- echo " ${ACCENT}${BOLD}💨 CloakBrowser Docker smoke${NC}"
+ "smoke"|"smoke "*)
+ echo " ${ACCENT}${BOLD}💨 Smoke${NC}"
echo ""
local -a smoke_args=()
- if [ "$target" != "smoke cloakbrowser" ]; then
- read -r -a smoke_args <<< "${target#smoke cloakbrowser }"
+ if [ "$target" != "smoke" ]; then
+ read -r -a smoke_args <<< "${target#smoke }"
fi
- exec bash scripts/docker-cloakbrowser-smoke.sh "${smoke_args[@]}"
+ exec bash scripts/dev-smoke.sh "${smoke_args[@]}"
;;
"e2e test")
echo " ${ERROR}Missing test name. Usage: dev e2e test \"<name substring>\"${NC}"
@@ -296,6 +290,15 @@ run_command() {
fi
exec bash tests/manual/openclaw-plugin-smoke/run.sh "${smoke_args[@]}"
;;
+ "e2e smoke"|"e2e smoke "*)
+ echo " ${ACCENT}${BOLD}🐳 E2E smoke moved to ./dev smoke ci${NC}"
+ echo ""
+ local -a smoke_args=()
+ if [ "$target" != "e2e smoke" ]; then
+ read -r -a smoke_args <<< "${target#e2e smoke }"
+ fi
+ exec bash scripts/dev-smoke.sh ci "${smoke_args[@]}"
+ ;;
"e2e"*)
local -a e2e_args=()
if [ "$target" != "e2e" ]; then
@@ -457,6 +460,12 @@ if [ $# -gt 0 ]; then
fi
;;
e2e)
+ if [ "${2:-}" = "smoke" ]; then
+ echo ""
+ echo " ${ACCENT}${BOLD}🐳 E2E smoke moved to ./dev smoke ci${NC}"
+ echo ""
+ exec bash scripts/dev-smoke.sh ci "${@:3}"
+ fi
if [ "${2:-}" = "test" ]; then
if [ $# -lt 3 ] || [ -z "${3:-}" ]; then
echo " ${ERROR}Missing test name. Usage: dev e2e test \"<name substring>\"${NC}" >&2
diff --git a/docs/architecture/browser-abstraction.md b/docs/architecture/browser-abstraction.md
new file mode 100644
index 00000000..fa47f06f
--- /dev/null
+++ b/docs/architecture/browser-abstraction.md
@@ -0,0 +1,218 @@
+# Browser Abstraction
+
+Status: proposed
+Owner: bridge
+Related: [browser-targets.md](browser-targets.md)
+
+## Problem
+
+Adding a new browser (e.g. lightpanda, brave, firefox) requires editing at least five unrelated files. Provider-specific logic is scattered across `config/`, `bridge/runtime/`, `browserprobe/`, and `doctor/`, coupled by string switches on `NormalizeBrowserProvider()` and predicates like `IsCloakBrowserProvider()`.
+
+Current branch points:
+
+| Concern | Location | Mechanism |
+|---|---|---|
+| Launch flags | `internal/bridge/runtime/init.go` | `IsCloakBrowserProvider()` gate + `CloakBrowserFlagArgs()` |
+| Geo alignment | `internal/bridge/runtime/geo_align.go` | `switch NormalizeBrowserProvider(...)` |
+| Binary discovery | `internal/browserprobe/binary.go` | Parallel `DiscoverChromeBinary`, `DiscoverCloakBrowserBinary` |
+| Doctor registry | `internal/doctor/runner.go` | `if IsCloakBrowserProvider()` adds checks |
+| Config validation | `internal/config/browser_targets.go` | Hardcoded `{chrome, cloak}` allowlist |
+
+`Engine` (`chrome` / `lite` / `auto`) and `Capabilities` are additional concepts layered on top, partially wired.
+
+## Goal
+
+A new browser implementation should be added by:
+
+1. Creating one sub-package under `internal/browsers/<id>/`.
+2. Registering it via `browsers.Register(...)`.
+
+No edits to bridge, doctor, validator, or geo dispatch.
+
+## Design
+
+### Package layout
+
+```
+internal/browsers/
+ browser.go // Browser interface + registry
+ config.go // LaunchConfig, GeoConfig, TargetConfig (provider-neutral)
+ capabilities.go // CapabilitySet (moved from config/)
+ common/ // shared chrome-family helpers (proxy auth, profile, CDP url discovery)
+ chrome/ // chrome implementation, registers itself
+ cloak/ // cloak implementation, composes chrome
+ lightpanda/ // future
+ brave/ // future
+```
+
+`browserprobe/`, `bridge/runtime/init.go` provider branches, and `doctor` provider gates are removed in favor of delegating to the registered `Browser`.
+
+### Interface
+
+```go
+package browsers
+
+type Browser interface {
+ ID() string // "chrome", "cloak", "lightpanda"
+ DisplayName() string // human-readable
+ Capabilities() CapabilitySet
+
+ // Discovery & doctor
+ DiscoverBinary() BinaryDiscovery
+ DoctorChecks(cfg TargetConfig) []doctor.Check
+
+ // Launch
+ BuildLaunchArgs(cfg LaunchConfig) (args []string, env []string, err error)
+ SupportsRemoteCDP() bool
+
+ // Strategy hooks
+ GeoAlignment(geo GeoConfig) GeoStrategy
+ ValidateTarget(cfg TargetConfig) error
+}
+
+type GeoStrategy struct {
+ Flags []string
+ Env []string
+ OperatorWins bool // explicit user config overrides geo-derived values
+}
+
+var registry = map[string]Browser{}
+
+func Register(b Browser) { registry[b.ID()] = b }
+func Get(id string) (Browser, bool) { b, ok := registry[id]; return b, ok }
+func IDs() []string { /* sorted list */ }
+```
+
+Each implementation registers in its package `init()`:
+
+```go
+// internal/browsers/chrome/chrome.go
+func init() { browsers.Register(&Browser{}) }
+```
+
+Importers wire providers via a barrel file (e.g. `internal/browsers/all/all.go`) so callers get all built-ins with one blank import.
+
+### Engine as a launch mode, not a provider axis
+
+`Engine` becomes a field on `LaunchConfig`:
+
+```go
+type LaunchConfig struct {
+ Mode LaunchMode // "chrome" | "lite" | "auto"
+ Binary string
+ UserDir string
+ Proxy ProxyConfig
+ ExtraFlags []string
+ // ...
+}
+```
+
+- `chrome`: full headful Chromium.
+- `lite`: headless + lightweight flags (`--disable-gpu`, `--disable-extensions`, etc.).
+- `auto`: resolved by the `Browser` via `Capabilities()` + workload hints.
+
+A provider may reject a mode it cannot serve (e.g. a future `lightpanda` rejects `chrome` mode).
+
+### Cloak as composition over Chrome
+
+Cloak is Chrome plus stealth flags and stricter geo precedence. Don't duplicate — embed:
+
+```go
+// internal/browsers/cloak/cloak.go
+type Browser struct{ chrome.Browser }
+
+func (b Browser) ID() string { return "cloak" }
+func (b Browser) DisplayName() string { return "CloakBrowser" }
+
+func (b Browser) BuildLaunchArgs(cfg browsers.LaunchConfig) ([]string, []string, error) {
+ args, env, err := b.Browser.BuildLaunchArgs(cfg)
+ if err != nil { return nil, nil, err }
+ return append(args, cloakFlagArgs(cfg)...), env, nil
+}
+
+func (b Browser) GeoAlignment(geo browsers.GeoConfig) browsers.GeoStrategy {
+ s := cloakGeoFlags(geo)
+ s.OperatorWins = true // explicit user config wins
+ return s
+}
+
+func (b Browser) DiscoverBinary() browsers.BinaryDiscovery {
+ return discoverCloakBinary() // separate paths from chrome
+}
+```
+
+### Doctor
+
+`doctor/runner.go` becomes a thin orchestrator:
+
+```go
+func Registry(cfg config.Config) []Check {
+ base := []Check{configFileCheck, binaryExistsCheck, binaryExecutableCheck, binaryStartsCheck}
+ for _, id := range browsers.IDs() {
+ b, _ := browsers.Get(id)
+ base = append(base, b.DoctorChecks(cfg.ResolveTarget())...)
+ }
+ return base
+}
+```
+
+Provider-specific checks (`cdp_reachable`, `fingerprint_flags_accepted`, `linux_fonts_present`) move into `browsers/cloak/doctor.go`.
+
+### Config validation
+
+`browser_targets.go` replaces its hardcoded allowlist with:
+
+```go
+if _, ok := browsers.Get(target.Provider); !ok {
+ return fmt.Errorf("unknown browser provider %q (known: %v)", target.Provider, browsers.IDs())
+}
+return browsers.MustGet(target.Provider).ValidateTarget(target)
+```
+
+### Bridge integration
+
+`bridge/runtime/init.go` no longer branches on provider. It resolves the `Browser` once, then delegates:
+
+```go
+b, ok := browsers.Get(cfg.Provider)
+if !ok { return fmt.Errorf("unsupported provider %q", cfg.Provider) }
+
+args, env, err := b.BuildLaunchArgs(launchCfg)
+geo := b.GeoAlignment(geoCfg)
+// apply args + env + geo.Flags + geo.Env
+```
+
+`InitRemoteCDP` checks `b.SupportsRemoteCDP()` before attaching.
+
+## Migration plan
+
+Extract-then-rewire. Each step lands independently with no behavior change.
+
+1. **Skeleton.** Add `internal/browsers/` with the interface, registry, and empty `chrome` package. Wire a barrel import in one place (`cmd/pinchtab/root.go`). No call sites change yet.
+2. **Chrome extraction.** Move `DiscoverChromeBinary`, chrome flag builders, chrome geo logic into `browsers/chrome/`. Old call sites delegate to `browsers.Get("chrome")`. Tests stay green.
+3. **Cloak extraction.** Move stealth flag builder, cloak geo, cloak binary discovery into `browsers/cloak/` as composition over chrome. Remove `IsCloakBrowserProvider()` callers one at a time.
+4. **Doctor migration.** Move provider-specific checks into `browsers/{chrome,cloak}/doctor.go`. `doctor/runner.go` collapses to a registry walk.
+5. **Geo migration.** Replace `geo_align.go` switch with `b.GeoAlignment(...)` call. Delete `geo_align.go` body.
+6. **Validator migration.** Replace `browser_targets.go` allowlist with `browsers.Get(...)` check.
+7. **Engine integration.** Wire `LaunchMode` through `LaunchConfig`. `auto` resolution lives in the registry or a small helper.
+8. **Validation by stub.** Add `browsers/lightpanda/` that registers but only stubs `BuildLaunchArgs` (returns "not implemented"). If wiring it requires editing anything outside `browsers/lightpanda/`, the abstraction has leaked — fix before merging.
+
+## Non-goals
+
+- Replacing chromedp / CDP client choice.
+- Per-target capability gating at the action layer. Capabilities stay advisory.
+- Sandboxing or process-isolation changes.
+- Cross-provider profile interop.
+
+## Open questions
+
+1. **Shared chrome-family code.** Cloak, Brave, and lightpanda-with-chromium-mode all share most flag building. Lives in `browsers/common/` or as exported helpers on `chrome.Browser`? Lean toward exporting from `chrome` to avoid a third package.
+2. **Doctor check identity.** Today checks have stable string IDs used by CI. Moving them into provider packages must preserve IDs. Audit before step 4.
+3. **Geo `OperatorWins` semantics.** Currently encoded implicitly in cloak geo. Lift to an explicit field as proposed, or keep inside the strategy's flag list?
+4. **Engine `auto`.** Resolved by the provider, or by a registry helper using `Capabilities()`? Probably the latter so policy stays in one place.
+
+## Out of scope for v1
+
+- Brave, Firefox, lightpanda actual implementations.
+- WebDriver fallback for non-CDP browsers.
+- Per-provider telemetry namespacing.
diff --git a/docs/architecture/browser-targets.md b/docs/architecture/browser-targets.md
index 91d9521d..7206799c 100644
--- a/docs/architecture/browser-targets.md
+++ b/docs/architecture/browser-targets.md
@@ -41,17 +41,15 @@ Example:
{
"browser": {
"defaultTarget": "chrome-local",
- "fallbackOrder": ["cloak-primary", "chrome-local"],
+ "fallbackOrder": ["cloak-primary"],
"targets": {
"chrome-local": {
"provider": "chrome",
- "binary": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
- "modes": ["headless", "headed"]
+ "binary": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
},
"cloak-primary": {
"provider": "cloak",
"binary": "/opt/cloakbrowser/chrome",
- "modes": ["headless"],
"cloak": {
"fingerprintSeed": "42069",
"platform": "linux",
@@ -59,15 +57,6 @@ Example:
"timezone": "UTC",
"disableDefaultStealthArgs": true
}
- },
- "lightpanda-fast": {
- "provider": "lightpanda",
- "binary": "/usr/local/bin/lightpanda",
- "modes": ["headless"],
- "capabilityOverrides": {
- "extensions": false,
- "pdf": false
- }
}
}
}
@@ -80,7 +69,8 @@ Rules:
- Target names are stable API identifiers. They must be lowercase, URL-safe,
and not derived from binary paths.
- `browser.fallbackOrder` is optional. If absent, fallback is disabled unless a
- request supplies an explicit fallback list.
+ request supplies an explicit fallback list. It must not repeat targets or
+ include `browser.defaultTarget`.
- Current `browser.provider`, `browser.binary`, `browser.extraFlags`, and
`browser.cloak` remain valid and are interpreted as `browser.targets.default`
during config load.
@@ -221,7 +211,6 @@ Capability resolution:
- Provider adapters expose default capabilities.
- Runtime probes can downgrade capabilities when a binary is missing a feature.
-- `capabilityOverrides` can disable capabilities for a target.
- Endpoint handlers declare required capabilities.
- If the selected target lacks a required capability, return `409
browser_capability_unsupported` unless fallback is enabled and another target
diff --git a/docs/guides/attach-chrome.md b/docs/guides/attach-chrome.md
index a7d49b31..6886ae85 100644
--- a/docs/guides/attach-chrome.md
+++ b/docs/guides/attach-chrome.md
@@ -36,7 +36,12 @@ With attach:
The current codebase implements:
-- `POST /instances/attach`
+- `POST /instances/attach` — starts a child `pinchtab bridge --cdp-attach ...`
+ process that wraps the external browser. The bridge speaks the normal
+ PinchTab HTTP API; the orchestrator registers the bridge's HTTP URL (not
+ the raw `ws://` CDP URL) as the routable instance URL.
+- `POST /instances/attach-bridge` — registers an already-running PinchTab
+ bridge as an instance (unchanged).
- attach policy in config under `security.attach`
- attached-instance metadata in `GET /instances`
@@ -45,10 +50,25 @@ The attach request body is:
```json
{
"name": "shared-chrome",
- "cdpUrl": "ws://127.0.0.1:9222/devtools/browser/..."
+ "cdpUrl": "ws://127.0.0.1:9222/devtools/browser/...",
+ "provider": "chrome",
+ "browserTarget": "chrome-local"
}
```
+`browserTarget` is optional. When `browser.targets` is configured, an omitted
+value attaches to the configured default target and the target provider is used.
+If you also pass `provider`, it must match that target. Without browser targets,
+`provider` defaults to `chrome`; use `cloak` for a CloakBrowser endpoint.
+
+Accepted `cdpUrl` shapes:
+
+- browser-level WebSocket URL: `ws://host:port/devtools/browser/<id>`
+- HTTP DevTools origin: `http://host:port` (resolved through `/json/version`)
+- HTTP `/json/version` URL
+
+Page-level URLs (`/devtools/page/...`) are rejected.
+
There is currently no CLI attach command.
---
@@ -65,7 +85,8 @@ Example:
"attach": {
"enabled": true,
"allowHosts": ["127.0.0.1", "localhost", "::1"],
- "allowSchemes": ["ws", "wss"]
+ "allowSchemes": ["ws", "wss"],
+ "forwardProxyAuth": false
}
}
}
@@ -122,7 +143,8 @@ curl -X POST http://localhost:9867/instances/attach \
-H "Content-Type: application/json" \
-d '{
"name": "shared-chrome",
- "cdpUrl": "ws://127.0.0.1:9222/devtools/browser/abc123"
+ "cdpUrl": "ws://127.0.0.1:9222/devtools/browser/abc123",
+ "browserTarget": "chrome-local"
}'
# Response
{
@@ -134,7 +156,9 @@ curl -X POST http://localhost:9867/instances/attach \
"headless": false,
"status": "running",
"attached": true,
- "cdpUrl": "ws://127.0.0.1:9222/devtools/browser/abc123"
+ "cdpUrl": "ws://127.0.0.1:9222/devtools/browser/abc123",
+ "browserTarget": "chrome-local",
+ "browserProvider": "chrome"
}
```
@@ -163,18 +187,24 @@ An attached instance appears in the normal instance list with:
## Ownership and lifecycle
-Attached instances are externally owned.
+Attached instances are externally owned, but PinchTab still owns a *bridge
+wrapper* around them.
That means:
- PinchTab did not launch the browser
-- PinchTab stores metadata about that browser as an instance
-- the external Chrome process remains outside PinchTab lifecycle ownership
+- PinchTab spawned a child `pinchtab bridge --cdp-attach ...` process that wraps
+ the external CDP endpoint and serves normal PinchTab routes
+- the external Chrome/CloakBrowser process remains outside PinchTab lifecycle
+ ownership
In practical terms:
-- stopping the attached instance in PinchTab unregisters it from the server
-- it does not imply that PinchTab launched or can fully manage the external Chrome process
+- `POST /instances/{id}/stop` shuts down the child PinchTab bridge — the
+ external Chrome process is **left running**
+- routes like `/tabs`, `/snapshot`, `/action`, `/screenshot` go to the child
+ bridge, which talks CDP to the external browser through a
+ `chromedp.NewRemoteAllocator`
---
@@ -198,6 +228,7 @@ Recommended rules:
- leave attach disabled unless you need it
- keep `allowHosts` narrow
- keep `allowSchemes` narrow
+- leave `forwardProxyAuth` disabled unless the attached browser process and CDP transport are trusted
- set `PINCHTAB_TOKEN` when the server is reachable outside localhost
- only attach to CDP endpoints you trust
@@ -237,3 +268,15 @@ curl -X POST http://localhost:9867/instances/start \
# CLI Alternative
pinchtab instance start
```
+
+---
+
+## Related guides
+
+- [cloakbrowser.md](cloakbrowser.md) — full CloakBrowser configuration and
+ the `provider: cloak` attach variant
+- [docker.md](docker.md) — running PinchTab (and the local CloakBrowser
+ smoke image) in containers
+- [headed-mode.md](headed-mode.md) — manual headed setup outside the
+ bundled image
+- [security.md](security.md) — attach policy details, IDPI, token handling
diff --git a/docs/guides/cloakbrowser.md b/docs/guides/cloakbrowser.md
index 13d5389b..c79ce2f6 100644
--- a/docs/guides/cloakbrowser.md
+++ b/docs/guides/cloakbrowser.md
@@ -20,9 +20,9 @@ PinchTab can launch a user-installed CloakBrowser binary with:
- `/stealth/status` reporting for the active provider, native Cloak mode, and
PinchTab overlay status
-When CloakBrowser native stealth is enabled, PinchTab disables overlapping
-PinchTab JavaScript stealth overlays and automation-hiding launch flags by
-default. PinchTab still controls browser lifecycle, user data directories,
+When `browser.cloak.disableDefaultStealthArgs=true`, PinchTab disables its
+overlapping JavaScript stealth overlays and automation-hiding launch flags.
+PinchTab still controls browser lifecycle, user data directories,
headless/headed mode, remote debugging, tab limits, and action humanization.
PinchTab does not bundle CloakBrowser in release binaries, npm packages,
@@ -40,6 +40,22 @@ license. Do not vendor, copy, or redistribute that binary in PinchTab release
artifacts or public Docker images unless the license explicitly permits that
use.
+PinchTab's distribution policy for CloakBrowser is:
+
+- PinchTab does **not** bundle any CloakBrowser binary in released artifacts —
+ not in `./dev binaries`, not in the npm package, not in the Homebrew formula,
+ not in the published `pinchtab/pinchtab` or `ghcr.io/pinchtab/pinchtab`
+ Docker images.
+- Users supply their own CloakBrowser binary on disk and point
+ `browser.binary` (or `browser.targets.<name>.binary`) at it.
+- The local Docker file
+ `tests/tools/docker/cloakbrowser-smoke.Dockerfile` exists for local
+ smoke/test purposes only. It is not pushed to any registry and is not a
+ release artifact.
+- There is no public CloakBrowser-bundled PinchTab release image and no
+ hosted service. None are planned until redistribution, OEM, or SaaS terms
+ are clear with the upstream CloakBrowser maintainers.
+
The safe default is: install or download CloakBrowser yourself, then point
PinchTab at that local binary path.
@@ -166,6 +182,23 @@ pinchtab nav https://example.com --snap
If your security policy blocks public navigation, add the exact host to
`security.allowedDomains` before using a public URL.
+## Verify Configuration With `pinchtab doctor`
+
+Before starting the server, run the read-only diagnostic command. It checks the
+configured binary, executes it briefly, and validates fingerprint flags
+without mutating any state:
+
+```bash
+pinchtab doctor # human-readable report
+pinchtab doctor --json # machine-readable JSON
+pinchtab doctor --target cloak-eu # scope to one browser.targets entry
+pinchtab doctor --check binary_exists # run a single check by name
+```
+
+Exit codes: `0` all checks passed or skipped, `1` at least one check failed,
+`2` config or usage error. See the [Troubleshooting](#troubleshooting) section
+below for how to react to specific failures.
+
## Verify CloakBrowser Is Active
Check `/stealth/status` after the managed browser instance starts:
@@ -270,12 +303,188 @@ binary license explicitly permits redistribution for your use case.
Project maintainers can validate the Docker integration with:
```bash
-./dev smoke cloakbrowser
+./dev e2e --provider=cloak
+```
+
+That command swaps the runtime config to `browser.provider=cloak`
+(`/opt/cloakbrowser/chrome`, `fingerprintSeed=42069`,
+`disableDefaultStealthArgs=true`), reuses the prebuilt
+`pinchtab-cloakbrowser:test` image (build it once via
+`tests/tools/docker/cloakbrowser-smoke.Dockerfile` — the runner does not
+auto-build it), asserts `/stealth/status` reports
+`provider=cloak, native=true, pinchtabOverlaysDisabled=true,
+fingerprintSeed=42069`, and runs the full E2E suite against the cloak
+container.
+
+Use `./dev smoke --provider=cloak` for the full local CloakBrowser smoke set.
+Use `./dev smoke cloakbrowser` when you only need the specialized parity legs,
+including `--multi-target`, `--profile-persistence`, and
+`--profile-lock-recovery`.
+
+## Attaching a running CloakBrowser
+
+If CloakBrowser is already running with remote debugging enabled (for example,
+under CloakBrowser Manager), you can attach it to PinchTab through the normal
+CDP attach path. PinchTab spawns a child `pinchtab bridge --cdp-attach ...` wrapper
+around the external endpoint and exposes the standard API on a local port.
+
+```bash
+curl -X POST http://localhost:9867/instances/attach \
+ -H "Content-Type: application/json" \
+ -d '{
+ "name": "cloak-manager-profile",
+ "cdpUrl": "ws://127.0.0.1:9222/devtools/browser/abc123",
+ "provider": "cloak",
+ "browserTarget": "cloak-1"
+ }'
+```
+
+For a remote CloakBrowser attach:
+
+- `browserTarget` should name a CloakBrowser target when `browser.targets` is configured; if omitted, the configured default target is used
+- `provider` must be `cloak` when no browser target is configured, or must match the selected target when both fields are present
+- `/stealth/status` reports `provider=cloak`, `launchMode=remote-cdp`,
+ `native=true`, and `pinchtabOverlaysDisabled=true` — PinchTab does not inject
+ its JS fingerprint overlays, on the assumption the external browser owns
+ native fingerprint behavior
+- stopping the attached PinchTab instance shuts down the wrapper bridge only;
+ the external CloakBrowser process is left running
+
+The opt-in smoke `./dev smoke cdp-attach` exercises this path against a
+locally-built CloakBrowser image.
+
+## Troubleshooting
+
+Most CloakBrowser launch failures fall into one of the buckets below. Run
+`pinchtab doctor` first — it isolates the failure to a specific named check
+and removes the need to guess.
+
+### Missing binary
+
+Symptom: `pinchtab doctor` reports `binary_exists: FAIL`, or the server logs
+`stat /path/to/cloakbrowser/chrome: no such file or directory` when starting an
+instance.
+
+Fix: set `browser.binary` (or `browser.targets.<name>.binary` for named
+targets) to an absolute path that exists and is executable:
+
+```bash
+pinchtab config set browser.binary /absolute/path/to/cloakbrowser/chrome
+# or, for a named target:
+pinchtab config set browser.targets.cloak-eu.binary /absolute/path/to/cloakbrowser/chrome
+```
+
+PinchTab does not search `$PATH` for CloakBrowser. Use the absolute path
+reported by `python -m cloakbrowser info` or `cloakbrowser.binaryInfo()`.
+
+### Unsupported platform build
+
+Symptom: `pinchtab doctor` reports `binary_starts: FAIL` with a non-zero
+exit code, a segfault, or an `exec format error`.
+
+Fix: the CloakBrowser binary is platform-specific (CPU architecture and
+operating system). A Linux x86_64 binary will not run on macOS arm64 and vice
+versa. Reinstall CloakBrowser for the platform you are actually running on,
+and refer to the upstream CloakBrowser release notes for the matrix of
+supported builds.
+
+The PinchTab smoke image
+(`tests/tools/docker/cloakbrowser-smoke.Dockerfile`) is built for the host
+architecture; if you build it on arm64 and try to run the resulting image on
+x86_64 (or vice versa) the inner CloakBrowser binary will fail the same way.
+
+### Profile lock conflicts
+
+Symptom: launch fails with `profile in use`, or PinchTab logs a warning that
+the profile lock is held.
+
+PinchTab's stale-`SingletonLock` recovery (P3b) automatically removes the
+lock when the owning PID no longer exists:
+
+- if the lock points to a live non-PinchTab process, PinchTab refuses to
+ steal the profile and logs `chrome profile lock appears active and owned by another pinchtab; leaving singleton files in place`
+- if the lock points to a dead process, PinchTab logs `chrome profile lock appears active but pinchtab owner is dead` and cleans up the stale files
+- if the lock points to a live process owned by another PinchTab, PinchTab
+ refuses to steal it
+
+If recovery does not happen automatically, check the container or host
+logs for the `chrome profile lock appears active but pinchtab owner is dead`
+line:
+
+```bash
+docker logs pinchtab-cloak | grep "profile lock"
+```
+
+Manual recovery (only when you are sure no real CloakBrowser process is
+running against that profile):
+
+```bash
+rm -f /path/to/profile/{SingletonLock,SingletonCookie,SingletonSocket}
+```
+
+### Bad fingerprint / proxy / timezone combinations
+
+Symptom: target site flags the session as automated even though
+`/stealth/status` reports `provider=cloak, native=true`.
+
+CloakBrowser's fingerprint flags and proxy geo must be **coherent**. A US
+residential proxy paired with `cloak.timezone=Europe/London` and
+`cloak.locale=en-GB` looks suspicious to any detector that cross-checks
+client locale against egress IP. Align them:
+
+- match `browser.proxy.geo.timezone` to the proxy's actual location
+- match `browser.proxy.geo.locale` and `browser.cloak.locale`
+- match `browser.cloak.platform` to a believable device for the locale
+- if you set `browser.cloak.webrtcIP`, ensure it is not leaking the host's
+ real LAN range
+
+If you cannot set the proxy's geo by hand, leave the `browser.proxy.geo`
+block out and let PinchTab use the proxy without geo overrides — better to
+have a missing signal than a contradictory one.
+
+Proxy geo alignment is CloakBrowser-only. Plain Chrome targets keep their normal
+Chrome launch behavior and do not receive proxy-derived `--lang`, `TZ`, or
+WebRTC flags.
+
+### Detection sites still flagging automation
+
+Symptom: bot-detection demo pages (CreepJS, BrowserScan, Sannysoft, etc.)
+report a non-zero detection score even with CloakBrowser native stealth
+enabled.
+
+This is expected to vary. Detection score is a moving target: detector
+heuristics change outside PinchTab releases, CloakBrowser ships new patches,
+Chromium versions drift, and per-site signals evolve independently of any
+single component.
+
+To investigate, re-run the live-detection smoke against the configured
+provider:
+
+```bash
+./dev smoke live-detection # Chrome leg (baseline)
+./dev smoke live-detection --provider=chrome
+./dev smoke live-detection --provider=cloak
```
-That command builds the same dedicated local image, starts PinchTab with
-`browser.provider=cloak`, verifies `/stealth/status`, and runs the
-Cloak-compatible API scenario set against the container.
+The smoke captures per-site screenshots and an extracted summary into
+`./tests/e2e/results/live-detection/<provider>-<timestamp>/`. Compare the cloak run
+against the chrome baseline: a non-zero cloak score that matches the
+Chrome baseline indicates a generic Chromium signal, not a CloakBrowser
+regression. Re-run the smoke after upstream CloakBrowser or detector
+updates rather than treating one run as authoritative.
+
+Results from the live-detection smoke are advisory and never gate CI.
+
+## Related Guides
+
+- [docker.md](docker.md) — the local CloakBrowser smoke image and persistent
+ profile volume
+- [attach-chrome.md](attach-chrome.md) — attach to an externally managed
+ CloakBrowser via CDP
+- [headed-mode.md](headed-mode.md) — manual headed setup (the bundled and
+ smoke images are headless-only)
+- [security.md](security.md) — the underlying security model, attach policy,
+ IDPI, and token handling
## Security
diff --git a/docs/guides/contributing.md b/docs/guides/contributing.md
index 79580b8e..743e2de5 100644
--- a/docs/guides/contributing.md
+++ b/docs/guides/contributing.md
@@ -252,8 +252,9 @@ go test ./... -v -coverprofile=coverage.out
go tool cover -html=coverage.out # View coverage
./dev e2e # Run the default extended E2E suite
./dev e2e basic # Run API + CLI + Infra basic tests
-./dev e2e smoke # Run smoke scenarios + host Docker smoke checks
-./dev smoke cloakbrowser # Run opt-in CloakBrowser Docker smoke image
+./dev smoke ci # Run CI smoke scenarios + host Docker smoke checks
+./dev smoke # Run all local smoke categories
+./dev smoke --provider=cloak # Run all local CloakBrowser smoke categories
./dev e2e api # Run API basic tests
./dev e2e cli # Run CLI basic tests
./dev e2e infra # Run Infra basic tests
diff --git a/docs/guides/docker.md b/docs/guides/docker.md
index 4835314f..0a7cae4a 100644
--- a/docs/guides/docker.md
+++ b/docs/guides/docker.md
@@ -259,3 +259,88 @@ You can run orchestrator mode inside one container and start managed instances f
- restart behavior is easier to reason about
Choose based on whether you want container-level isolation or PinchTab-managed multi-instance orchestration.
+
+## CloakBrowser In Docker (local image only)
+
+The published `pinchtab/pinchtab` and `ghcr.io/pinchtab/pinchtab` images ship with stock Chromium. They do **not** include CloakBrowser, and PinchTab does not publish a CloakBrowser-bundled image. See [cloakbrowser.md → Licensing](cloakbrowser.md#licensing) for why.
+
+For local testing, the repository contains a self-built Dockerfile that layers CloakBrowser onto the PinchTab image. It is labelled "smoke" because it is intended for local smoke testing and parity validation only — not for distribution or production.
+
+### Build the local CloakBrowser smoke image
+
+```bash
+docker build \
+ -f tests/tools/docker/cloakbrowser-smoke.Dockerfile \
+ -t pinchtab-cloakbrowser:local \
+ .
+```
+
+This image is local-only:
+
+- it is not pushed to any registry
+- it is not produced by `./dev binaries`
+- `./dev smoke cloakbrowser` reuses it when present; set `SKIP_BUILD=0` or remove the image to force a rebuild
+
+### Run a CloakBrowser-backed container locally
+
+Create a config that points PinchTab at the in-image CloakBrowser binary:
+
+```json
+{
+ "server": {
+ "bind": "0.0.0.0",
+ "port": "9867",
+ "token": "replace-me",
+ "stateDir": "/data"
+ },
+ "browser": {
+ "provider": "cloak",
+ "binary": "/opt/cloakbrowser/chrome",
+ "cloak": {
+ "fingerprintSeed": "42069",
+ "platform": "linux",
+ "timezone": "UTC",
+ "locale": "en-US",
+ "disableDefaultStealthArgs": true
+ }
+ },
+ "instanceDefaults": {
+ "mode": "headless",
+ "humanize": true
+ },
+ "profiles": {
+ "baseDir": "/data/profiles",
+ "defaultProfile": "default"
+ }
+}
+```
+
+Run it with the config mounted read-only and a persistent profile volume:
+
+```bash
+docker run -d \
+ --name pinchtab-cloak \
+ -p 127.0.0.1:9867:9867 \
+ --shm-size=2g \
+ -v pinchtab-cloak-data:/data \
+ -v "$PWD/pinchtab-cloak.json":/config/pinchtab.json:ro \
+ -e PINCHTAB_CONFIG=/config/pinchtab.json \
+ pinchtab-cloakbrowser:local
+```
+
+The `pinchtab-cloak-data` named volume holds `/data/profiles` across container restarts, so CloakBrowser keeps cookies, local storage, and history between runs. Delete the volume to start clean:
+
+```bash
+docker volume rm pinchtab-cloak-data
+```
+
+### Headless-only design
+
+The smoke image follows the same headless-only design as the bundled `pinchtab/pinchtab` image: no X11, no Wayland, no Xvfb. Headed CloakBrowser inside Docker is not a supported configuration. If you need a visible browser window for debugging, run PinchTab + CloakBrowser directly on the host — see [headed-mode.md](headed-mode.md) for the manual local setup.
+
+### Related guides
+
+- [cloakbrowser.md](cloakbrowser.md) — full CloakBrowser configuration, fingerprint flags, and troubleshooting
+- [attach-chrome.md](attach-chrome.md) — attach to an externally managed CloakBrowser via CDP
+- [headed-mode.md](headed-mode.md) — manual headed setup outside the bundled image
+- [security.md](security.md) — security model for container and non-local deployments
diff --git a/docs/guides/headed-mode.md b/docs/guides/headed-mode.md
new file mode 100644
index 00000000..3cbdbc80
--- /dev/null
+++ b/docs/guides/headed-mode.md
@@ -0,0 +1,144 @@
+# Headed Mode (manual local only)
+
+PinchTab supports headed Chrome (a visible browser window) for local
+development, debugging, and human-in-the-loop workflows. See
+[Headless vs Headed](../headless-vs-headed.md) for the per-mode tradeoffs.
+
+This page is the operational guide for *running* headed mode. Headed mode is
+**manual-local-only**: PinchTab does not ship a supported path for headed mode
+in containers or CI.
+
+## Why the bundled Docker image is headless-only
+
+The standard PinchTab Docker image (built from the repo `Dockerfile`) installs
+Chromium without any X11 / Wayland / Xvfb packages. This is deliberate:
+
+- The image targets headless automation, agents, and CI.
+- Keeping the runtime free of a display stack keeps the image small, the
+ attack surface narrow, and the startup cost low.
+- Driving an X server from inside a container is fragile, host-specific, and
+ not something PinchTab will support as a first-class deployment target.
+
+If you try to launch a headed instance against the bundled image it will fail
+(no display, no X libraries). That is expected.
+
+If you need headed Chrome you must run PinchTab outside the image, or build
+your own image with an X stack and a display server — both treated as manual
+local workflows, not officially supported configurations.
+
+## Running headed mode
+
+### Linux native (recommended)
+
+Run PinchTab directly on a Linux desktop session.
+
+```bash
+export DISPLAY=:0
+pinchtab server &
+pinchtab instance start --mode headed
+```
+
+This is the simplest and most reliable headed setup. Wayland sessions usually
+work too because Chrome falls back to XWayland.
+
+### Linux over SSH with X forwarding
+
+```bash
+ssh -X user@workstation 'DISPLAY=:0 pinchtab instance start --mode headed'
+```
+
+Forwarding works but is laggy for interactive use; prefer running PinchTab on
+the workstation itself.
+
+### Docker with X11 forwarding (manual, Linux host only)
+
+Not supported out of the box, but achievable on a Linux host that already runs
+an X server. You must build your own image that adds the X client libraries
+Chromium needs, then forward the host's X socket:
+
+```bash
+# On the host, allow local containers to use the X server
+xhost +local:
+
+docker run --rm \
+ -e DISPLAY="$DISPLAY" \
+ -v /tmp/.X11-unix:/tmp/.X11-unix \
+ -p 9867:9867 \
+ your-pinchtab-image-with-x11
+```
+
+Caveats:
+
+- Linux hosts only — `xhost` and `/tmp/.X11-unix` do not exist as-is on
+ macOS or Windows hosts.
+- `xhost +local:` weakens X access control; restrict it to trusted users.
+- GPU acceleration, fonts, input devices, and clipboard integration are all
+ host-specific and may behave differently than a native session.
+- This is **not** the bundled image. You are responsible for the X stack you
+ add on top.
+
+### macOS via XQuartz
+
+XQuartz can host X clients on macOS, including Chromium running in a Linux
+container, but the experience is fragile:
+
+```bash
+# One-time: install XQuartz from https://www.xquartz.org/
+# In XQuartz preferences → Security: enable "Allow connections from network clients"
+open -a XQuartz
+xhost + 127.0.0.1
+
+docker run --rm \
+ -e DISPLAY=host.docker.internal:0 \
+ -p 9867:9867 \
+ your-pinchtab-image-with-x11
+```
+
+Caveats:
+
+- XQuartz must be running before you start the container.
+- Performance is noticeably worse than native macOS apps.
+- Some Chrome features (audio, GPU, certain input events) may not work.
+- Prefer running PinchTab natively on macOS for headed work — `pinchtab server`
+ on the host plus headed instances is the supported path.
+
+### Windows via WSLg or VcXsrv
+
+- **WSLg** (Windows 11 / recent Windows 10): WSL2 ships with a built-in
+ Wayland/X compositor. Run PinchTab inside your WSL distro and headed Chrome
+ appears on the Windows desktop with no extra configuration.
+- **VcXsrv / Xming**: install an X server on Windows, run it with access
+ control disabled for the loopback interface, and point `DISPLAY` from WSL or
+ a container at the Windows host IP. Fragile; prefer WSLg.
+
+Native Windows builds of `pinchtab` are best-effort — see
+[Headless vs Headed](../headless-vs-headed.md#windows) for the broader Windows
+support story.
+
+## Headed mode in CI
+
+Not supported. The headless image is the only configuration PinchTab tests in
+CI, and the bundled Docker image will not run headed Chrome. If you need
+headed-only behavior validated, run those tests on a developer workstation
+with a real display.
+
+## Fingerprint differences (CloakBrowser users)
+
+Headed and headless Chrome have observably different fingerprints — different
+`navigator.webdriver` handling, different GPU strings, different feature
+flags, and different default window/viewport sizes. CloakBrowser narrows the
+gap but cannot make headless mode pixel-identical to a headed session on the
+same machine. If a target site treats your headed-on-laptop traffic as human
+and your headless-in-container traffic as a bot, that is the fingerprint
+delta, not a CloakBrowser bug — validate your flows in the mode you intend to
+deploy in.
+
+## Related guides
+
+- [cloakbrowser.md](cloakbrowser.md) — CloakBrowser provider configuration
+ and troubleshooting
+- [docker.md](docker.md) — bundled headless image and CloakBrowser smoke
+ image (both headless-only)
+- [attach-chrome.md](attach-chrome.md) — attach to a separately launched
+ headed Chrome or CloakBrowser via CDP
+- [security.md](security.md) — security model for local and remote setups
diff --git a/docs/guides/security.md b/docs/guides/security.md
index c356f762..d1e002cd 100644
--- a/docs/guides/security.md
+++ b/docs/guides/security.md
@@ -25,7 +25,8 @@ The default security posture is:
- `instanceDefaults.stealthLevel = "light"` (minimal fingerprint normalization only; anti-bot bypass requires explicit opt-in to `medium` or `full`)
- `security.attach.enabled = false`
- `security.attach.allowHosts = ["127.0.0.1", "localhost", "::1"]`
-- `security.attach.allowSchemes = ["ws", "wss"]`
+- `security.attach.allowSchemes = ["ws", "wss", "http", "https"]`
+- `security.attach.forwardProxyAuth = false`
- `security.allowedDomains = ["127.0.0.1", "localhost", "::1"]`
- `security.trustedProxyCIDRs = []`
- `security.trustedResolveCIDRs = []`
@@ -222,7 +223,8 @@ Attach is an advanced feature for registering an externally managed Chrome insta
"attach": {
"enabled": false,
"allowHosts": ["127.0.0.1", "localhost", "::1"],
- "allowSchemes": ["ws", "wss"]
+ "allowSchemes": ["ws", "wss", "http", "https"],
+ "forwardProxyAuth": false
}
}
}
@@ -234,12 +236,30 @@ If you enable attach:
- prefer local-only hosts unless external Chrome targets or remote bridges are intentional
- only attach to browsers and CDP endpoints you trust
- `allowHosts: ["*"]` is a documented, non-default, security-reducing override. It disables host allowlisting entirely and allows any reachable attach host with an allowed scheme. Use it only on isolated, operator-controlled networks.
+- keep `forwardProxyAuth` disabled unless the attached browser process and CDP transport are trusted; enabling it permits PinchTab to send configured proxy credentials over the CDP WebSocket.
-If you use `POST /instances/attach-bridge`, `security.attach.allowSchemes` must also include `http` or `https`.
+There are two attach endpoints with different trust shapes:
+
+- `POST /instances/attach` — attach an existing **CDP browser** by `cdpUrl`.
+ PinchTab spawns a child `pinchtab bridge --cdp-attach ...` process that wraps
+ the external endpoint and registers the bridge's local HTTP URL (not the
+ raw `ws://` CDP URL) as the routable instance URL. The CDP URL is preserved
+ as metadata and **redacted in logs**.
+- `POST /instances/attach-bridge` — attach an already-running **PinchTab
+ bridge** by its HTTP `baseUrl`. The orchestrator runs a `/health` check
+ before registering it.
+
+Scheme allowlist rules:
+
+- `ws`, `wss` — required for CDP attach using a browser WebSocket URL
+- `http`, `https` — required for CDP attach using an HTTP DevTools origin
+ *and* for `POST /instances/attach-bridge`
`security.attach.allowSchemes` and `security.attach.enabled` still apply when `allowHosts` contains `"*"`, but host allowlisting no longer provides protection in that configuration.
-For `attach-bridge`, `baseUrl` should be a bare bridge origin such as `http://bridge.internal:9868`. Do not include credentials, query strings, fragments, or a path.
+For `attach-bridge`, `baseUrl` should be a bare bridge origin such as `http://bridge.internal:9868`. Do not include credentials, query strings, fragments, or a path. For CDP attach via HTTP, only the bare origin or a `/json/version` path is accepted.
+
+Stopping a CDP-attached instance shuts down the child PinchTab bridge but never kills the external browser process — PinchTab does not own that process.
## IDPI
@@ -333,7 +353,8 @@ For a secure local setup:
"attach": {
"enabled": false,
"allowHosts": ["127.0.0.1", "localhost", "::1"],
- "allowSchemes": ["ws", "wss"]
+ "allowSchemes": ["ws", "wss", "http", "https"],
+ "forwardProxyAuth": false
},
"idpi": {
"enabled": true,
@@ -383,3 +404,14 @@ For automated agents, use **agent sessions** instead of sharing the server beare
**Important:** Agent sessions are designed for trusted environments. The session management API (`/sessions`) has no per-agent authorization — any bearer-authenticated caller can manage all sessions. Do not expose these endpoints to untrusted networks.
See [Reference: Agent Sessions](../reference/sessions.md) for configuration and API details.
+
+## Related guides
+
+- [cloakbrowser.md](cloakbrowser.md) — provider-specific fingerprint flags
+ and the licensing/distribution policy for CloakBrowser binaries
+- [attach-chrome.md](attach-chrome.md) — attach an externally managed Chrome
+ or CloakBrowser via CDP, and the attach policy fields summarized above
+- [docker.md](docker.md) — container deployment, the headless-only design,
+ and the local CloakBrowser smoke image
+- [headed-mode.md](headed-mode.md) — manual headed setup (not supported in
+ the bundled image or in CI)
diff --git a/docs/reference/config.md b/docs/reference/config.md
index 3da172d6..529394a3 100644
--- a/docs/reference/config.md
+++ b/docs/reference/config.md
@@ -240,7 +240,8 @@ Current nested file-config shape:
"attach": {
"enabled": false,
"allowHosts": ["127.0.0.1", "localhost", "::1"],
- "allowSchemes": ["ws", "wss"]
+ "allowSchemes": ["ws", "wss", "http", "https"],
+ "forwardProxyAuth": false
},
"idpi": {
"enabled": true,
@@ -376,14 +377,21 @@ flags:
- `fontsDir` -> `--fingerprint-fonts-dir`
- `storageQuotaMB` -> `--fingerprint-storage-quota`
-`disableDefaultStealthArgs` defaults to true for native Cloak mode. In that mode,
+`disableDefaultStealthArgs` defaults to true for CloakBrowser targets. When set,
PinchTab keeps its process, profile, tab, extension, and action-control behavior,
-but does not add its own JS stealth overlays or automation-hiding launch flags on
-top of CloakBrowser's native patches.
+but does not add its own JS stealth overlays or automation-hiding launch flags.
+Set it to false only when you intentionally want PinchTab's legacy stealth layer
+on top of CloakBrowser's native patches.
Advanced CloakBrowser flags can still go through `browser.extraFlags` when they
are not PinchTab-owned lifecycle flags.
+`browser.proxy.geo` is a CloakBrowser fingerprint-alignment hint. When a proxy
+server and geo block are configured for a CloakBrowser target, PinchTab maps the
+geo values into native CloakBrowser fingerprint flags unless the target already
+sets the corresponding `browser.cloak` field. The stock `chrome` provider does
+not derive `--lang`, `TZ`, or WebRTC launch settings from proxy geo data.
+
### Browser Extra Flags
`browser.extraFlags` is validated and sanitized. It is only for user-safe Chrome flags that do not weaken browser security and do not override PinchTab-owned launch behavior.
@@ -563,7 +571,8 @@ headers correctly.
"attach": {
"enabled": true,
"allowHosts": ["127.0.0.1", "localhost", "chrome.internal"],
- "allowSchemes": ["ws", "wss", "http", "https"]
+ "allowSchemes": ["ws", "wss", "http", "https"],
+ "forwardProxyAuth": false
}
}
}
@@ -571,6 +580,8 @@ headers correctly.
`security.attach.allowHosts` is an allowlist. If you set it to `["*"]`, PinchTab accepts any reachable attach host with an allowed scheme. That is a documented, non-default, security-reducing override: it removes host allowlisting entirely and should only be used on isolated, operator-controlled networks.
+`security.attach.forwardProxyAuth` controls whether PinchTab may send configured proxy authentication credentials over remote CDP attach. It defaults to `false`; enable it only when the attached browser process and CDP transport are trusted.
+
### Activity Retention
```json
@@ -638,6 +649,7 @@ Valid enum values:
| `multiInstance.strategy` | `simple`, `explicit`, `simple-autorestart`, `always-on`, `no-instance` |
| `multiInstance.allocationPolicy` | `fcfs`, `round_robin`, `random` |
| `security.attach.allowSchemes` | `ws`, `wss`, `http`, `https` |
+| `security.attach.forwardProxyAuth` | `true`, `false` |
## Notes
diff --git a/docs/reference/instances.md b/docs/reference/instances.md
index 876c079d..fd5fdf9c 100644
--- a/docs/reference/instances.md
+++ b/docs/reference/instances.md
@@ -186,20 +186,56 @@ This is the fleet-wide tab listing endpoint. It is different from `GET /tabs`, w
curl http://localhost:9867/instances/metrics
```
-## Attach An Existing Chrome
+## Attach An Existing Chrome Or CloakBrowser (CDP)
```bash
curl -X POST http://localhost:9867/instances/attach \
-H "Content-Type: application/json" \
- -d '{"name":"shared-chrome","cdpUrl":"ws://127.0.0.1:9222/devtools/browser/..."}'
+ -d '{
+ "name":"shared-chrome",
+ "cdpUrl":"ws://127.0.0.1:9222/devtools/browser/...",
+ "provider":"chrome",
+ "browserTarget":"chrome-local"
+ }'
```
+What this does:
+
+- spawns a child `pinchtab bridge --cdp-attach ...` process that wraps the
+ external CDP browser via `chromedp.NewRemoteAllocator`
+- registers the instance with `attached=true`, `attachType="cdp-bridge"`,
+ and the routable `url` set to the **HTTP bridge URL** (not the raw `ws://`
+ CDP URL)
+- preserves the original `cdpUrl` as metadata in the API response
+- routes `/tabs`, `/snapshot`, `/action`, `/screenshot`, etc. through the
+ child bridge
+
+Accepted `cdpUrl` shapes:
+
+- browser-level WebSocket URL: `ws://host:port/devtools/browser/<id>`
+- HTTP DevTools origin: `http://host:port` (resolved through `/json/version`)
+- HTTP `/json/version` URL
+
+Page-level URLs (`/devtools/page/...`) are rejected.
+
+`browserTarget` is optional. When `browser.targets` is configured, an omitted
+value attaches to the configured default target and the target provider is used.
+When `browserTarget` is present, it must name a configured target. If `provider`
+is also present, it must match that target's provider. Without `browser.targets`,
+`provider` is `chrome` (default) or `cloak`; the cloak provider disables
+PinchTab JS overlays on the assumption that the external browser owns native
+fingerprint behavior.
+
Notes:
- there is no CLI attach command
- attach is allowed only when enabled in config under `security.attach`
- `security.attach.allowHosts` must allow the `cdpUrl` host
-- `allowHosts: ["*"]` is a documented, non-default, security-reducing override. It disables host allowlisting entirely and allows any reachable CDP host with an allowed scheme. Use it only on isolated, operator-controlled networks.
+- if you pass an HTTP DevTools origin, `security.attach.allowSchemes` must
+ include `http` or `https`
+- stopping the attached instance shuts down the child PinchTab bridge but
+ leaves the external browser process running
+- `allowHosts: ["*"]` is a documented, non-default, security-reducing override
## Attach An Existing Bridge
@@ -209,13 +245,15 @@ curl -X POST http://localhost:9867/instances/attach-bridge \
-d '{
"name":"shared-bridge",
"baseUrl":"http://10.0.12.24:9868",
- "token":"bridge-secret-token"
+ "token":"bridge-secret-token",
+ "browserTarget":"chrome-local"
}'
```
Notes:
- `baseUrl` must be a bare bridge origin; do not include credentials, query strings, fragments, or a path
+- `browserTarget` is optional; with `browser.targets` configured, an omitted value attaches to the default target
- the orchestrator performs a health check before registering it
- `security.attach.allowHosts` must allow the bridge host
- `allowHosts: ["*"]` is a documented, non-default, security-reducing override. It disables host allowlisting entirely and allows any reachable bridge host with an allowed scheme. Use it only on isolated, operator-controlled networks.
diff --git a/internal/api/types/types.go b/internal/api/types/types.go
index 45e94c40..a5827779 100644
--- a/internal/api/types/types.go
+++ b/internal/api/types/types.go
@@ -47,6 +47,15 @@ type Instance struct {
AttachType string `json:"attachType,omitempty"`
CdpURL string `json:"cdpUrl,omitempty"` // CDP WebSocket URL (for CDP-attached instances)
SecurityPolicy *SecurityPolicy `json:"securityPolicy,omitempty"`
+
+ // BrowserTarget is the resolved named target; empty on legacy configs.
+ BrowserTarget string `json:"browserTarget,omitempty"`
+ BrowserProvider string `json:"browserProvider,omitempty"`
+
+ // FallbackFrom/FallbackReason are reserved for a future phase (always
+ // empty in P2.4a).
+ FallbackFrom string `json:"fallbackFrom,omitempty"`
+ FallbackReason string `json:"fallbackReason,omitempty"`
}
// Agent represents a connected AI agent.
diff --git a/internal/bridge/api.go b/internal/bridge/api.go
index 0c9fe866..32063407 100644
--- a/internal/bridge/api.go
+++ b/internal/bridge/api.go
@@ -107,6 +107,7 @@ type OrchestratorService interface {
Logs(id string) (string, error)
FirstRunningURL() string
AllTabs() []InstanceTab
+ FindInstanceByTab(tabID string) (*Instance, bool)
ScreencastURL(instanceID, tabID string) string
Shutdown()
ForceShutdown()
@@ -187,6 +188,14 @@ type Instance struct {
AttachType string `json:"attachType,omitempty"` // "cdp" or "bridge" for attached instances
CdpURL string `json:"cdpUrl,omitempty"` // CDP WebSocket URL (for CDP-attached instances)
SecurityPolicy *SecurityPolicy `json:"securityPolicy,omitempty"`
+
+ BrowserTarget string `json:"browserTarget,omitempty"`
+ BrowserProvider string `json:"browserProvider,omitempty"`
+
+ // FallbackFrom/FallbackReason: omitempty keeps successful-launch
+ // Instance JSON byte-identical to pre-P2.4a output.
+ FallbackFrom string `json:"fallbackFrom,omitempty"`
+ FallbackReason string `json:"fallbackReason,omitempty"`
}
func (i Instance) MarshalJSON() ([]byte, error) {
diff --git a/internal/bridge/bridge_cleanup_test.go b/internal/bridge/bridge_cleanup_test.go
index 1e606048..4253535d 100644
--- a/internal/bridge/bridge_cleanup_test.go
+++ b/internal/bridge/bridge_cleanup_test.go
@@ -4,11 +4,44 @@ import (
"context"
"os"
"path/filepath"
+ "sync/atomic"
"testing"
+ "time"
"github.com/pinchtab/pinchtab/internal/config"
)
+func withMockedProcessLookup(t *testing.T, pidsFor func() []int) (termCount, killCount *atomic.Int32) {
+ t.Helper()
+ origFind := findChromePIDsByProfileDirFunc
+ origTerm := terminateChromeByProfileDirFunc
+ origKill := killChromeByProfileDirFunc
+ origPoll := chromeExitPollInterval
+
+ var term atomic.Int32
+ var kill atomic.Int32
+
+ findChromePIDsByProfileDirFunc = func(string) []int { return pidsFor() }
+ terminateChromeByProfileDirFunc = func(string) int {
+ term.Add(1)
+ return len(pidsFor())
+ }
+ killChromeByProfileDirFunc = func(string) int {
+ kill.Add(1)
+ return len(pidsFor())
+ }
+ chromeExitPollInterval = 5 * time.Millisecond
+
+ t.Cleanup(func() {
+ findChromePIDsByProfileDirFunc = origFind
+ terminateChromeByProfileDirFunc = origTerm
+ killChromeByProfileDirFunc = origKill
+ chromeExitPollInterval = origPoll
+ })
+
+ return &term, &kill
+}
+
func TestCleanup_RemovesTempProfileDir(t *testing.T) {
tmpDir := t.TempDir()
profileDir := filepath.Join(tmpDir, "pinchtab-profile-test")
@@ -36,3 +69,162 @@ func TestCleanup_NoTempDir(t *testing.T) {
// Should not panic with no temp dir
b.Cleanup()
}
+
+func withShortenedGrace(t *testing.T, grace, termGrace time.Duration) {
+ t.Helper()
+ origGrace := BridgeShutdownGracePeriod
+ origTerm := bridgeShutdownTermGrace
+ origFast := bridgeFastShutdownGrace
+ BridgeShutdownGracePeriod = grace
+ bridgeShutdownTermGrace = termGrace
+ bridgeFastShutdownGrace = grace
+ t.Cleanup(func() {
+ BridgeShutdownGracePeriod = origGrace
+ bridgeShutdownTermGrace = origTerm
+ bridgeFastShutdownGrace = origFast
+ })
+}
+
+func TestCleanup_WaitsForChromeExit_BeforeSIGKILL(t *testing.T) {
+ withShortenedGrace(t, 500*time.Millisecond, 200*time.Millisecond)
+
+ start := time.Now()
+ // Report alive for the first ~100ms then gone.
+ termCount, killCount := withMockedProcessLookup(t, func() []int {
+ if time.Since(start) < 100*time.Millisecond {
+ return []int{12345}
+ }
+ return nil
+ })
+
+ ctx := context.TODO()
+ b := New(ctx, ctx, &config.RuntimeConfig{ProfileDir: "/tmp/pinchtab-test-profile"})
+ b.Cleanup()
+
+ if got := termCount.Load(); got != 0 {
+ t.Errorf("expected 0 SIGTERM escalations when chrome exits during grace, got %d", got)
+ }
+ if got := killCount.Load(); got != 0 {
+ t.Errorf("expected 0 SIGKILL escalations when chrome exits during grace, got %d", got)
+ }
+}
+
+func TestCleanup_FallsBackToSIGKILL_WhenChromeWontDie(t *testing.T) {
+ withShortenedGrace(t, 80*time.Millisecond, 80*time.Millisecond)
+
+ termCount, killCount := withMockedProcessLookup(t, func() []int {
+ return []int{67890} // always alive
+ })
+
+ ctx := context.TODO()
+ b := New(ctx, ctx, &config.RuntimeConfig{ProfileDir: "/tmp/pinchtab-test-profile"})
+ b.Cleanup()
+
+ if got := termCount.Load(); got == 0 {
+ t.Errorf("expected SIGTERM escalation for persistent chrome profile, got 0")
+ }
+ if got := killCount.Load(); got == 0 {
+ t.Errorf("expected SIGKILL escalation when chrome never exits, got 0")
+ }
+}
+
+func TestCleanup_TempProfileUsesFastKill(t *testing.T) {
+ withShortenedGrace(t, 20*time.Millisecond, 20*time.Millisecond)
+ termCount, killCount := withMockedProcessLookup(t, func() []int {
+ return []int{67890}
+ })
+
+ profileDir := t.TempDir()
+ ctx := context.TODO()
+ b := New(ctx, ctx, &config.RuntimeConfig{ProfileDir: "/tmp/pinchtab-test-profile"})
+ b.tempProfileDir = profileDir
+ b.Cleanup()
+
+ if got := termCount.Load(); got != 0 {
+ t.Errorf("temp profile cleanup must not SIGTERM, got %d", got)
+ }
+ if got := killCount.Load(); got == 0 {
+ t.Errorf("expected SIGKILL escalation for temp profile when chrome never exits, got 0")
+ }
+}
+
+func TestCleanup_CloakTermBeforeKill(t *testing.T) {
+ withShortenedGrace(t, 80*time.Millisecond, 80*time.Millisecond)
+
+ var termOrder, killOrder atomic.Int64
+ var step atomic.Int64
+
+ origFind := findChromePIDsByProfileDirFunc
+ origTerm := terminateChromeByProfileDirFunc
+ origKill := killChromeByProfileDirFunc
+ origPoll := chromeExitPollInterval
+ t.Cleanup(func() {
+ findChromePIDsByProfileDirFunc = origFind
+ terminateChromeByProfileDirFunc = origTerm
+ killChromeByProfileDirFunc = origKill
+ chromeExitPollInterval = origPoll
+ })
+ chromeExitPollInterval = 5 * time.Millisecond
+
+ findChromePIDsByProfileDirFunc = func(string) []int { return []int{42} }
+ terminateChromeByProfileDirFunc = func(string) int {
+ termOrder.Store(step.Add(1))
+ return 1
+ }
+ killChromeByProfileDirFunc = func(string) int {
+ killOrder.Store(step.Add(1))
+ return 1
+ }
+
+ ctx := context.TODO()
+ b := New(ctx, ctx, &config.RuntimeConfig{
+ BrowserProvider: config.BrowserProviderCloak,
+ ProfileDir: "/tmp/pinchtab-test-profile",
+ })
+ b.Cleanup()
+
+ to := termOrder.Load()
+ ko := killOrder.Load()
+ if to == 0 {
+ t.Fatalf("expected SIGTERM to be called, but it was not")
+ }
+ if ko == 0 {
+ t.Fatalf("expected SIGKILL to be called, but it was not")
+ }
+ if to >= ko {
+ t.Errorf("expected SIGTERM before SIGKILL, got term=%d kill=%d", to, ko)
+ }
+}
+
+func TestCmdlineHasExactUserDataDirArgAvoidsPrefixCollision(t *testing.T) {
+ args := [][]byte{
+ []byte("/Applications/Chrome"),
+ []byte("--user-data-dir=/var/lib/pt/profile10"),
+ []byte("--remote-debugging-port=9222"),
+ }
+ if cmdlineHasExactArg(args, "--user-data-dir=/var/lib/pt/profile1") {
+ t.Fatal("profile1 matched profile10")
+ }
+ if !cmdlineHasExactArg(args, "--user-data-dir=/var/lib/pt/profile10") {
+ t.Fatal("profile10 should match exact user-data-dir arg")
+ }
+}
+
+func TestCleanup_RemoteCDP_SkipsKillLogic(t *testing.T) {
+ withShortenedGrace(t, 20*time.Millisecond, 20*time.Millisecond)
+ termCount, killCount := withMockedProcessLookup(t, func() []int { return []int{1} })
+
+ ctx := context.TODO()
+ b := New(ctx, ctx, &config.RuntimeConfig{
+ ProfileDir: "/tmp/pinchtab-test-profile",
+ RemoteCDPURL: "http://127.0.0.1:9222",
+ })
+ b.Cleanup()
+
+ if got := termCount.Load(); got != 0 {
+ t.Errorf("remote-CDP cleanup must not SIGTERM, got %d", got)
+ }
+ if got := killCount.Load(); got != 0 {
+ t.Errorf("remote-CDP cleanup must not SIGKILL, got %d", got)
+ }
+}
diff --git a/internal/bridge/bridge_lifecycle.go b/internal/bridge/bridge_lifecycle.go
index 78b9e3b0..99e25d56 100644
--- a/internal/bridge/bridge_lifecycle.go
+++ b/internal/bridge/bridge_lifecycle.go
@@ -7,6 +7,7 @@ import (
"log/slog"
"math/big"
"os"
+ "strings"
"sync"
"time"
@@ -17,6 +18,13 @@ import (
"github.com/pinchtab/pinchtab/internal/stealth"
)
+// Combined grace+term budget stays under docker stop's 10s default while
+// giving Chromium's leveldb-backed Local Storage time to flush. var (not
+// const) so tests can shrink them.
+var BridgeShutdownGracePeriod = 5 * time.Second
+var bridgeShutdownTermGrace = 2 * time.Second
+var bridgeFastShutdownGrace = 200 * time.Millisecond
+
func (b *Bridge) quietStealthObservers() bool {
return b != nil && b.Config != nil && stealth.NormalizeLevel(b.Config.StealthLevel) == stealth.LevelFull
}
@@ -55,7 +63,7 @@ func (b *Bridge) applyTargetStealth(ctx context.Context) {
if b == nil || b.Config == nil {
return
}
- if config.NativeCloakStealthEnabled(b.Config) {
+ if config.PinchTabStealthDefaultsDisabled(b.Config) {
return
}
@@ -72,7 +80,7 @@ func (b *Bridge) applyTargetStealth(ctx context.Context) {
}
func (b *Bridge) tabSetup(ctx context.Context) {
- if !config.NativeCloakStealthEnabled(b.Config) {
+ if !config.PinchTabStealthDefaultsDisabled(b.Config) {
b.applyTargetStealth(ctx)
b.installWorkerStealthParity(ctx)
}
@@ -126,6 +134,11 @@ func (b *Bridge) EnsureChrome(cfg *config.RuntimeConfig) error {
b.BrowserCancel = nil
}
+ // Remote-CDP: no profile lock, no launched process.
+ if strings.TrimSpace(cfg.RemoteCDPURL) != "" {
+ return b.ensureRemoteCDPLocked(cfg)
+ }
+
slog.Debug("ensure chrome called", "headless", cfg.Headless, "profile", cfg.ProfileDir)
if err := AcquireProfileLock(cfg.ProfileDir); err != nil {
@@ -293,6 +306,19 @@ func (b *Bridge) RestartBrowser(cfg *config.RuntimeConfig) error {
// Cleanup releases browser resources and removes temporary profile directories.
// Must be called on shutdown to prevent Chrome process and disk leaks.
func (b *Bridge) Cleanup() {
+ // Remote-CDP: external browser is not owned by PinchTab.
+ if b != nil && b.Config != nil && strings.TrimSpace(b.Config.RemoteCDPURL) != "" {
+ if b.BrowserCancel != nil {
+ b.BrowserCancel()
+ slog.Debug("remote-CDP: browser context cancelled (external browser left running)")
+ }
+ if b.AllocCancel != nil {
+ b.AllocCancel()
+ slog.Debug("remote-CDP: allocator context cancelled")
+ }
+ return
+ }
+
if b.TabManager != nil && b.tempProfileDir == "" {
b.SaveState()
}
@@ -302,7 +328,24 @@ func (b *Bridge) Cleanup() {
MarkCleanExit(b.Config.ProfileDir)
}
- if b.BrowserCancel != nil {
+ gracefulOwnedChrome := b.requiresGracefulChromeCleanup()
+ if gracefulOwnedChrome {
+ // chromedp.Cancel issues Browser.close (graceful); plain CancelFunc
+ // only tears down the WebSocket, so Chromium may not flush leveldb-backed
+ // Local Storage, IndexedDB, service workers, or cookies before process
+ // teardown. Use the slower path for owned persistent profiles.
+ if b.BrowserCtx != nil && b.BrowserCtx.Err() == nil {
+ cancelCtx, cancel := context.WithTimeout(b.BrowserCtx, bridgeShutdownTermGrace)
+ if err := chromedp.Cancel(cancelCtx); err != nil {
+ slog.Warn("chromedp.Cancel during cleanup failed", "err", err)
+ }
+ cancel()
+ slog.Debug("chrome closed via chromedp.Cancel (Browser.close)")
+ } else if b.BrowserCancel != nil {
+ b.BrowserCancel()
+ slog.Debug("chrome browser context cancelled (already errored)")
+ }
+ } else if b.BrowserCancel != nil {
b.BrowserCancel()
slog.Debug("chrome browser context cancelled")
}
@@ -321,10 +364,27 @@ func (b *Bridge) Cleanup() {
profileDir = b.Config.ProfileDir
}
if profileDir != "" {
- time.Sleep(200 * time.Millisecond)
- killed := killChromeByProfileDir(profileDir)
- if killed > 0 {
- slog.Info("cleanup: killed surviving chrome processes", "count", killed, "profileDir", profileDir)
+ if gracefulOwnedChrome {
+ if !waitForChromeExit(profileDir, BridgeShutdownGracePeriod) {
+ slog.Info("cleanup: chrome did not exit within grace, sending SIGTERM",
+ "grace", BridgeShutdownGracePeriod, "profileDir", profileDir)
+ terminateChromeByProfileDirFunc(profileDir)
+ if !waitForChromeExit(profileDir, bridgeShutdownTermGrace) {
+ slog.Warn("cleanup: chrome still alive after SIGTERM, escalating to SIGKILL",
+ "profileDir", profileDir)
+ killed := killChromeByProfileDirFunc(profileDir)
+ if killed > 0 {
+ slog.Info("cleanup: SIGKILL'd surviving chrome processes",
+ "count", killed, "profileDir", profileDir)
+ }
+ }
+ }
+ } else if !waitForChromeExit(profileDir, bridgeFastShutdownGrace) {
+ killed := killChromeByProfileDirFunc(profileDir)
+ if killed > 0 {
+ slog.Info("cleanup: SIGKILL'd surviving chrome processes",
+ "count", killed, "profileDir", profileDir)
+ }
}
}
@@ -338,6 +398,14 @@ func (b *Bridge) Cleanup() {
}
}
+func (b *Bridge) requiresGracefulChromeCleanup() bool {
+ if b == nil || b.Config == nil || b.tempProfileDir != "" {
+ return false
+ }
+ return b.stealthLaunchMode != stealth.LaunchModeAttached &&
+ b.stealthLaunchMode != stealth.LaunchModeRemoteCDP
+}
+
func (b *Bridge) SetBrowserContexts(allocCtx context.Context, allocCancel context.CancelFunc, browserCtx context.Context, browserCancel context.CancelFunc) {
b.initMu.Lock()
defer b.initMu.Unlock()
diff --git a/internal/bridge/cleanup.go b/internal/bridge/cleanup.go
index df1fe838..0cc7892d 100644
--- a/internal/bridge/cleanup.go
+++ b/internal/bridge/cleanup.go
@@ -4,11 +4,11 @@ package bridge
import (
"bytes"
- "fmt"
"log/slog"
"os"
"os/exec"
"path/filepath"
+ "regexp"
"strconv"
"strings"
"syscall"
@@ -79,13 +79,15 @@ func KillAllPinchtabChrome() int {
return len(pids)
}
+// Test seam: overridden to simulate process presence without /proc or ps.
+var findChromePIDsByProfileDirFunc = findChromePIDsByProfileDir
+
// findChromePIDsByProfileDir returns PIDs of Chrome processes using the given profile directory.
func findChromePIDsByProfileDir(profileDir string) []int {
- needle := fmt.Sprintf("--user-data-dir=%s", profileDir)
- if pids := findPIDsByNeedle(needle); len(pids) > 0 {
+ if pids := findChromePIDsByUserDataDirViaProc(profileDir); pids != nil {
return pids
}
- return nil
+ return findChromePIDsByUserDataDirViaPS(profileDir)
}
// findPIDsByNeedle searches process command lines for a substring.
@@ -130,6 +132,72 @@ func findPIDsViaProc(needle string) []int {
return pids
}
+func findChromePIDsByUserDataDirViaProc(profileDir string) []int {
+ entries, err := os.ReadDir("/proc")
+ if err != nil {
+ return nil // /proc not available (macOS, some BSDs)
+ }
+
+ want := "--user-data-dir=" + profileDir
+ var pids []int
+ self := os.Getpid()
+
+ for _, e := range entries {
+ if !e.IsDir() {
+ continue
+ }
+ pid, err := strconv.Atoi(e.Name())
+ if err != nil || pid <= 0 || pid == self {
+ continue
+ }
+ cmdline, err := os.ReadFile(filepath.Join("/proc", e.Name(), "cmdline"))
+ if err != nil {
+ continue
+ }
+ if cmdlineHasExactArg(bytes.Split(bytes.TrimRight(cmdline, "\x00"), []byte{0}), want) {
+ pids = append(pids, pid)
+ }
+ }
+ return pids
+}
+
+func cmdlineHasExactArg(args [][]byte, want string) bool {
+ for _, arg := range args {
+ if string(arg) == want {
+ return true
+ }
+ }
+ return false
+}
+
+func findChromePIDsByUserDataDirViaPS(profileDir string) []int {
+ cmd := exec.Command("ps", "-axo", "pid=,args=")
+ out, err := cmd.Output()
+ if err != nil {
+ return nil
+ }
+
+ pattern := regexp.MustCompile(`(?:^|\s)` + regexp.QuoteMeta("--user-data-dir="+profileDir) + `(?:\s|$)`)
+ lines := bytes.Split(out, []byte{'\n'})
+ var pids []int
+ for _, rawLine := range lines {
+ line := strings.TrimSpace(string(rawLine))
+ if line == "" || !pattern.MatchString(line) {
+ continue
+ }
+ fields := strings.Fields(line)
+ if len(fields) < 2 {
+ continue
+ }
+ pid, err := strconv.Atoi(fields[0])
+ if err != nil || pid <= 0 {
+ continue
+ }
+ pids = append(pids, pid)
+ }
+ return pids
+}
+
// findPIDsViaPS uses `ps -axo pid=,args=` to find matching processes.
func findPIDsViaPS(needle string) []int {
cmd := exec.Command("ps", "-axo", "pid=,args=")
@@ -165,7 +233,7 @@ func findPIDsViaPS(needle string) []int {
// directory, sends SIGTERM, waits briefly, then SIGKILL any survivors.
// Returns the number of processes killed.
func killChromeByProfileDir(profileDir string) int {
- pids := findChromePIDsByProfileDir(profileDir)
+ pids := findChromePIDsByProfileDirFunc(profileDir)
if len(pids) == 0 {
return 0
}
@@ -194,3 +262,17 @@ func killChromeByProfileDir(profileDir string) int {
return killed
}
+
+// terminateChromeByProfileDir sends SIGTERM without escalating to SIGKILL.
+func terminateChromeByProfileDir(profileDir string) int {
+ pids := findChromePIDsByProfileDirFunc(profileDir)
+ if len(pids) == 0 {
+ return 0
+ }
+ for _, pid := range pids {
+ if err := syscall.Kill(pid, syscall.SIGTERM); err == nil {
+ slog.Info("cleanup: SIGTERM chrome process", "pid", pid)
+ }
+ }
+ return len(pids)
+}
diff --git a/internal/bridge/cleanup_windows.go b/internal/bridge/cleanup_windows.go
index 7dfb9499..09559a51 100644
--- a/internal/bridge/cleanup_windows.go
+++ b/internal/bridge/cleanup_windows.go
@@ -56,15 +56,37 @@ func taskkillPIDs(pids []int) int {
return killed
}
+// Test seam: overridden in tests.
+var findChromePIDsByProfileDirFunc = findChromePIDsByProfileDir
+
+func findChromePIDsByProfileDir(profileDir string) []int {
+ return findPIDsByPowerShell(fmt.Sprintf("--user-data-dir=%s", profileDir))
+}
+
// killChromeByProfileDir finds and kills Chrome processes using the given profile directory.
func killChromeByProfileDir(profileDir string) int {
- pids := findPIDsByPowerShell(fmt.Sprintf("--user-data-dir=%s", profileDir))
+ pids := findChromePIDsByProfileDirFunc(profileDir)
if len(pids) == 0 {
return 0
}
return taskkillPIDs(pids)
}
+// terminateChromeByProfileDir: taskkill without /F (no SIGKILL escalation).
+func terminateChromeByProfileDir(profileDir string) int {
+ pids := findChromePIDsByProfileDirFunc(profileDir)
+ if len(pids) == 0 {
+ return 0
+ }
+ for _, pid := range pids {
+ cmd := exec.Command("taskkill", "/PID", strconv.Itoa(pid))
+ if err := cmd.Run(); err == nil {
+ slog.Info("cleanup: taskkill chrome process", "pid", pid)
+ }
+ }
+ return len(pids)
+}
+
// KillAllPinchtabChrome kills all Chrome processes spawned by PinchTab.
func KillAllPinchtabChrome() int {
var pids []int
diff --git a/internal/bridge/init_test.go b/internal/bridge/init_test.go
index 848d98a8..8135a6db 100644
--- a/internal/bridge/init_test.go
+++ b/internal/bridge/init_test.go
@@ -158,6 +158,45 @@ func TestBuildChromeArgsIncludesExistingExtensionPaths(t *testing.T) {
}
}
+func TestBuildChromeArgsIncludesProxyFlagsWhenConfigured(t *testing.T) {
+ args := buildChromeArgs(&config.RuntimeConfig{
+ Proxy: config.BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ BypassList: []string{"*.local", "127.0.0.1"},
+ Username: "alice",
+ Password: "s3cr3t",
+ },
+ }, 9222)
+
+ hasProxy, hasBypass := false, false
+ for _, a := range args {
+ if a == "--proxy-server=http://proxy.example.com:8080" {
+ hasProxy = true
+ }
+ if a == "--proxy-bypass-list=*.local;127.0.0.1" {
+ hasBypass = true
+ }
+ if strings.Contains(a, "alice") || strings.Contains(a, "s3cr3t") {
+ t.Fatalf("proxy credentials leaked into Chrome args: %q", a)
+ }
+ }
+ if !hasProxy {
+ t.Fatalf("expected --proxy-server flag in %v", args)
+ }
+ if !hasBypass {
+ t.Fatalf("expected --proxy-bypass-list flag in %v", args)
+ }
+}
+
+func TestBuildChromeArgsOmitsProxyFlagsWhenDisabled(t *testing.T) {
+ args := buildChromeArgs(&config.RuntimeConfig{}, 9222)
+ for _, a := range args {
+ if strings.HasPrefix(a, "--proxy-server=") || strings.HasPrefix(a, "--proxy-bypass-list=") {
+ t.Fatalf("did not expect proxy flag without config: %q", a)
+ }
+ }
+}
+
func TestBaseChromeFlagArgsDisablesMetricsReporting(t *testing.T) {
args := baseChromeFlagArgs()
for _, want := range []string{"--disable-metrics-reporting", "--metrics-recording-only"} {
diff --git a/internal/bridge/lifecycle_remote_cdp.go b/internal/bridge/lifecycle_remote_cdp.go
new file mode 100644
index 00000000..3bddb7af
--- /dev/null
+++ b/internal/bridge/lifecycle_remote_cdp.go
@@ -0,0 +1,79 @@
+package bridge
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+
+ "github.com/chromedp/cdproto/target"
+ "github.com/chromedp/chromedp"
+ bridgeruntime "github.com/pinchtab/pinchtab/internal/bridge/runtime"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/ids"
+ internalurls "github.com/pinchtab/pinchtab/internal/urls"
+)
+
+// ensureRemoteCDPLocked attaches to an external browser via CDP URL.
+// Caller must hold b.initMu. No profile lock, no launched process; Cleanup
+// cancels PinchTab-owned contexts only.
+func (b *Bridge) ensureRemoteCDPLocked(cfg *config.RuntimeConfig) error {
+ slog.Info("attaching bridge to remote CDP endpoint",
+ "provider", config.NormalizeBrowserProvider(cfg.BrowserProvider),
+ "remoteBrowserName", cfg.RemoteBrowserName,
+ "cdpUrl", internalurls.RedactForLog(cfg.RemoteCDPURL),
+ )
+
+ allocCtx, allocCancel, browserCtx, browserCancel, launchMode, err := bridgeruntime.InitRemoteCDP(context.Background(), cfg, cfg.RemoteCDPURL)
+ if err != nil {
+ return fmt.Errorf("init remote CDP: %w", err)
+ }
+
+ b.AllocCtx = allocCtx
+ b.AllocCancel = allocCancel
+ b.BrowserCtx = browserCtx
+ b.BrowserCancel = browserCancel
+ b.initialized = true
+ b.stealthLaunchMode = launchMode
+
+ if b.IdMgr == nil {
+ b.IdMgr = ids.NewManager()
+ }
+ if b.LogStore == nil {
+ b.LogStore = NewConsoleLogStore(1000)
+ }
+ if b.TabManager == nil {
+ b.TabManager = NewTabManager(browserCtx, cfg, b.IdMgr, b.LogStore, b.tabSetup)
+ b.SetOnAfterClose(func() { go b.SaveState() })
+ b.SetDialogManager(b.Dialogs)
+ b.SetNetworkMonitor(b.netMonitor)
+ b.SetRouteManager(b.routeMgr)
+ }
+ if b.Actions == nil {
+ b.InitActionRegistry()
+ }
+
+ if err := b.ensureAtLeastOnePageTarget(browserCtx); err != nil {
+ slog.Warn("failed to ensure a page target on remote CDP", "err", err)
+ }
+
+ return nil
+}
+
+func (b *Bridge) ensureAtLeastOnePageTarget(browserCtx context.Context) error {
+ var targets []*target.Info
+ err := chromedp.Run(browserCtx, chromedp.ActionFunc(func(ctx context.Context) error {
+ var listErr error
+ targets, listErr = target.GetTargets().Do(ctx)
+ return listErr
+ }))
+ if err != nil {
+ return err
+ }
+ for _, t := range targets {
+ if t.Type == "page" {
+ return nil
+ }
+ }
+ _, _, _, err = b.CreateTab("about:blank")
+ return err
+}
diff --git a/internal/bridge/runtime/cdp_url.go b/internal/bridge/runtime/cdp_url.go
new file mode 100644
index 00000000..49b279da
--- /dev/null
+++ b/internal/bridge/runtime/cdp_url.go
@@ -0,0 +1,414 @@
+package runtime
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log/slog"
+ "net"
+ "net/http"
+ "net/netip"
+ "net/url"
+ "strings"
+ "time"
+)
+
+const cdpVersionBodyLimit = 64 * 1024
+
+var defaultCDPAllowHosts = []string{"127.0.0.1", "localhost", "::1"}
+var defaultCDPAllowSchemes = []string{"ws", "wss", "http", "https"}
+
+var cdpResolveHostIPs = func(ctx context.Context, network, host string) ([]net.IP, error) {
+ return net.DefaultResolver.LookupIP(ctx, network, host)
+}
+
+type CDPVersionProbe struct {
+ VersionURL string
+ WebSocketDebuggerURL string
+}
+
+// NormalizeCDPURL accepts any of:
+// - browser-level WebSocket URL: ws://host:port/devtools/browser/<id>
+// - HTTP DevTools origin: http://host:port (or http://host:port/)
+// - HTTP /json/version URL: http://host:port/json/version
+//
+// It returns the browser-level WebSocket URL suitable for chromedp.NewRemoteAllocator.
+//
+// Page-level URLs (containing /devtools/page/) are rejected in this slice.
+func NormalizeCDPURL(raw string) (string, error) {
+ return NormalizeCDPURLWithAllowedHosts(raw, defaultCDPAllowHosts)
+}
+
+// NormalizeCDPURLWithAllowedHosts resolves and pins the endpoint host. Loopback
+// CDP endpoints are always accepted; non-loopback endpoints must match
+// allowedHosts (or "*"). HTTP probes never follow redirects and response bodies
+// are capped.
+func NormalizeCDPURLWithAllowedHosts(raw string, allowedHosts []string) (string, error) {
+ return NormalizeCDPURLWithAllowlist(raw, allowedHosts, defaultCDPAllowSchemes)
+}
+
+// NormalizeCDPURLWithAllowlist resolves and pins the endpoint host while
+// enforcing the caller's attach host and input-scheme allowlists.
+func NormalizeCDPURLWithAllowlist(raw string, allowedHosts, allowedSchemes []string) (string, error) {
+ trimmed := strings.TrimSpace(raw)
+ if trimmed == "" {
+ return "", fmt.Errorf("cdpUrl is required")
+ }
+
+ parsed, err := url.Parse(trimmed)
+ if err != nil {
+ return "", fmt.Errorf("invalid cdpUrl: %w", err)
+ }
+ if parsed.Host == "" {
+ return "", fmt.Errorf("cdpUrl must include a host")
+ }
+ if parsed.User != nil {
+ return "", fmt.Errorf("cdpUrl must not include credentials")
+ }
+
+ scheme := strings.ToLower(parsed.Scheme)
+ if err := validateCDPScheme(scheme, allowedSchemes); err != nil {
+ return "", err
+ }
+ switch scheme {
+ case "ws", "wss":
+ if strings.Contains(parsed.Path, "/devtools/page/") {
+ return "", fmt.Errorf("page-level CDP URLs are not supported; use a browser-level URL (ws://host:port/devtools/browser/<id>)")
+ }
+ if !strings.Contains(parsed.Path, "/devtools/browser/") {
+ return "", fmt.Errorf("expected browser-level CDP path (/devtools/browser/<id>) in %q", trimmed)
+ }
+ pinned, err := validateAndResolveCDPHost(parsed, allowedHosts)
+ if err != nil {
+ return "", err
+ }
+ parsed.Host = urlHostForAddr(pinned, parsed.Port())
+ return parsed.String(), nil
+ case "http", "https":
+ return resolveDevToolsURL(parsed, allowedHosts, allowedSchemes)
+ default:
+ return "", fmt.Errorf("unsupported cdpUrl scheme %q", parsed.Scheme)
+ }
+}
+
+func resolveDevToolsURL(parsed *url.URL, allowedHosts, allowedSchemes []string) (string, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ probe, pinned, err := probeCDPVersionParsed(ctx, parsed, allowedHosts, allowedSchemes)
+ if err != nil {
+ return "", err
+ }
+
+ return normalizeResolvedDevToolsURL(probe.WebSocketDebuggerURL, parsed, pinned, allowedHosts)
+}
+
+func ProbeCDPVersion(ctx context.Context, raw string, allowedHosts []string) (CDPVersionProbe, error) {
+ trimmed := strings.TrimSpace(raw)
+ if trimmed == "" {
+ return CDPVersionProbe{}, fmt.Errorf("cdpUrl is required")
+ }
+ parsed, err := url.Parse(trimmed)
+ if err != nil {
+ return CDPVersionProbe{}, fmt.Errorf("invalid cdpUrl: %w", err)
+ }
+ probe, _, err := probeCDPVersionParsed(ctx, parsed, allowedHosts, defaultCDPAllowSchemes)
+ return probe, err
+}
+
+func probeCDPVersionParsed(ctx context.Context, parsed *url.URL, allowedHosts, allowedSchemes []string) (CDPVersionProbe, netip.Addr, error) {
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ if parsed.Host == "" {
+ return CDPVersionProbe{}, netip.Addr{}, fmt.Errorf("cdpUrl must include a host")
+ }
+ if parsed.User != nil {
+ return CDPVersionProbe{}, netip.Addr{}, fmt.Errorf("cdpUrl must not include credentials")
+ }
+
+ var versionURL string
+ var httpScheme string
+ scheme := strings.ToLower(parsed.Scheme)
+ if err := validateCDPScheme(scheme, allowedSchemes); err != nil {
+ return CDPVersionProbe{}, netip.Addr{}, err
+ }
+ switch scheme {
+ case "ws", "wss":
+ if strings.Contains(parsed.Path, "/devtools/page/") {
+ return CDPVersionProbe{}, netip.Addr{}, fmt.Errorf("page-level CDP URLs are not supported; use a browser-level URL (ws://host:port/devtools/browser/<id>)")
+ }
+ if !strings.Contains(parsed.Path, "/devtools/browser/") {
+ return CDPVersionProbe{}, netip.Addr{}, fmt.Errorf("expected browser-level CDP path (/devtools/browser/<id>) in %q", parsed.String())
+ }
+ httpScheme = "http"
+ if strings.ToLower(parsed.Scheme) == "wss" {
+ httpScheme = "https"
+ }
+ versionURL = (&url.URL{Scheme: httpScheme, Host: parsed.Host, Path: "/json/version"}).String()
+ case "http", "https":
+ if strings.Contains(parsed.Path, "/devtools/page/") {
+ return CDPVersionProbe{}, netip.Addr{}, fmt.Errorf("page-level CDP URLs are not supported; use a browser-level URL or DevTools origin")
+ }
+ if parsed.Path != "" && parsed.Path != "/" && !strings.HasSuffix(parsed.Path, "/json/version") {
+ return CDPVersionProbe{}, netip.Addr{}, fmt.Errorf("HTTP cdpUrl must be the DevTools origin or end with /json/version, got %q", parsed.Path)
+ }
+ httpScheme = strings.ToLower(parsed.Scheme)
+ versionURL = (&url.URL{Scheme: httpScheme, Host: parsed.Host, Path: "/json/version"}).String()
+ default:
+ return CDPVersionProbe{}, netip.Addr{}, fmt.Errorf("unsupported cdpUrl scheme %q", parsed.Scheme)
+ }
+
+ pinned, err := validateAndResolveCDPHostWithContext(ctx, parsed, allowedHosts)
+ if err != nil {
+ return CDPVersionProbe{}, netip.Addr{}, err
+ }
+ probe, err := fetchCDPVersion(ctx, versionURL, pinned, portForScheme(httpScheme, parsed.Port()))
+ if err != nil {
+ return CDPVersionProbe{}, netip.Addr{}, err
+ }
+ return probe, pinned, nil
+}
+
+func fetchCDPVersion(ctx context.Context, target string, pinned netip.Addr, port string) (CDPVersionProbe, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
+ if err != nil {
+ return CDPVersionProbe{}, err
+ }
+ resp, err := pinnedCDPHTTPClient(pinned, port).Do(req)
+ if err != nil {
+ return CDPVersionProbe{}, fmt.Errorf("fetch %s: %w", target, err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if resp.StatusCode != http.StatusOK {
+ return CDPVersionProbe{}, fmt.Errorf("fetch %s: HTTP %d", target, resp.StatusCode)
+ }
+ var info struct {
+ WebSocketDebuggerURL string `json:"webSocketDebuggerUrl"`
+ }
+ body, err := readCDPVersionBody(resp.Body, target)
+ if err != nil {
+ return CDPVersionProbe{}, err
+ }
+ if err := json.Unmarshal(body, &info); err != nil {
+ return CDPVersionProbe{}, fmt.Errorf("decode %s: %w", target, err)
+ }
+ if info.WebSocketDebuggerURL == "" {
+ return CDPVersionProbe{}, fmt.Errorf("missing webSocketDebuggerUrl in %s", target)
+ }
+ return CDPVersionProbe{VersionURL: target, WebSocketDebuggerURL: info.WebSocketDebuggerURL}, nil
+}
+
+func normalizeResolvedDevToolsURL(raw string, requested *url.URL, requestedPinned netip.Addr, allowedHosts []string) (string, error) {
+ wsURL, err := url.Parse(raw)
+ if err != nil {
+ return "", fmt.Errorf("invalid webSocketDebuggerUrl %q: %w", raw, err)
+ }
+ switch strings.ToLower(wsURL.Scheme) {
+ case "ws", "wss":
+ default:
+ return "", fmt.Errorf("webSocketDebuggerUrl must use ws or wss, got %q", wsURL.Scheme)
+ }
+ if strings.Contains(wsURL.Path, "/devtools/page/") {
+ return "", fmt.Errorf("page-level CDP URLs are not supported; use a browser-level URL")
+ }
+ if !strings.Contains(wsURL.Path, "/devtools/browser/") {
+ return "", fmt.Errorf("expected browser-level CDP path (/devtools/browser/<id>) in webSocketDebuggerUrl")
+ }
+ if wsURL.User != nil {
+ return "", fmt.Errorf("webSocketDebuggerUrl must not include credentials")
+ }
+ if wsURL.Host == "" {
+ return "", fmt.Errorf("webSocketDebuggerUrl must include a host")
+ }
+ if requested != nil && requested.Host != "" && shouldUseRequestedDevToolsHost(wsURL.Hostname()) {
+ wsURL.Host = urlHostForAddr(requestedPinned, requested.Port())
+ return wsURL.String(), nil
+ }
+
+ if requestedPinned.IsValid() {
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ addrs, err := resolveCDPHostAddrs(ctx, wsURL.Hostname())
+ cancel()
+ if err == nil {
+ for _, addr := range addrs {
+ if addr == requestedPinned {
+ wsURL.Host = urlHostForAddr(requestedPinned, wsURL.Port())
+ return wsURL.String(), nil
+ }
+ }
+ }
+ }
+
+ requestedHost := ""
+ if requested != nil {
+ requestedHost = requested.Hostname()
+ }
+ return "", fmt.Errorf("webSocketDebuggerUrl host %q does not match requested CDP endpoint %q", wsURL.Hostname(), requestedHost)
+}
+
+func shouldUseRequestedDevToolsHost(host string) bool {
+ host = strings.TrimSpace(host)
+ if host == "" || strings.EqualFold(host, "localhost") {
+ return true
+ }
+ ip := net.ParseIP(host)
+ return ip != nil && (ip.IsLoopback() || ip.IsUnspecified())
+}
+
+func validateAndResolveCDPHost(parsed *url.URL, allowedHosts []string) (netip.Addr, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ return validateAndResolveCDPHostWithContext(ctx, parsed, allowedHosts)
+}
+
+func validateAndResolveCDPHostWithContext(ctx context.Context, parsed *url.URL, allowedHosts []string) (netip.Addr, error) {
+ host := strings.TrimSpace(parsed.Hostname())
+ if host == "" {
+ return netip.Addr{}, fmt.Errorf("cdpUrl must include a host")
+ }
+
+ addrs, err := resolveCDPHostAddrs(ctx, host)
+ if err != nil {
+ return netip.Addr{}, err
+ }
+ allowlisted := cdpHostAllowed(host, allowedHosts)
+ allLoopback := true
+ for _, addr := range addrs {
+ if !addr.IsLoopback() {
+ allLoopback = false
+ break
+ }
+ }
+ if !allLoopback && !allowlisted {
+ return netip.Addr{}, fmt.Errorf("remote CDP host %q resolved to non-loopback address; add it to security.attach.allowHosts to allow remote attach", host)
+ }
+ if !allLoopback {
+ slog.Warn("remote CDP endpoint is non-loopback; CDP attach grants full browser control", "host", host, "scheme", parsed.Scheme)
+ }
+ return addrs[0], nil
+}
+
+func resolveCDPHostAddrs(ctx context.Context, host string) ([]netip.Addr, error) {
+ if ip := net.ParseIP(host); ip != nil {
+ addr, ok := netip.AddrFromSlice(ip)
+ if !ok {
+ return nil, fmt.Errorf("invalid cdpUrl host %q", host)
+ }
+ return []netip.Addr{addr.Unmap()}, nil
+ }
+ ips, err := cdpResolveHostIPs(ctx, "ip", host)
+ if err != nil {
+ return nil, fmt.Errorf("resolve remote CDP host %q: %w", host, err)
+ }
+ if len(ips) == 0 {
+ return nil, fmt.Errorf("resolve remote CDP host %q: no addresses", host)
+ }
+ out := make([]netip.Addr, 0, len(ips))
+ seen := make(map[netip.Addr]struct{}, len(ips))
+ for _, ip := range ips {
+ addr, ok := netip.AddrFromSlice(ip)
+ if !ok {
+ continue
+ }
+ addr = addr.Unmap()
+ if _, ok := seen[addr]; ok {
+ continue
+ }
+ seen[addr] = struct{}{}
+ out = append(out, addr)
+ }
+ if len(out) == 0 {
+ return nil, fmt.Errorf("resolve remote CDP host %q: no usable IPs", host)
+ }
+ return out, nil
+}
+
+func cdpHostAllowed(host string, allowedHosts []string) bool {
+ host = strings.ToLower(strings.Trim(host, "[] "))
+ for _, raw := range allowedHosts {
+ allowed := strings.ToLower(strings.Trim(raw, "[] "))
+ if allowed == "*" || allowed == host {
+ return true
+ }
+ }
+ return false
+}
+
+func validateCDPScheme(scheme string, allowedSchemes []string) error {
+ switch scheme {
+ case "ws", "wss", "http", "https":
+ default:
+ return fmt.Errorf("unsupported cdpUrl scheme %q", scheme)
+ }
+
+ effective := effectiveCDPAllowSchemes(allowedSchemes)
+ for _, allowed := range effective {
+ if scheme == allowed {
+ return nil
+ }
+ }
+ return fmt.Errorf("remote CDP scheme %q not allowed (allowed: %v)", scheme, effective)
+}
+
+func effectiveCDPAllowSchemes(allowedSchemes []string) []string {
+ if len(allowedSchemes) == 0 {
+ return append([]string(nil), defaultCDPAllowSchemes...)
+ }
+ out := make([]string, 0, len(allowedSchemes))
+ for _, raw := range allowedSchemes {
+ scheme := strings.ToLower(strings.TrimSpace(raw))
+ if scheme != "" {
+ out = append(out, scheme)
+ }
+ }
+ return out
+}
+
+func pinnedCDPHTTPClient(addr netip.Addr, port string) *http.Client {
+ return &http.Client{
+ Timeout: 3 * time.Second,
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
+ Transport: &http.Transport{
+ DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
+ dialer := &net.Dialer{Timeout: 3 * time.Second}
+ return dialer.DialContext(ctx, network, net.JoinHostPort(addr.String(), port))
+ },
+ TLSHandshakeTimeout: 3 * time.Second,
+ },
+ }
+}
+
+func portForScheme(scheme, explicit string) string {
+ if explicit != "" {
+ return explicit
+ }
+ switch strings.ToLower(scheme) {
+ case "https", "wss":
+ return "443"
+ default:
+ return "80"
+ }
+}
+
+func readCDPVersionBody(r io.Reader, target string) ([]byte, error) {
+ body, err := io.ReadAll(io.LimitReader(r, cdpVersionBodyLimit+1))
+ if err != nil {
+ return nil, fmt.Errorf("read %s: %w", target, err)
+ }
+ if len(body) > cdpVersionBodyLimit {
+ return nil, fmt.Errorf("read %s: response body exceeds %d bytes", target, cdpVersionBodyLimit)
+ }
+ return body, nil
+}
+
+func urlHostForAddr(addr netip.Addr, port string) string {
+ host := addr.String()
+ if port == "" {
+ if addr.Is6() {
+ return "[" + host + "]"
+ }
+ return host
+ }
+ return net.JoinHostPort(host, port)
+}
diff --git a/internal/bridge/runtime/cdp_url_test.go b/internal/bridge/runtime/cdp_url_test.go
new file mode 100644
index 00000000..af348057
--- /dev/null
+++ b/internal/bridge/runtime/cdp_url_test.go
@@ -0,0 +1,264 @@
+package runtime
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/netip"
+ "net/url"
+ "strings"
+ "testing"
+)
+
+func TestNormalizeCDPURL_BrowserWebSocket(t *testing.T) {
+ in := "ws://127.0.0.1:9222/devtools/browser/abc123"
+ got, err := NormalizeCDPURL(in)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != in {
+ t.Fatalf("got %q, want %q", got, in)
+ }
+}
+
+func TestNormalizeCDPURL_RejectsPageLevel(t *testing.T) {
+ in := "ws://127.0.0.1:9222/devtools/page/xyz"
+ _, err := NormalizeCDPURL(in)
+ if err == nil {
+ t.Fatalf("expected error for page-level URL")
+ }
+ if !strings.Contains(err.Error(), "page-level") {
+ t.Fatalf("error should mention page-level, got %v", err)
+ }
+}
+
+func TestNormalizeCDPURL_RejectsEmpty(t *testing.T) {
+ if _, err := NormalizeCDPURL(""); err == nil {
+ t.Fatalf("expected error for empty cdpUrl")
+ }
+ if _, err := NormalizeCDPURL(" "); err == nil {
+ t.Fatalf("expected error for whitespace cdpUrl")
+ }
+}
+
+func TestNormalizeCDPURL_RejectsUnsupportedScheme(t *testing.T) {
+ if _, err := NormalizeCDPURL("ftp://x/devtools/browser/y"); err == nil {
+ t.Fatalf("expected error for ftp scheme")
+ }
+}
+
+func TestNormalizeCDPURL_RejectsNonLoopbackByDefault(t *testing.T) {
+ _, err := NormalizeCDPURL("ws://169.254.169.254:9222/devtools/browser/abc")
+ if err == nil {
+ t.Fatalf("expected non-loopback remote CDP host to be rejected")
+ }
+ if !strings.Contains(err.Error(), "non-loopback") {
+ t.Fatalf("error should mention non-loopback, got %v", err)
+ }
+}
+
+func TestNormalizeCDPURL_AllowsExplicitlyAllowlistedRemoteHost(t *testing.T) {
+ got, err := NormalizeCDPURLWithAllowlist("ws://192.0.2.10:9222/devtools/browser/abc", []string{"192.0.2.10"}, []string{"ws"})
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != "ws://192.0.2.10:9222/devtools/browser/abc" {
+ t.Fatalf("got %q", got)
+ }
+}
+
+func TestNormalizeCDPURL_RejectsDisallowedAttachScheme(t *testing.T) {
+ _, err := NormalizeCDPURLWithAllowlist("http://127.0.0.1:9222", []string{"127.0.0.1"}, []string{"ws"})
+ if err == nil {
+ t.Fatal("expected disallowed scheme to be rejected")
+ }
+ if !strings.Contains(err.Error(), "scheme") || !strings.Contains(err.Error(), "not allowed") {
+ t.Fatalf("error should mention disallowed scheme, got %v", err)
+ }
+}
+
+func TestNormalizeCDPURL_RejectsWsWithoutBrowserPath(t *testing.T) {
+ if _, err := NormalizeCDPURL("ws://127.0.0.1:9222/something/else"); err == nil {
+ t.Fatalf("expected error for missing /devtools/browser/")
+ }
+}
+
+func TestNormalizeCDPURL_HTTPOriginResolves(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/json/version" {
+ http.NotFound(w, r)
+ return
+ }
+ _, _ = fmt.Fprintf(w, `{"webSocketDebuggerUrl":"ws://%s/devtools/browser/test-id"}`, r.Host)
+ }))
+ defer srv.Close()
+
+ got, err := NormalizeCDPURL(srv.URL)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !strings.HasPrefix(got, "ws://") || !strings.Contains(got, "/devtools/browser/") {
+ t.Fatalf("expected resolved browser WS URL, got %q", got)
+ }
+}
+
+func TestNormalizeCDPURL_HTTPOriginRewritesLoopbackDebuggerHost(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/json/version" {
+ http.NotFound(w, r)
+ return
+ }
+ _, _ = fmt.Fprint(w, `{"webSocketDebuggerUrl":"ws://[::1]:9222/devtools/browser/test-id"}`)
+ }))
+ defer srv.Close()
+
+ got, err := NormalizeCDPURL(srv.URL)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ want := "ws://" + strings.TrimPrefix(srv.URL, "http://") + "/devtools/browser/test-id"
+ if got != want {
+ t.Fatalf("got %q, want %q", got, want)
+ }
+}
+
+func TestNormalizeCDPURL_HTTPJSONVersionResolves(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/json/version" {
+ http.NotFound(w, r)
+ return
+ }
+ _, _ = fmt.Fprintf(w, `{"webSocketDebuggerUrl":"ws://%s/devtools/browser/test-id"}`, r.Host)
+ }))
+ defer srv.Close()
+
+ got, err := NormalizeCDPURL(srv.URL + "/json/version")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !strings.HasPrefix(got, "ws://") {
+ t.Fatalf("expected ws:// URL, got %q", got)
+ }
+}
+
+func TestProbeCDPVersionHTTPOrigin(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/json/version" {
+ http.NotFound(w, r)
+ return
+ }
+ _, _ = fmt.Fprintf(w, `{"webSocketDebuggerUrl":"ws://%s/devtools/browser/test-id"}`, r.Host)
+ }))
+ defer srv.Close()
+
+ got, err := ProbeCDPVersion(context.Background(), srv.URL, nil)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got.VersionURL != srv.URL+"/json/version" {
+ t.Fatalf("VersionURL = %q, want %q", got.VersionURL, srv.URL+"/json/version")
+ }
+ if !strings.Contains(got.WebSocketDebuggerURL, "/devtools/browser/test-id") {
+ t.Fatalf("WebSocketDebuggerURL = %q", got.WebSocketDebuggerURL)
+ }
+}
+
+func TestProbeCDPVersionBrowserWebSocket(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/json/version" {
+ http.NotFound(w, r)
+ return
+ }
+ _, _ = fmt.Fprintf(w, `{"webSocketDebuggerUrl":"ws://%s/devtools/browser/test-id"}`, r.Host)
+ }))
+ defer srv.Close()
+
+ raw := "ws://" + strings.TrimPrefix(srv.URL, "http://") + "/devtools/browser/test-id"
+ got, err := ProbeCDPVersion(context.Background(), raw, nil)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got.VersionURL != srv.URL+"/json/version" {
+ t.Fatalf("VersionURL = %q, want %q", got.VersionURL, srv.URL+"/json/version")
+ }
+ if got.WebSocketDebuggerURL != raw {
+ t.Fatalf("WebSocketDebuggerURL = %q, want %q", got.WebSocketDebuggerURL, raw)
+ }
+}
+
+func TestNormalizeCDPURL_HTTPRejectsArbitraryPath(t *testing.T) {
+ if _, err := NormalizeCDPURL("http://127.0.0.1:9222/some/other/path"); err == nil {
+ t.Fatalf("expected error for arbitrary HTTP path")
+ }
+}
+
+func TestNormalizeCDPURL_HTTPDoesNotFollowRedirects(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, "/redirected", http.StatusFound)
+ }))
+ defer srv.Close()
+
+ _, err := NormalizeCDPURL(srv.URL)
+ if err == nil {
+ t.Fatalf("expected redirect response to fail")
+ }
+ if !strings.Contains(err.Error(), "HTTP 302") {
+ t.Fatalf("error should report redirect status, got %v", err)
+ }
+}
+
+func TestNormalizeCDPURL_HTTPVersionBodyIsCapped(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(strings.Repeat("x", cdpVersionBodyLimit+1)))
+ }))
+ defer srv.Close()
+
+ _, err := NormalizeCDPURL(srv.URL)
+ if err == nil {
+ t.Fatalf("expected oversized response to fail")
+ }
+ if !strings.Contains(err.Error(), "exceeds") {
+ t.Fatalf("error should mention body limit, got %v", err)
+ }
+}
+
+func TestNormalizeResolvedDevToolsURL_AllowsRequestedPinnedIP(t *testing.T) {
+ requested, err := url.Parse("http://cdp.example.test:9222")
+ if err != nil {
+ t.Fatalf("parse requested URL: %v", err)
+ }
+
+ got, err := normalizeResolvedDevToolsURL(
+ "ws://192.0.2.10:9222/devtools/browser/abc",
+ requested,
+ netip.MustParseAddr("192.0.2.10"),
+ []string{"cdp.example.test"},
+ )
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != "ws://192.0.2.10:9222/devtools/browser/abc" {
+ t.Fatalf("got %q", got)
+ }
+}
+
+func TestNormalizeResolvedDevToolsURL_RejectsAllowlistedDifferentHost(t *testing.T) {
+ requested, err := url.Parse("http://192.0.2.10:9222")
+ if err != nil {
+ t.Fatalf("parse requested URL: %v", err)
+ }
+
+ _, err = normalizeResolvedDevToolsURL(
+ "ws://192.0.2.20:9222/devtools/browser/abc",
+ requested,
+ netip.MustParseAddr("192.0.2.10"),
+ []string{"192.0.2.20"},
+ )
+ if err == nil {
+ t.Fatal("expected different allowlisted response host to be rejected")
+ }
+ if !strings.Contains(err.Error(), "does not match requested CDP endpoint") {
+ t.Fatalf("unexpected error: %v", err)
+ }
+}
diff --git a/internal/bridge/runtime/geo_align.go b/internal/bridge/runtime/geo_align.go
new file mode 100644
index 00000000..e28a3441
--- /dev/null
+++ b/internal/bridge/runtime/geo_align.go
@@ -0,0 +1,45 @@
+package runtime
+
+// Provider-depth contract:
+// - Cloak: deep alignment via --fingerprint-* flags; explicit per-target
+// Cloak fingerprint config wins over derived geo (operator intent beats
+// proxy-driven hints).
+// - Chrome: no automatic proxy-derived geo localization. Use Cloak when
+// PinchTab should align browser fingerprint fields with proxy geography.
+// - Unknown providers: no-op.
+
+import (
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/config/geo"
+)
+
+// applyGeoAlignment returns provider-specific flags and env additions.
+// cloak carries the merged Cloak runtime config so the "explicit wins"
+// precedence rule is honored without re-reading config.
+func applyGeoAlignment(provider string, info geo.Info, cloak config.CloakBrowserRuntimeConfig) (flags, env []string) {
+ if info.IsZero() {
+ return nil, nil
+ }
+ switch config.NormalizeBrowserProvider(provider) {
+ case config.BrowserProviderCloak:
+ return cloakGeoFlags(info, cloak), nil
+ default:
+ return nil, nil
+ }
+}
+
+// Skips fields the operator has explicitly set on the Cloak config —
+// per-target intent (e.g. NY locale via London proxy) wins.
+func cloakGeoFlags(info geo.Info, cloak config.CloakBrowserRuntimeConfig) []string {
+ var flags []string
+ if info.Timezone != "" && cloak.Timezone == "" {
+ flags = append(flags, "--fingerprint-timezone="+info.Timezone)
+ }
+ if info.Locale != "" && cloak.Locale == "" {
+ flags = append(flags, "--fingerprint-locale="+info.Locale)
+ }
+ if info.WebRTCIP != "" && cloak.WebRTCIP == "" {
+ flags = append(flags, "--fingerprint-webrtc-ip="+info.WebRTCIP)
+ }
+ return flags
+}
diff --git a/internal/bridge/runtime/geo_align_test.go b/internal/bridge/runtime/geo_align_test.go
new file mode 100644
index 00000000..10345cb9
--- /dev/null
+++ b/internal/bridge/runtime/geo_align_test.go
@@ -0,0 +1,282 @@
+package runtime
+
+import (
+ "context"
+ "errors"
+ "reflect"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/config/geo"
+ "github.com/pinchtab/pinchtab/internal/stealth"
+)
+
+func TestApplyGeoAlignment_ZeroInfo(t *testing.T) {
+ flags, env := applyGeoAlignment(config.BrowserProviderChrome, geo.Info{}, config.CloakBrowserRuntimeConfig{})
+ if len(flags) != 0 || len(env) != 0 {
+ t.Fatalf("expected no flags/env for zero info, got flags=%v env=%v", flags, env)
+ }
+}
+
+func TestResolveLaunchGeoAlignmentSkipsLookupWithoutProxyServer(t *testing.T) {
+ old := geoProviderForConfigFunc
+ t.Cleanup(func() { geoProviderForConfigFunc = old })
+ geoProviderForConfigFunc = func(*config.RuntimeConfig) geo.Provider {
+ t.Fatal("geo provider should not be constructed without a proxy server")
+ return geo.Noop{}
+ }
+
+ cfg := &config.RuntimeConfig{
+ BrowserProvider: config.BrowserProviderChrome,
+ Proxy: config.BrowserProxyConfig{
+ Geo: &config.BrowserProxyGeoConfig{Timezone: "Europe/London"},
+ },
+ }
+ got, err := resolveLaunchGeoAlignment(context.Background(), cfg)
+ if err != nil {
+ t.Fatalf("resolveLaunchGeoAlignment returned error: %v", err)
+ }
+ if !got.info.IsZero() || len(got.flags) != 0 || len(got.env) != 0 {
+ t.Fatalf("expected empty alignment without proxy server, got %+v", got)
+ }
+}
+
+func TestResolveLaunchGeoAlignmentPropagatesLookupError(t *testing.T) {
+ old := geoProviderForConfigFunc
+ t.Cleanup(func() { geoProviderForConfigFunc = old })
+
+ sentinel := errors.New("geo boom")
+ calls := 0
+ geoProviderForConfigFunc = func(*config.RuntimeConfig) geo.Provider {
+ return fakeGeoProvider{lookup: func(context.Context, string) (geo.Info, error) {
+ calls++
+ return geo.Info{}, sentinel
+ }}
+ }
+
+ cfg := &config.RuntimeConfig{
+ BrowserProvider: config.BrowserProviderCloak,
+ Proxy: config.BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Geo: &config.BrowserProxyGeoConfig{Timezone: "Europe/London"},
+ },
+ }
+ _, err := resolveLaunchGeoAlignment(context.Background(), cfg)
+ if !errors.Is(err, sentinel) {
+ t.Fatalf("error = %v, want sentinel", err)
+ }
+ if calls != 1 {
+ t.Fatalf("lookup calls = %d, want 1", calls)
+ }
+}
+
+func TestBuildChromeArgsWithBundleUsesProvidedGeoAlignment(t *testing.T) {
+ old := geoProviderForConfigFunc
+ t.Cleanup(func() { geoProviderForConfigFunc = old })
+ geoProviderForConfigFunc = func(*config.RuntimeConfig) geo.Provider {
+ t.Fatal("buildChromeArgsWithBundle should use cached alignment")
+ return geo.Noop{}
+ }
+
+ args := buildChromeArgsWithBundle(&config.RuntimeConfig{
+ BrowserProvider: config.BrowserProviderCloak,
+ }, nil, 9222, launchGeoAlignment{
+ flags: []string{"--fingerprint-locale=en-GB"},
+ })
+ if !stealth.HasLaunchArg(args, "--fingerprint-locale=en-GB") {
+ t.Fatalf("cached geo flag missing from args: %v", args)
+ }
+}
+
+type fakeGeoProvider struct {
+ lookup func(context.Context, string) (geo.Info, error)
+}
+
+func (f fakeGeoProvider) Lookup(ctx context.Context, ip string) (geo.Info, error) {
+ return f.lookup(ctx, ip)
+}
+
+func TestResolveLaunchGeoAlignmentSkipsLookupForChromeProvider(t *testing.T) {
+ old := geoProviderForConfigFunc
+ t.Cleanup(func() { geoProviderForConfigFunc = old })
+ geoProviderForConfigFunc = func(*config.RuntimeConfig) geo.Provider {
+ t.Fatal("geo provider should not be constructed for the chrome provider")
+ return geo.Noop{}
+ }
+
+ cfg := &config.RuntimeConfig{
+ BrowserProvider: config.BrowserProviderChrome,
+ Proxy: config.BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Geo: &config.BrowserProxyGeoConfig{Timezone: "Europe/London", Locale: "en-GB"},
+ },
+ }
+ got, err := resolveLaunchGeoAlignment(context.Background(), cfg)
+ if err != nil {
+ t.Fatalf("resolveLaunchGeoAlignment returned error: %v", err)
+ }
+ if !got.info.IsZero() || len(got.flags) != 0 || len(got.env) != 0 {
+ t.Fatalf("expected empty alignment for chrome provider, got %+v", got)
+ }
+}
+
+func TestApplyGeoAlignment_ChromeNoop(t *testing.T) {
+ info := geo.Info{
+ Timezone: "Europe/London",
+ Locale: "en-GB",
+ CountryISO: "GB",
+ }
+ flags, env := applyGeoAlignment(config.BrowserProviderChrome, info, config.CloakBrowserRuntimeConfig{})
+ if len(flags) != 0 || len(env) != 0 {
+ t.Fatalf("chrome provider should not receive proxy-derived geo flags/env, got flags=%v env=%v", flags, env)
+ }
+}
+
+func TestApplyGeoAlignment_ChromeLocaleOnlyNoop(t *testing.T) {
+ info := geo.Info{Locale: "en-GB"}
+ flags, env := applyGeoAlignment(config.BrowserProviderChrome, info, config.CloakBrowserRuntimeConfig{})
+ if len(flags) != 0 || len(env) != 0 {
+ t.Fatalf("chrome provider should not receive proxy-derived geo flags/env, got flags=%v env=%v", flags, env)
+ }
+}
+
+func TestApplyGeoAlignment_ChromeCountryOnly_NoFlags(t *testing.T) {
+ // CountryISO is metadata only — it must not trigger flag emission.
+ info := geo.Info{CountryISO: "GB"}
+ flags, env := applyGeoAlignment(config.BrowserProviderChrome, info, config.CloakBrowserRuntimeConfig{})
+ if len(flags) != 0 || len(env) != 0 {
+ t.Fatalf("country-only info should produce no flags/env, got flags=%v env=%v", flags, env)
+ }
+}
+
+func TestApplyGeoAlignment_Cloak(t *testing.T) {
+ info := geo.Info{
+ Timezone: "Europe/London",
+ Locale: "en-GB",
+ WebRTCIP: "203.0.113.7",
+ }
+ flags, env := applyGeoAlignment(config.BrowserProviderCloak, info, config.CloakBrowserRuntimeConfig{})
+
+ wantFlags := []string{
+ "--fingerprint-timezone=Europe/London",
+ "--fingerprint-locale=en-GB",
+ "--fingerprint-webrtc-ip=203.0.113.7",
+ }
+ if !reflect.DeepEqual(flags, wantFlags) {
+ t.Errorf("cloak flags = %v, want %v", flags, wantFlags)
+ }
+ if len(env) != 0 {
+ t.Errorf("cloak env should be empty, got %v", env)
+ }
+}
+
+func TestApplyGeoAlignment_CloakExplicitWinsOverDerivedGeo(t *testing.T) {
+ info := geo.Info{
+ Timezone: "Europe/London",
+ Locale: "en-GB",
+ WebRTCIP: "203.0.113.7",
+ }
+ cloak := config.CloakBrowserRuntimeConfig{
+ Timezone: "America/New_York", // explicit per-target override
+ }
+ flags, _ := applyGeoAlignment(config.BrowserProviderCloak, info, cloak)
+
+ // Explicit Cloak timezone wins → no derived flag.
+ for _, f := range flags {
+ if f == "--fingerprint-timezone=Europe/London" {
+ t.Errorf("derived timezone leaked despite explicit Cloak override: %v", flags)
+ }
+ }
+ // Other derived fields still emitted (no explicit override).
+ if !stealth.HasLaunchArg(flags, "--fingerprint-locale=en-GB") {
+ t.Errorf("expected derived locale, got %v", flags)
+ }
+ if !stealth.HasLaunchArg(flags, "--fingerprint-webrtc-ip=203.0.113.7") {
+ t.Errorf("expected derived webrtc-ip, got %v", flags)
+ }
+}
+
+func TestApplyGeoAlignment_UnknownProviderNoop(t *testing.T) {
+ info := geo.Info{Timezone: "Europe/London", Locale: "en-GB"}
+ flags, env := applyGeoAlignment("future-provider", info, config.CloakBrowserRuntimeConfig{})
+ if len(flags) != 0 || len(env) != 0 {
+ t.Fatalf("unknown provider should produce no flags/env, got %v / %v", flags, env)
+ }
+}
+
+func TestBuildChromeArgs_ChromeDoesNotApplyProxyGeoFlagsByDefault(t *testing.T) {
+ old := geoProviderForConfigFunc
+ t.Cleanup(func() { geoProviderForConfigFunc = old })
+ geoProviderForConfigFunc = func(*config.RuntimeConfig) geo.Provider {
+ t.Fatal("BuildChromeArgs should not perform geo lookup for the chrome provider")
+ return geo.Noop{}
+ }
+
+ cfg := &config.RuntimeConfig{
+ BrowserProvider: config.BrowserProviderChrome,
+ ChromeVersion: "144.0.0.0",
+ Proxy: config.BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Geo: &config.BrowserProxyGeoConfig{
+ Timezone: "Europe/London",
+ Locale: "en-GB",
+ },
+ },
+ }
+ args := BuildChromeArgs(cfg, 9222)
+ for _, blocked := range []string{
+ "--lang=en-GB",
+ "--webrtc-ip-handling-policy=disable_non_proxied_udp",
+ } {
+ if stealth.HasLaunchArg(args, blocked) {
+ t.Errorf("BuildChromeArgs() included proxy-derived geo flag %q in %v", blocked, args)
+ }
+ }
+}
+
+func TestBuildChromeArgs_CloakAppliesGeoFlagsAndRespectsExplicit(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ BrowserProvider: config.BrowserProviderCloak,
+ Cloak: config.CloakBrowserRuntimeConfig{
+ Timezone: "America/New_York", // explicit wins
+ },
+ Proxy: config.BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Geo: &config.BrowserProxyGeoConfig{
+ Timezone: "Europe/London",
+ Locale: "en-GB",
+ },
+ },
+ }
+ args := BuildChromeArgs(cfg, 9222)
+ // Locale derived (no explicit cloak locale)
+ if !stealth.HasLaunchArg(args, "--fingerprint-locale=en-GB") {
+ t.Errorf("expected --fingerprint-locale=en-GB in %v", args)
+ }
+ // Explicit cloak timezone preserved
+ if !stealth.HasLaunchArg(args, "--fingerprint-timezone=America/New_York") {
+ t.Errorf("expected explicit cloak timezone in %v", args)
+ }
+ // Derived timezone NOT emitted
+ if stealth.HasLaunchArg(args, "--fingerprint-timezone=Europe/London") {
+ t.Errorf("derived timezone leaked despite explicit cloak override in %v", args)
+ }
+}
+
+func TestMergeGeoEnv_OverridesByKey(t *testing.T) {
+ base := []string{"PATH=/bin", "TZ=UTC", "FOO=bar"}
+ add := []string{"TZ=Europe/London"}
+ got := mergeGeoEnv(base, add)
+ want := []string{"PATH=/bin", "FOO=bar", "TZ=Europe/London"}
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("mergeGeoEnv = %v, want %v", got, want)
+ }
+}
+
+func TestMergeGeoEnv_NoAdditionsReturnsBase(t *testing.T) {
+ base := []string{"PATH=/bin"}
+ got := mergeGeoEnv(base, nil)
+ if !reflect.DeepEqual(got, base) {
+ t.Errorf("mergeGeoEnv(_, nil) = %v, want %v", got, base)
+ }
+}
diff --git a/internal/bridge/runtime/init.go b/internal/bridge/runtime/init.go
index e1d6bbf7..ee7525c4 100644
--- a/internal/bridge/runtime/init.go
+++ b/internal/bridge/runtime/init.go
@@ -20,16 +20,27 @@ import (
"time"
"github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/browserprobe"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/config/geo"
"github.com/pinchtab/pinchtab/internal/stealth"
)
var (
- runtimeGOOS = goruntime.GOOS
- osGeteuid = os.Geteuid
- containerMarkerPath = "/.dockerenv"
+ runtimeGOOS = goruntime.GOOS
+ osGeteuid = os.Geteuid
+ containerMarkerPath = "/.dockerenv"
+ geoProviderForConfigFunc = geoProviderForConfig
)
+const launchGeoLookupTimeout = 3 * time.Second
+
+type launchGeoAlignment struct {
+ info geo.Info
+ flags []string
+ env []string
+}
+
type Hooks struct {
SetHumanRandSeed func(int64)
IsChromeProfileLockError func(string) bool
@@ -54,14 +65,26 @@ func InitChrome(cfg *config.RuntimeConfig, bundle *stealth.Bundle, hooks Hooks)
}
bundle = ensureStealthBundle(cfg, bundle)
- allocCtx, allocCancel, opts, debugPort := setupAllocator(cfg, bundle, hooks)
- browserCtx, browserCancel, launchMode, err := startChrome(allocCtx, cfg, bundle, opts, debugPort, hooks)
+ geoAlignment, err := resolveLaunchGeoAlignment(context.Background(), cfg)
+ if err != nil {
+ return nil, nil, nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to resolve proxy geo alignment: %w", err)
+ }
+ allocCtx, allocCancel, opts, debugPort := setupAllocator(cfg, bundle, hooks, geoAlignment)
+ browserCtx, browserCancel, launchMode, err := startChrome(allocCtx, cfg, bundle, opts, debugPort, hooks, geoAlignment)
if err != nil {
allocCancel()
slog.Error("chrome initialization failed", "headless", cfg.Headless, "error", err.Error())
return nil, nil, nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to start chrome: %w", err)
}
+ if proxyAuthEnabled(cfg.Proxy) {
+ if err := enableProxyAuth(browserCtx, cfg.Proxy); err != nil {
+ browserCancel()
+ allocCancel()
+ return nil, nil, nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to enable proxy auth: %w", err)
+ }
+ }
+
slog.Info("chrome initialized successfully", "headless", cfg.Headless, "profile", cfg.ProfileDir)
return allocCtx, allocCancel, browserCtx, browserCancel, launchMode, nil
}
@@ -96,34 +119,13 @@ func initChromeFromExistingCDP(cfg *config.RuntimeConfig, bundle *stealth.Bundle
}
func findChromeBinary() string {
- var candidates []string
- switch goruntime.GOOS {
- case "darwin":
- candidates = []string{
- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
- "/Applications/Chromium.app/Contents/MacOS/Chromium",
- "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
- }
- case "windows":
- candidates = []string{
- "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
- "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
- }
- default:
- candidates = []string{
- "/usr/bin/google-chrome",
- "/usr/bin/google-chrome-stable",
- "/usr/bin/chromium",
- "/usr/bin/chromium-browser",
- }
- }
+ return FindChromeBinary()
+}
- for _, path := range candidates {
- if _, err := os.Stat(path); err == nil {
- return path
- }
- }
- return ""
+// FindChromeBinary exposes the launch-time Chrome discovery used by runtime
+// initialization so diagnostics can report against the same search path.
+func FindChromeBinary() string {
+ return browserprobe.DiscoverChromeBinary(runtimeGOOS).Found
}
func appendExecAllocatorFlag(opts []chromedp.ExecAllocatorOption, flag string) []chromedp.ExecAllocatorOption {
@@ -148,14 +150,17 @@ func appendExecAllocatorFlags(opts []chromedp.ExecAllocatorOption, flags []strin
return opts
}
-func setupAllocator(cfg *config.RuntimeConfig, bundle *stealth.Bundle, hooks Hooks) (context.Context, context.CancelFunc, []chromedp.ExecAllocatorOption, int) {
+func setupAllocator(cfg *config.RuntimeConfig, bundle *stealth.Bundle, hooks Hooks, geoAlignment launchGeoAlignment) (context.Context, context.CancelFunc, []chromedp.ExecAllocatorOption, int) {
opts := []chromedp.ExecAllocatorOption{
chromedp.NoFirstRun,
chromedp.NoDefaultBrowserCheck,
}
opts = appendExecAllocatorFlags(opts, BaseChromeFlagArgs())
opts = appendExecAllocatorFlags(opts, bundle.Launch.Args)
- opts = appendExecAllocatorFlags(opts, cloakBrowserFlagArgs(cfg))
+ opts = appendExecAllocatorFlags(opts, CloakBrowserFlagArgs(cfg))
+ opts = appendExecAllocatorFlags(opts, config.BrowserProxyFlags(cfg.Proxy))
+
+ opts = appendExecAllocatorFlags(opts, geoAlignment.flags)
chromeBinary := cfg.ChromeBinary
if chromeBinary == "" {
@@ -230,6 +235,12 @@ func setupAllocator(cfg *config.RuntimeConfig, bundle *stealth.Bundle, hooks Hoo
}
opts = append(opts, chromedp.CombinedOutput(newPrefixedLogWriter(os.Stdout, "chrome")))
opts = append(opts, chromedp.ModifyCmdFunc(func(cmd *exec.Cmd) {
+ if len(geoAlignment.env) > 0 {
+ if cmd.Env == nil {
+ cmd.Env = os.Environ()
+ }
+ cmd.Env = mergeGeoEnv(cmd.Env, geoAlignment.env)
+ }
if hooks.ConfigureChromeProcessCmd != nil {
hooks.ConfigureChromeProcessCmd(cmd)
}
@@ -239,11 +250,11 @@ func setupAllocator(cfg *config.RuntimeConfig, bundle *stealth.Bundle, hooks Hoo
return ctx, cancel, opts, debugPort
}
-func startChrome(parentCtx context.Context, cfg *config.RuntimeConfig, bundle *stealth.Bundle, opts []chromedp.ExecAllocatorOption, debugPort int, hooks Hooks) (context.Context, context.CancelFunc, stealth.LaunchMode, error) {
- return startChromeWithRecovery(parentCtx, cfg, bundle, opts, debugPort, hooks, false)
+func startChrome(parentCtx context.Context, cfg *config.RuntimeConfig, bundle *stealth.Bundle, opts []chromedp.ExecAllocatorOption, debugPort int, hooks Hooks, geoAlignment launchGeoAlignment) (context.Context, context.CancelFunc, stealth.LaunchMode, error) {
+ return startChromeWithRecovery(parentCtx, cfg, bundle, opts, debugPort, hooks, geoAlignment, false)
}
-func startChromeWithRecovery(parentCtx context.Context, cfg *config.RuntimeConfig, bundle *stealth.Bundle, opts []chromedp.ExecAllocatorOption, debugPort int, hooks Hooks, retriedProfileLock bool) (context.Context, context.CancelFunc, stealth.LaunchMode, error) {
+func startChromeWithRecovery(parentCtx context.Context, cfg *config.RuntimeConfig, bundle *stealth.Bundle, opts []chromedp.ExecAllocatorOption, debugPort int, hooks Hooks, geoAlignment launchGeoAlignment, retriedProfileLock bool) (context.Context, context.CancelFunc, stealth.LaunchMode, error) {
allocCtx, allocCancel := chromedp.NewExecAllocator(parentCtx, opts...)
browserCtx, browserCancel := chromedp.NewContext(allocCtx)
@@ -278,7 +289,7 @@ func startChromeWithRecovery(parentCtx context.Context, cfg *config.RuntimeConfi
if hooks.ClearStaleChromeProfile != nil {
if recovered, _ := hooks.ClearStaleChromeProfile(cfg.ProfileDir, errMsg); recovered {
time.Sleep(250 * time.Millisecond)
- return startChromeWithRecovery(parentCtx, cfg, bundle, opts, debugPort, hooks, true)
+ return startChromeWithRecovery(parentCtx, cfg, bundle, opts, debugPort, hooks, geoAlignment, true)
}
}
}
@@ -286,7 +297,7 @@ func startChromeWithRecovery(parentCtx context.Context, cfg *config.RuntimeConfi
if shouldRetryChromeStartupWithDirectLaunch(parentCtx, err) && debugPort > 0 {
slog.Warn("chrome startup failed via allocator, trying direct-launch fallback", "port", debugPort, "error", errMsg)
time.Sleep(500 * time.Millisecond)
- return startChromeWithRemoteAllocator(parentCtx, cfg, bundle, debugPort, bundle.Script)
+ return startChromeWithRemoteAllocator(parentCtx, cfg, bundle, debugPort, bundle.Script, geoAlignment)
}
return nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to connect to chrome: %w", err)
@@ -327,7 +338,7 @@ func shouldRetryChromeStartupWithDirectLaunch(parentCtx context.Context, err err
return strings.Contains(err.Error(), "context canceled")
}
-func startChromeWithRemoteAllocator(parentCtx context.Context, cfg *config.RuntimeConfig, bundle *stealth.Bundle, debugPort int, injectedStealthScript string) (context.Context, context.CancelFunc, stealth.LaunchMode, error) {
+func startChromeWithRemoteAllocator(parentCtx context.Context, cfg *config.RuntimeConfig, bundle *stealth.Bundle, debugPort int, injectedStealthScript string, geoAlignment launchGeoAlignment) (context.Context, context.CancelFunc, stealth.LaunchMode, error) {
chromeBinary := cfg.ChromeBinary
if chromeBinary == "" {
chromeBinary = findChromeBinary()
@@ -336,11 +347,14 @@ func startChromeWithRemoteAllocator(parentCtx context.Context, cfg *config.Runti
return nil, nil, stealth.LaunchModeUninitialized, missingBrowserBinaryError(cfg)
}
- args := buildChromeArgsWithBundle(cfg, bundle, debugPort)
- // #nosec G204 -- chromeBinary from user config or findChromeBinary() known system paths
+ args := buildChromeArgsWithBundle(cfg, bundle, debugPort, geoAlignment)
+ // #nosec G204 -- chromeBinary from user config or shared browser discovery
cmd := exec.Command(chromeBinary, args...)
cmd.Stdout = newPrefixedLogWriter(os.Stdout, "chrome stdout")
cmd.Stderr = newPrefixedLogWriter(os.Stderr, "chrome stderr")
+ if len(geoAlignment.env) > 0 {
+ cmd.Env = mergeGeoEnv(os.Environ(), geoAlignment.env)
+ }
if err := cmd.Start(); err != nil {
return nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to start chrome directly: %w", err)
}
@@ -464,7 +478,11 @@ func chromeNeedsNoSandbox() bool {
}
func BuildChromeArgs(cfg *config.RuntimeConfig, port int) []string {
- return buildChromeArgsWithBundle(cfg, nil, port)
+ geoAlignment, err := resolveLaunchGeoAlignment(context.Background(), cfg)
+ if err != nil {
+ return buildChromeArgsWithBundle(cfg, nil, port, launchGeoAlignment{})
+ }
+ return buildChromeArgsWithBundle(cfg, nil, port, geoAlignment)
}
func existingExtensionPaths(paths []string) []string {
@@ -480,11 +498,13 @@ func existingExtensionPaths(paths []string) []string {
return validPaths
}
-func buildChromeArgsWithBundle(cfg *config.RuntimeConfig, bundle *stealth.Bundle, port int) []string {
+func buildChromeArgsWithBundle(cfg *config.RuntimeConfig, bundle *stealth.Bundle, port int, geoAlignment launchGeoAlignment) []string {
bundle = ensureStealthBundle(cfg, bundle)
args := append([]string{fmt.Sprintf("--remote-debugging-port=%d", port)}, BaseChromeFlagArgs()...)
args = append(args, bundle.Launch.Args...)
- args = append(args, cloakBrowserFlagArgs(cfg)...)
+ args = append(args, CloakBrowserFlagArgs(cfg)...)
+ args = append(args, config.BrowserProxyFlags(cfg.Proxy)...)
+ args = append(args, geoAlignment.flags...)
if validPaths := existingExtensionPaths(cfg.ExtensionPaths); len(validPaths) > 0 {
joined := strings.Join(validPaths, ",")
@@ -519,7 +539,7 @@ func buildChromeArgsWithBundle(cfg *config.RuntimeConfig, bundle *stealth.Bundle
return appendChromeCompatibilityFlags(args)
}
-func cloakBrowserFlagArgs(cfg *config.RuntimeConfig) []string {
+func CloakBrowserFlagArgs(cfg *config.RuntimeConfig) []string {
if cfg == nil || !config.IsCloakBrowserProvider(cfg.BrowserProvider) {
return nil
}
@@ -544,7 +564,7 @@ func cloakBrowserFlagArgs(cfg *config.RuntimeConfig) []string {
}
func applyStartupStealth(ctx context.Context, cfg *config.RuntimeConfig, bundle *stealth.Bundle, script string) error {
- if !config.NativeCloakStealthEnabled(cfg) {
+ if !config.PinchTabStealthDefaultsDisabled(cfg) {
ua := ""
if bundle != nil {
ua = bundle.LaunchUserAgent()
@@ -616,6 +636,63 @@ func (w *prefixedLogWriter) Write(p []byte) (int, error) {
return len(p), nil
}
+func geoProviderForConfig(cfg *config.RuntimeConfig) geo.Provider {
+ if cfg == nil || cfg.Proxy.Geo == nil || cfg.Proxy.Geo.IsZero() {
+ return geo.Noop{}
+ }
+ return geo.Static{Info: cfg.Proxy.GeoInfo()}
+}
+
+func resolveLaunchGeoAlignment(parent context.Context, cfg *config.RuntimeConfig) (launchGeoAlignment, error) {
+ if cfg == nil || cfg.Proxy.IsZero() || cfg.Proxy.Geo == nil || cfg.Proxy.Geo.IsZero() {
+ return launchGeoAlignment{}, nil
+ }
+ if !config.CloakBrowserProviderActive(cfg) {
+ return launchGeoAlignment{}, nil
+ }
+ if parent == nil {
+ parent = context.Background()
+ }
+ ctx, cancel := context.WithTimeout(parent, launchGeoLookupTimeout)
+ defer cancel()
+
+ info, err := geoProviderForConfigFunc(cfg).Lookup(ctx, "")
+ if err != nil {
+ return launchGeoAlignment{}, err
+ }
+ flags, env := applyGeoAlignment(cfg.BrowserProvider, info, cfg.Cloak)
+ return launchGeoAlignment{
+ info: info,
+ flags: flags,
+ env: env,
+ }, nil
+}
+
+// mergeGeoEnv overlays additions over base by key; base is not mutated.
+func mergeGeoEnv(base, additions []string) []string {
+ if len(additions) == 0 {
+ return base
+ }
+ out := make([]string, 0, len(base)+len(additions))
+ overrideKeys := make(map[string]struct{}, len(additions))
+ for _, kv := range additions {
+ if eq := strings.IndexByte(kv, '='); eq > 0 {
+ overrideKeys[kv[:eq]] = struct{}{}
+ }
+ }
+ for _, kv := range base {
+ eq := strings.IndexByte(kv, '=')
+ if eq > 0 {
+ if _, replace := overrideKeys[kv[:eq]]; replace {
+ continue
+ }
+ }
+ out = append(out, kv)
+ }
+ out = append(out, additions...)
+ return out
+}
+
func cryptoRandSeed() int64 {
n, err := rand.Int(rand.Reader, big.NewInt(1000000000))
if err != nil {
diff --git a/internal/bridge/runtime/init_remote.go b/internal/bridge/runtime/init_remote.go
new file mode 100644
index 00000000..6af55370
--- /dev/null
+++ b/internal/bridge/runtime/init_remote.go
@@ -0,0 +1,96 @@
+package runtime
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "net/url"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/stealth"
+)
+
+// InitRemoteCDP attaches to an external browser via CDP URL. The browser
+// process is not owned by PinchTab; returned cancels release only chromedp
+// contexts.
+func InitRemoteCDP(ctx context.Context, cfg *config.RuntimeConfig, cdpURL string) (context.Context, context.CancelFunc, context.Context, context.CancelFunc, stealth.LaunchMode, error) {
+ if cfg == nil {
+ return nil, nil, nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("runtime config is required")
+ }
+
+ normalized, err := NormalizeCDPURLWithAllowlist(cdpURL, cfg.AttachAllowHosts, cfg.AttachAllowSchemes)
+ if err != nil {
+ return nil, nil, nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("normalize cdpUrl: %w", err)
+ }
+ if err := requireRemoteProxyAuthOptIn(normalized, cfg); err != nil {
+ return nil, nil, nil, nil, stealth.LaunchModeUninitialized, err
+ }
+
+ slog.Info("attaching to remote CDP endpoint", "provider", cfg.BrowserProvider)
+
+ if ctx == nil {
+ ctx = context.Background()
+ }
+
+ allocCtx, allocCancel := chromedp.NewRemoteAllocator(ctx, normalized)
+ probeCtx, probeCancel := context.WithTimeout(ctx, 10*time.Second)
+ _, err = ProbeCDPVersion(probeCtx, normalized, cfg.AttachAllowHosts)
+ probeCancel()
+ if err != nil {
+ allocCancel()
+ return nil, nil, nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("remote CDP connectivity check failed: %w", err)
+ }
+
+ browserCtx, browserCancel := chromedp.NewContext(allocCtx)
+ if proxyAuthEnabled(cfg.Proxy) {
+ auditRemoteProxyAuthForward(normalized, cfg)
+ if err := enableProxyAuth(browserCtx, cfg.Proxy); err != nil {
+ browserCancel()
+ allocCancel()
+ return nil, nil, nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("enable proxy auth on remote CDP: %w", err)
+ }
+ }
+
+ return allocCtx, allocCancel, browserCtx, func() {
+ // Cancel PinchTab contexts only; do not terminate the external browser.
+ browserCancel()
+ allocCancel()
+ }, stealth.LaunchModeRemoteCDP, nil
+}
+
+func requireRemoteProxyAuthOptIn(browserWSURL string, cfg *config.RuntimeConfig) error {
+ if cfg == nil || !proxyAuthEnabled(cfg.Proxy) {
+ return nil
+ }
+ targetHost := remoteCDPTargetHost(browserWSURL)
+ if cfg.AttachForwardProxyAuth {
+ return nil
+ }
+ slog.Warn("audit",
+ "event", "remote_cdp.proxy_auth_blocked",
+ "targetHost", targetHost,
+ "proxy", cfg.Proxy.Redacted(),
+ )
+ return fmt.Errorf("remote CDP proxy authentication is disabled: refusing to send proxy credentials to attached browser %q; set security.attach.forwardProxyAuth=true to allow this trust-boundary crossing", targetHost)
+}
+
+func auditRemoteProxyAuthForward(browserWSURL string, cfg *config.RuntimeConfig) {
+ if cfg == nil || !proxyAuthEnabled(cfg.Proxy) || !cfg.AttachForwardProxyAuth {
+ return
+ }
+ slog.Warn("audit",
+ "event", "remote_cdp.proxy_auth_forwarded",
+ "targetHost", remoteCDPTargetHost(browserWSURL),
+ "proxy", cfg.Proxy.Redacted(),
+ )
+}
+
+func remoteCDPTargetHost(browserWSURL string) string {
+ parsed, err := url.Parse(browserWSURL)
+ if err != nil {
+ return ""
+ }
+ return parsed.Hostname()
+}
diff --git a/internal/bridge/runtime/proxy_auth.go b/internal/bridge/runtime/proxy_auth.go
new file mode 100644
index 00000000..975cb63c
--- /dev/null
+++ b/internal/bridge/runtime/proxy_auth.go
@@ -0,0 +1,78 @@
+package runtime
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+
+ "github.com/chromedp/cdproto/fetch"
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+// proxyAuthEnabled is the single gate for the CDP credential path
+// (testable without a running Chrome).
+func proxyAuthEnabled(p config.BrowserProxyConfig) bool {
+ if p.IsZero() {
+ return false
+ }
+ return p.Username != ""
+}
+
+// enableProxyAuth registers a browser-scoped CDP Fetch listener that responds
+// to proxy auth challenges. Never log the password — use p.Redacted().
+func enableProxyAuth(browserCtx context.Context, p config.BrowserProxyConfig) error {
+ if !proxyAuthEnabled(p) {
+ return nil
+ }
+
+ if err := chromedp.Run(browserCtx,
+ fetch.Enable().WithHandleAuthRequests(true),
+ ); err != nil {
+ return fmt.Errorf("enable fetch domain for proxy auth: %w", err)
+ }
+
+ username := p.Username
+ password := p.Password
+
+ chromedp.ListenBrowser(browserCtx, func(ev interface{}) {
+ switch e := ev.(type) {
+ case *fetch.EventAuthRequired:
+ handleAuthRequired(browserCtx, e, username, password)
+ case *fetch.EventRequestPaused:
+ handleRequestPaused(browserCtx, e)
+ }
+ })
+
+ slog.Info("proxy authentication enabled via CDP", "proxy", p.Redacted())
+ return nil
+}
+
+func handleAuthRequired(browserCtx context.Context, e *fetch.EventAuthRequired, username, password string) {
+ // Yield non-proxy challenges (e.g. server WWW-Authenticate) with Default.
+ if e.AuthChallenge == nil || e.AuthChallenge.Source != fetch.AuthChallengeSourceProxy {
+ if err := chromedp.Run(browserCtx,
+ fetch.ContinueWithAuth(e.RequestID, &fetch.AuthChallengeResponse{
+ Response: fetch.AuthChallengeResponseResponseDefault,
+ }),
+ ); err != nil && browserCtx.Err() == nil {
+ slog.Warn("proxy auth: yield (non-proxy) failed", "err", err)
+ }
+ return
+ }
+ if err := chromedp.Run(browserCtx,
+ fetch.ContinueWithAuth(e.RequestID, &fetch.AuthChallengeResponse{
+ Response: fetch.AuthChallengeResponseResponseProvideCredentials,
+ Username: username,
+ Password: password,
+ }),
+ ); err != nil && browserCtx.Err() == nil {
+ slog.Warn("proxy auth: provide credentials failed", "err", err)
+ }
+}
+
+func handleRequestPaused(browserCtx context.Context, e *fetch.EventRequestPaused) {
+ if err := chromedp.Run(browserCtx, fetch.ContinueRequest(e.RequestID)); err != nil && browserCtx.Err() == nil {
+ slog.Warn("proxy auth: continue request failed", "err", err)
+ }
+}
diff --git a/internal/bridge/runtime/proxy_auth_test.go b/internal/bridge/runtime/proxy_auth_test.go
new file mode 100644
index 00000000..2452cdc8
--- /dev/null
+++ b/internal/bridge/runtime/proxy_auth_test.go
@@ -0,0 +1,207 @@
+package runtime
+
+import (
+ "bytes"
+ "context"
+ "log/slog"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestProxyAuthEnabled_DisabledWhenNoCredentials(t *testing.T) {
+ cases := []struct {
+ name string
+ p config.BrowserProxyConfig
+ }{
+ {
+ name: "zero value",
+ p: config.BrowserProxyConfig{},
+ },
+ {
+ name: "server only, no username",
+ p: config.BrowserProxyConfig{Server: "http://proxy.example:8080"},
+ },
+ {
+ name: "server + password but no username (validator would reject)",
+ p: config.BrowserProxyConfig{Server: "http://proxy.example:8080", Password: "secret"},
+ },
+ {
+ name: "empty server, credentials populated",
+ p: config.BrowserProxyConfig{Username: "user", Password: "pw"},
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if proxyAuthEnabled(tc.p) {
+ t.Fatalf("proxyAuthEnabled(%+v) = true, want false", tc.p.Redacted())
+ }
+ })
+ }
+}
+
+func TestProxyAuthEnabled_EnabledWhenCredentialsPresent(t *testing.T) {
+ p := config.BrowserProxyConfig{
+ Server: "http://proxy.example:8080",
+ Username: "user",
+ Password: "pw",
+ }
+ if !proxyAuthEnabled(p) {
+ t.Fatalf("proxyAuthEnabled(%+v) = false, want true", p.Redacted())
+ }
+}
+
+// Cancelled context ensures the function bails before any CDP call.
+func TestEnableProxyAuth_NoopWhenDisabled(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if err := enableProxyAuth(ctx, config.BrowserProxyConfig{}); err != nil {
+ t.Fatalf("enableProxyAuth on disabled proxy returned %v, want nil", err)
+ }
+ if err := enableProxyAuth(ctx, config.BrowserProxyConfig{Server: "http://p:1"}); err != nil {
+ t.Fatalf("enableProxyAuth on credential-less proxy returned %v, want nil", err)
+ }
+}
+
+func TestProxyAuth_PasswordNotLoggedViaRedacted(t *testing.T) {
+ p := config.BrowserProxyConfig{
+ Server: "http://proxy.example:8080",
+ Username: "user",
+ Password: "super-secret",
+ }
+ r := p.Redacted()
+ if r.Password == p.Password {
+ t.Fatalf("Redacted() did not mask password: %q", r.Password)
+ }
+ if r.Password == "" {
+ t.Fatalf("Redacted() should keep a placeholder for non-empty passwords")
+ }
+}
+
+func TestRemoteProxyAuthRequiresExplicitOptIn(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ Proxy: config.BrowserProxyConfig{
+ Server: "http://proxy.example:8080",
+ Username: "user",
+ Password: "super-secret",
+ },
+ }
+
+ var err error
+ logs := captureSlog(t, func() {
+ err = requireRemoteProxyAuthOptIn("ws://203.0.113.10:9222/devtools/browser/abc", cfg)
+ })
+ if err == nil {
+ t.Fatal("expected remote proxy auth forwarding to be refused")
+ }
+ if !strings.Contains(err.Error(), "security.attach.forwardProxyAuth=true") {
+ t.Fatalf("error should mention explicit opt-in, got %v", err)
+ }
+ if !strings.Contains(logs, "remote_cdp.proxy_auth_blocked") || !strings.Contains(logs, "203.0.113.10") {
+ t.Fatalf("audit log missing blocked event/target host: %s", logs)
+ }
+ if !strings.Contains(logs, "proxy.example:8080") {
+ t.Fatalf("audit log missing redacted proxy endpoint: %s", logs)
+ }
+ if strings.Contains(logs, "super-secret") {
+ t.Fatalf("audit log leaked proxy password: %s", logs)
+ }
+}
+
+func TestInitRemoteCDPRefusesProxyAuthBeforeProbe(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ AttachAllowHosts: []string{"203.0.113.10"},
+ AttachAllowSchemes: []string{"ws"},
+ Proxy: config.BrowserProxyConfig{
+ Server: "http://proxy.example:8080",
+ Username: "user",
+ Password: "super-secret",
+ },
+ }
+
+ var err error
+ logs := captureSlog(t, func() {
+ _, _, _, _, _, err = InitRemoteCDP(context.Background(), cfg, "ws://203.0.113.10:9222/devtools/browser/abc")
+ })
+ if err == nil {
+ t.Fatal("expected remote CDP proxy auth forwarding to be refused")
+ }
+ if !strings.Contains(err.Error(), "security.attach.forwardProxyAuth=true") {
+ t.Fatalf("error should mention explicit opt-in, got %v", err)
+ }
+ if !strings.Contains(logs, "remote_cdp.proxy_auth_blocked") || !strings.Contains(logs, "203.0.113.10") {
+ t.Fatalf("audit log missing blocked event/target host: %s", logs)
+ }
+ if strings.Contains(logs, "super-secret") {
+ t.Fatalf("audit log leaked proxy password: %s", logs)
+ }
+}
+
+func TestInitRemoteCDPRejectsDisallowedAttachSchemeBeforeProbe(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ AttachAllowHosts: []string{"*"},
+ AttachAllowSchemes: []string{"ws"},
+ }
+
+ _, _, _, _, _, err := InitRemoteCDP(context.Background(), cfg, "http://203.0.113.10:9222")
+ if err == nil {
+ t.Fatal("expected disallowed attach scheme to be rejected")
+ }
+ if !strings.Contains(err.Error(), "scheme") || !strings.Contains(err.Error(), "not allowed") {
+ t.Fatalf("error should mention disallowed scheme, got %v", err)
+ }
+}
+
+func TestRemoteProxyAuthAllowsExplicitOptInAndAuditsForward(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ AttachForwardProxyAuth: true,
+ Proxy: config.BrowserProxyConfig{
+ Server: "http://proxy.example:8080",
+ Username: "user",
+ Password: "super-secret",
+ },
+ }
+
+ if err := requireRemoteProxyAuthOptIn("ws://203.0.113.10:9222/devtools/browser/abc", cfg); err != nil {
+ t.Fatalf("requireRemoteProxyAuthOptIn returned %v, want nil", err)
+ }
+
+ logs := captureSlog(t, func() {
+ auditRemoteProxyAuthForward("ws://203.0.113.10:9222/devtools/browser/abc", cfg)
+ })
+ if !strings.Contains(logs, "remote_cdp.proxy_auth_forwarded") || !strings.Contains(logs, "203.0.113.10") {
+ t.Fatalf("audit log missing forwarded event/target host: %s", logs)
+ }
+ if !strings.Contains(logs, "proxy.example:8080") {
+ t.Fatalf("audit log missing redacted proxy endpoint: %s", logs)
+ }
+ if strings.Contains(logs, "super-secret") {
+ t.Fatalf("audit log leaked proxy password: %s", logs)
+ }
+}
+
+func TestRemoteProxyAuthNoopWithoutCredentials(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ Proxy: config.BrowserProxyConfig{Server: "http://proxy.example:8080"},
+ }
+ logs := captureSlog(t, func() {
+ if err := requireRemoteProxyAuthOptIn("ws://203.0.113.10:9222/devtools/browser/abc", cfg); err != nil {
+ t.Fatalf("requireRemoteProxyAuthOptIn returned %v, want nil", err)
+ }
+ auditRemoteProxyAuthForward("ws://203.0.113.10:9222/devtools/browser/abc", cfg)
+ })
+ if logs != "" {
+ t.Fatalf("unexpected audit log without proxy credentials: %s", logs)
+ }
+}
+
+func captureSlog(t *testing.T, fn func()) string {
+ t.Helper()
+ var buf bytes.Buffer
+ old := slog.Default()
+ slog.SetDefault(slog.New(slog.NewJSONHandler(&buf, nil)))
+ defer slog.SetDefault(old)
+ fn()
+ return buf.String()
+}
diff --git a/internal/bridge/wait_for_exit.go b/internal/bridge/wait_for_exit.go
new file mode 100644
index 00000000..8b452270
--- /dev/null
+++ b/internal/bridge/wait_for_exit.go
@@ -0,0 +1,36 @@
+package bridge
+
+import "time"
+
+// var (not const) so tests can shrink the poll interval.
+var chromeExitPollInterval = 50 * time.Millisecond
+
+// Test seams: counted by unit tests instead of signalling real processes.
+var (
+ terminateChromeByProfileDirFunc = terminateChromeByProfileDir
+ killChromeByProfileDirFunc = killChromeByProfileDir
+)
+
+func waitForChromeExit(profileDir string, timeout time.Duration) bool {
+ if profileDir == "" {
+ return true
+ }
+ deadline := time.Now().Add(timeout)
+ for {
+ if len(findChromePIDsByProfileDirFunc(profileDir)) == 0 {
+ return true
+ }
+ if time.Now().After(deadline) {
+ return false
+ }
+ remaining := time.Until(deadline)
+ sleep := chromeExitPollInterval
+ if remaining < sleep {
+ sleep = remaining
+ }
+ if sleep <= 0 {
+ return false
+ }
+ time.Sleep(sleep)
+ }
+}
diff --git a/internal/bridge/worker_stealth.go b/internal/bridge/worker_stealth.go
index 817824c1..f9d0c6d1 100644
--- a/internal/bridge/worker_stealth.go
+++ b/internal/bridge/worker_stealth.go
@@ -18,7 +18,7 @@ func (b *Bridge) installWorkerStealthParity(ctx context.Context) {
if b == nil || b.Config == nil {
return
}
- if config.NativeCloakStealthEnabled(b.Config) {
+ if config.PinchTabStealthDefaultsDisabled(b.Config) {
return
}
@@ -38,7 +38,7 @@ func (b *Bridge) installWorkerStealthParity(ctx context.Context) {
}
func (b *Bridge) applyWorkerStealth(parent context.Context, targetID target.ID, targetType string) {
- if b == nil || config.NativeCloakStealthEnabled(b.Config) {
+ if b == nil || config.PinchTabStealthDefaultsDisabled(b.Config) {
return
}
diff --git a/internal/browserprobe/binary.go b/internal/browserprobe/binary.go
new file mode 100644
index 00000000..55efa16f
--- /dev/null
+++ b/internal/browserprobe/binary.go
@@ -0,0 +1,118 @@
+package browserprobe
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+)
+
+// BinaryDiscovery captures both the selected executable and the search space
+// inspected, so callers can produce useful diagnostics without duplicating
+// discovery logic.
+type BinaryDiscovery struct {
+ Found string
+ Probed []string
+}
+
+var chromeBinaryNames = []string{
+ "google-chrome",
+ "google-chrome-stable",
+ "chromium",
+ "chromium-browser",
+ "chrome",
+}
+
+var cloakBinaryNames = []string{
+ "cloakbrowser",
+}
+
+// DiscoverChromeBinary returns the first executable Chrome/Chromium candidate
+// found via PATH or known install locations for goos.
+func DiscoverChromeBinary(goos string) BinaryDiscovery {
+ return DiscoverBinary(chromeBinaryNames, ChromeCommonPaths(goos))
+}
+
+// DiscoverCloakBrowserBinary returns the first executable CloakBrowser
+// candidate found via PATH or known install locations for goos.
+func DiscoverCloakBrowserBinary(goos string) BinaryDiscovery {
+ return DiscoverBinary(cloakBinaryNames, CloakCommonPaths(goos))
+}
+
+// ChromeCommonPaths returns per-OS Chrome install paths probed after PATH
+// misses.
+func ChromeCommonPaths(goos string) []string {
+ switch goos {
+ case "linux":
+ return []string{
+ "/usr/bin/google-chrome",
+ "/usr/bin/google-chrome-stable",
+ "/usr/bin/chromium",
+ "/usr/bin/chromium-browser",
+ "/opt/google/chrome/chrome",
+ }
+ case "darwin":
+ return []string{
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
+ "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
+ }
+ case "windows":
+ return []string{
+ `C:\Program Files\Google\Chrome\Application\chrome.exe`,
+ `C:\Program Files (x86)\Google\Chrome\Application\chrome.exe`,
+ }
+ default:
+ return nil
+ }
+}
+
+// CloakCommonPaths returns per-OS CloakBrowser install paths probed after PATH
+// misses.
+func CloakCommonPaths(goos string) []string {
+ switch goos {
+ case "linux", "darwin":
+ paths := []string{
+ "/opt/cloakbrowser/chrome",
+ }
+ if home := homeDir(); home != "" {
+ paths = append(paths, filepath.Join(home, ".cloakbrowser", "chrome"))
+ }
+ return paths
+ default:
+ return nil
+ }
+}
+
+// DiscoverBinary returns the first executable found via PATH then fallback
+// paths; Probed lists every location inspected for diagnostic messages.
+func DiscoverBinary(names, paths []string) BinaryDiscovery {
+ var probed []string
+ for _, name := range names {
+ probed = append(probed, "$PATH:"+name)
+ if p, err := exec.LookPath(name); err == nil {
+ return BinaryDiscovery{Found: p, Probed: probed}
+ }
+ }
+ for _, p := range paths {
+ probed = append(probed, p)
+ info, err := os.Stat(p)
+ if err != nil || info.IsDir() {
+ continue
+ }
+ if info.Mode()&0o111 == 0 {
+ continue
+ }
+ return BinaryDiscovery{Found: p, Probed: probed}
+ }
+ return BinaryDiscovery{Probed: probed}
+}
+
+func homeDir() string {
+ if home := os.Getenv("HOME"); home != "" {
+ return home
+ }
+ if home, err := os.UserHomeDir(); err == nil {
+ return home
+ }
+ return ""
+}
diff --git a/internal/browserprobe/binary_test.go b/internal/browserprobe/binary_test.go
new file mode 100644
index 00000000..2c0c9be8
--- /dev/null
+++ b/internal/browserprobe/binary_test.go
@@ -0,0 +1,48 @@
+package browserprobe
+
+import (
+ "os"
+ "path/filepath"
+ "runtime"
+ "testing"
+)
+
+func TestDiscoverBinaryPrefersPath(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("PATH executable stub requires unix shell permissions")
+ }
+ dir := t.TempDir()
+ pathBinary := filepath.Join(dir, "fake-browser")
+ if err := os.WriteFile(pathBinary, []byte("#!/bin/sh\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ fallback := filepath.Join(t.TempDir(), "fake-browser")
+ if err := os.WriteFile(fallback, []byte("#!/bin/sh\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PATH", dir)
+
+ got := DiscoverBinary([]string{"fake-browser"}, []string{fallback})
+ if got.Found != pathBinary {
+ t.Fatalf("Found = %q, want %q", got.Found, pathBinary)
+ }
+}
+
+func TestDiscoverBinaryReportsProbedPaths(t *testing.T) {
+ t.Setenv("PATH", t.TempDir())
+ fallback := filepath.Join(t.TempDir(), "missing-browser")
+
+ got := DiscoverBinary([]string{"missing-browser"}, []string{fallback})
+ if got.Found != "" {
+ t.Fatalf("Found = %q, want empty", got.Found)
+ }
+ want := []string{"$PATH:missing-browser", fallback}
+ if len(got.Probed) != len(want) {
+ t.Fatalf("Probed = %v, want %v", got.Probed, want)
+ }
+ for i := range want {
+ if got.Probed[i] != want[i] {
+ t.Fatalf("Probed = %v, want %v", got.Probed, want)
+ }
+ }
+}
diff --git a/internal/browserprobe/fonts.go b/internal/browserprobe/fonts.go
new file mode 100644
index 00000000..e930aa31
--- /dev/null
+++ b/internal/browserprobe/fonts.go
@@ -0,0 +1,96 @@
+package browserprobe
+
+import (
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "time"
+)
+
+// WindowsFingerprintFonts lists font-family substrings expected on a
+// Windows-fingerprint host; any one match passes the check.
+var WindowsFingerprintFonts = []string{
+ "arial",
+ "times new roman",
+ "calibri",
+ "segoe ui",
+}
+
+// LinuxFontDirs are scanned when fc-list is missing.
+var LinuxFontDirs = []string{
+ "/usr/share/fonts",
+ "/usr/local/share/fonts",
+ "/var/lib/fonts",
+}
+
+type WindowsFontProbe struct {
+ Matched []string
+ Source string
+ Expected []string
+}
+
+func ProbeWindowsFingerprintFonts(ctx context.Context) WindowsFontProbe {
+ if matched, err := probeFontsViaFcList(ctx); err == nil {
+ return WindowsFontProbe{
+ Matched: matched,
+ Source: "fc-list",
+ Expected: append([]string(nil), WindowsFingerprintFonts...),
+ }
+ }
+ return WindowsFontProbe{
+ Matched: probeFontsViaFilesystem(LinuxFontDirs),
+ Source: "filesystem",
+ Expected: append([]string(nil), WindowsFingerprintFonts...),
+ }
+}
+
+func probeFontsViaFcList(ctx context.Context) ([]string, error) {
+ if _, err := exec.LookPath("fc-list"); err != nil {
+ return nil, err
+ }
+ cctx, cancel := context.WithTimeout(ctx, 3*time.Second)
+ defer cancel()
+ out, err := exec.CommandContext(cctx, "fc-list", ":", "family").Output()
+ if err != nil {
+ return nil, err
+ }
+ lower := strings.ToLower(string(out))
+ var found []string
+ for _, target := range WindowsFingerprintFonts {
+ if strings.Contains(lower, target) {
+ found = append(found, target)
+ }
+ }
+ return found, nil
+}
+
+func probeFontsViaFilesystem(dirs []string) []string {
+ var found []string
+ seen := map[string]struct{}{}
+ for _, dir := range dirs {
+ _ = filepath.WalkDir(dir, func(path string, _ os.DirEntry, walkErr error) error {
+ if walkErr != nil {
+ return nil
+ }
+ base := strings.ToLower(filepath.Base(path))
+ for _, target := range WindowsFingerprintFonts {
+ // fc-list searches by family; filenames typically collapse
+ // "Times New Roman" -> "times" and "Segoe UI" -> "segoeui",
+ // so match the first whitespace-delimited token.
+ token := strings.Fields(target)[0]
+ if !strings.Contains(base, token) {
+ continue
+ }
+ if _, ok := seen[target]; ok {
+ continue
+ }
+ seen[target] = struct{}{}
+ found = append(found, target)
+ }
+ return nil
+ })
+ }
+ return found
+}
diff --git a/internal/browserprobe/fonts_test.go b/internal/browserprobe/fonts_test.go
new file mode 100644
index 00000000..71b837f9
--- /dev/null
+++ b/internal/browserprobe/fonts_test.go
@@ -0,0 +1,28 @@
+package browserprobe
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestProbeFontsViaFilesystemMatchesWindowsFontTokens(t *testing.T) {
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, "Arial.ttf"), []byte(""), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "segoeui.ttf"), []byte(""), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ got := probeFontsViaFilesystem([]string{dir})
+ want := []string{"arial", "segoe ui"}
+ if len(got) != len(want) {
+ t.Fatalf("matched = %v, want %v", got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("matched = %v, want %v", got, want)
+ }
+ }
+}
diff --git a/internal/cli/actions/actions_instance.go b/internal/cli/actions/actions_instance.go
index c82ff458..bd912892 100644
--- a/internal/cli/actions/actions_instance.go
+++ b/internal/cli/actions/actions_instance.go
@@ -27,6 +27,12 @@ func InstanceStart(client *http.Client, base, token string, cmd *cobra.Command)
"allowedDomains": domains,
}
}
+ if v, _ := cmd.Flags().GetString("browser"); v != "" {
+ body["browserTarget"] = v
+ }
+ if fallbacks, _ := cmd.Flags().GetStringArray("browser-fallback"); len(fallbacks) > 0 {
+ body["fallbackTargets"] = fallbacks
+ }
apiclient.DoPost(client, base, token, "/instances/start", body)
}
diff --git a/internal/config/browser_provider.go b/internal/config/browser_provider.go
index bca2b11e..542f6916 100644
--- a/internal/config/browser_provider.go
+++ b/internal/config/browser_provider.go
@@ -1,6 +1,9 @@
package config
-import "strings"
+import (
+ "fmt"
+ "strings"
+)
const (
BrowserProviderChrome = "chrome"
@@ -16,14 +19,37 @@ func NormalizeBrowserProvider(provider string) string {
}
}
+func ParseBrowserProvider(provider string) (string, error) {
+ switch strings.ToLower(strings.TrimSpace(provider)) {
+ case "", BrowserProviderChrome:
+ return BrowserProviderChrome, nil
+ case BrowserProviderCloak:
+ return BrowserProviderCloak, nil
+ default:
+ return "", fmt.Errorf("invalid browser provider %q (must be chrome or cloak)", provider)
+ }
+}
+
func IsCloakBrowserProvider(provider string) bool {
return NormalizeBrowserProvider(provider) == BrowserProviderCloak
}
-func NativeCloakStealthEnabled(cfg *RuntimeConfig) bool {
- return cfg != nil &&
- IsCloakBrowserProvider(cfg.BrowserProvider) &&
- cfg.Cloak.DisableDefaultStealthArgs
+// CloakBrowserProviderActive reports only the configured browser provider. It
+// deliberately does not mean PinchTab's stealth layer should be disabled.
+func CloakBrowserProviderActive(cfg *RuntimeConfig) bool {
+ if cfg == nil || !IsCloakBrowserProvider(cfg.BrowserProvider) {
+ return false
+ }
+ return true
+}
+
+// PinchTabStealthDefaultsDisabled is the explicit opt-out from PinchTab's JS
+// stealth overlays and automation-hiding launch flags.
+func PinchTabStealthDefaultsDisabled(cfg *RuntimeConfig) bool {
+ if !CloakBrowserProviderActive(cfg) {
+ return false
+ }
+ return cfg.Cloak.DisableDefaultStealthArgs
}
func hasCloakBrowserConfig(c CloakBrowserConfig) bool {
diff --git a/internal/config/browser_provider_test.go b/internal/config/browser_provider_test.go
new file mode 100644
index 00000000..36aa2542
--- /dev/null
+++ b/internal/config/browser_provider_test.go
@@ -0,0 +1,74 @@
+package config
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestParseBrowserProvider(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ want string
+ wantErr string
+ }{
+ {name: "empty defaults chrome", input: "", want: BrowserProviderChrome},
+ {name: "chrome", input: "chrome", want: BrowserProviderChrome},
+ {name: "cloak trimmed case", input: " Cloak ", want: BrowserProviderCloak},
+ {name: "rejects unknown", input: "cloack", wantErr: "invalid browser provider"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := ParseBrowserProvider(tt.input)
+ if tt.wantErr != "" {
+ if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
+ t.Fatalf("ParseBrowserProvider(%q) error = %v, want %q", tt.input, err, tt.wantErr)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("ParseBrowserProvider(%q) unexpected error: %v", tt.input, err)
+ }
+ if got != tt.want {
+ t.Fatalf("ParseBrowserProvider(%q) = %q, want %q", tt.input, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestCloakStealthBooleansAreIndependent(t *testing.T) {
+ chromeRemote := &RuntimeConfig{
+ BrowserProvider: BrowserProviderChrome,
+ RemoteCDPURL: "ws://127.0.0.1:9222/devtools/browser/id",
+ }
+ if CloakBrowserProviderActive(chromeRemote) {
+ t.Fatal("remote CDP attach must not imply native Cloak stealth without cloak provider")
+ }
+ if PinchTabStealthDefaultsDisabled(chromeRemote) {
+ t.Fatal("remote CDP attach must not disable PinchTab stealth defaults without cloak provider opt-in")
+ }
+
+ cloakWithDefaults := &RuntimeConfig{
+ BrowserProvider: BrowserProviderCloak,
+ }
+ if !CloakBrowserProviderActive(cloakWithDefaults) {
+ t.Fatal("cloak provider should report native Cloak stealth active")
+ }
+ if PinchTabStealthDefaultsDisabled(cloakWithDefaults) {
+ t.Fatal("native Cloak stealth must not imply PinchTab defaults are disabled")
+ }
+
+ cloakWithoutPinchTabDefaults := &RuntimeConfig{
+ BrowserProvider: BrowserProviderCloak,
+ Cloak: CloakBrowserRuntimeConfig{
+ DisableDefaultStealthArgs: true,
+ },
+ }
+ if !CloakBrowserProviderActive(cloakWithoutPinchTabDefaults) {
+ t.Fatal("cloak provider should report native Cloak stealth active")
+ }
+ if !PinchTabStealthDefaultsDisabled(cloakWithoutPinchTabDefaults) {
+ t.Fatal("explicit disableDefaultStealthArgs should disable PinchTab defaults")
+ }
+}
diff --git a/internal/config/browser_proxy.go b/internal/config/browser_proxy.go
new file mode 100644
index 00000000..ef4a809b
--- /dev/null
+++ b/internal/config/browser_proxy.go
@@ -0,0 +1,211 @@
+package config
+
+import (
+ "fmt"
+ "net"
+ "strconv"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/config/geo"
+)
+
+// BrowserProxyConfig describes a single browser-level proxy.
+//
+// Server is "<scheme>://<host>:<port>" (http, https, socks4, socks5); embedded
+// credentials are rejected — use Username/Password. Empty Server disables the
+// proxy and ignores other fields. Proxy auth is delivered via CDP at the
+// bridge layer (see internal/bridge/runtime/proxy_auth.go) because Chrome
+// rejects credentials in --proxy-server.
+type BrowserProxyConfig struct {
+ Server string `json:"server,omitempty"`
+ BypassList []string `json:"bypassList,omitempty"`
+ Username string `json:"username,omitempty"`
+ Password string `json:"password,omitempty"`
+ Geo *BrowserProxyGeoConfig `json:"geo,omitempty"`
+}
+
+// BrowserProxyGeoConfig is explicit geo-alignment data; zero-value fields mean "no opinion".
+type BrowserProxyGeoConfig struct {
+ Timezone string `json:"timezone,omitempty"`
+ Locale string `json:"locale,omitempty"`
+ WebRTCIP string `json:"webrtcIP,omitempty"`
+ CountryISO string `json:"countryISO,omitempty"`
+}
+
+func (g BrowserProxyGeoConfig) IsZero() bool {
+ return g == BrowserProxyGeoConfig{}
+}
+
+var validProxySchemes = map[string]struct{}{
+ "http": {},
+ "https": {},
+ "socks4": {},
+ "socks5": {},
+}
+
+func (p BrowserProxyConfig) IsZero() bool {
+ return strings.TrimSpace(p.Server) == ""
+}
+
+// Redacted masks Password to "***" when set; empty Password stays empty so callers can distinguish absent vs hidden.
+func (p BrowserProxyConfig) Redacted() BrowserProxyConfig {
+ out := BrowserProxyConfig{
+ Server: p.Server,
+ Username: p.Username,
+ Password: p.Password,
+ }
+ if len(p.BypassList) > 0 {
+ out.BypassList = append([]string(nil), p.BypassList...)
+ }
+ if p.Geo != nil {
+ geoCopy := *p.Geo
+ out.Geo = &geoCopy
+ }
+ if p.Password != "" {
+ out.Password = "***"
+ }
+ return out
+}
+
+func (p BrowserProxyConfig) GeoInfo() geo.Info {
+ if p.Geo == nil {
+ return geo.Info{}
+ }
+ return geo.Info{
+ Timezone: p.Geo.Timezone,
+ Locale: p.Geo.Locale,
+ WebRTCIP: p.Geo.WebRTCIP,
+ CountryISO: p.Geo.CountryISO,
+ }
+}
+
+// ParseProxyServer splits a proxy server URL strictly; rejects embedded userinfo to prevent credential leak.
+func ParseProxyServer(server string) (scheme, host string, port int, err error) {
+ server = strings.TrimSpace(server)
+ if server == "" {
+ return "", "", 0, fmt.Errorf("proxy server is empty")
+ }
+ idx := strings.Index(server, "://")
+ if idx <= 0 {
+ return "", "", 0, fmt.Errorf("proxy server %q must include a scheme (http, https, socks4, socks5)", server)
+ }
+ scheme = strings.ToLower(server[:idx])
+ if _, ok := validProxySchemes[scheme]; !ok {
+ return "", "", 0, fmt.Errorf("proxy server scheme %q is not supported (use http, https, socks4, or socks5)", scheme)
+ }
+ rest := server[idx+3:]
+ if rest == "" {
+ return "", "", 0, fmt.Errorf("proxy server %q is missing host:port", server)
+ }
+ if strings.ContainsRune(rest, '@') {
+ return "", "", 0, fmt.Errorf("proxy server %q must not include embedded credentials; use the username/password fields", server)
+ }
+ if slash := strings.Index(rest, "/"); slash >= 0 {
+ rest = rest[:slash]
+ }
+ h, p, splitErr := net.SplitHostPort(rest)
+ if splitErr != nil {
+ return "", "", 0, fmt.Errorf("proxy server %q must be of the form scheme://host:port: %w", server, splitErr)
+ }
+ if strings.TrimSpace(h) == "" {
+ return "", "", 0, fmt.Errorf("proxy server %q has empty host", server)
+ }
+ portNum, atoiErr := strconv.Atoi(p)
+ if atoiErr != nil {
+ return "", "", 0, fmt.Errorf("proxy server %q port %q is not numeric: %w", server, p, atoiErr)
+ }
+ if portNum < 1 || portNum > 65535 {
+ return "", "", 0, fmt.Errorf("proxy server %q port %d out of range (1-65535)", server, portNum)
+ }
+ return scheme, h, portNum, nil
+}
+
+// ValidateBrowserProxy returns nil when disabled (empty Server); otherwise validates server, bypass, and credential pairing.
+func ValidateBrowserProxy(field string, p BrowserProxyConfig) []error {
+ if p.IsZero() {
+ return nil
+ }
+ var errs []error
+
+ if _, _, _, err := ParseProxyServer(p.Server); err != nil {
+ errs = append(errs, ValidationError{
+ Field: field + ".server",
+ Message: err.Error(),
+ })
+ }
+
+ for i, pat := range p.BypassList {
+ trimmed := strings.TrimSpace(pat)
+ if trimmed == "" {
+ errs = append(errs, ValidationError{
+ Field: fmt.Sprintf("%s.bypassList[%d]", field, i),
+ Message: "bypass pattern must not be empty",
+ })
+ continue
+ }
+ if strings.ContainsAny(trimmed, " \t\n\r;") {
+ errs = append(errs, ValidationError{
+ Field: fmt.Sprintf("%s.bypassList[%d]", field, i),
+ Message: fmt.Sprintf("bypass pattern %q must not contain whitespace or ';' (use multiple entries)", trimmed),
+ })
+ }
+ }
+
+ if p.Geo != nil && !p.Geo.IsZero() {
+ if err := geo.Validate(p.GeoInfo()); err != nil {
+ errs = append(errs, ValidationError{
+ Field: field + ".geo",
+ Message: err.Error(),
+ })
+ }
+ }
+
+ hasUser := strings.TrimSpace(p.Username) != ""
+ hasPass := p.Password != ""
+ if hasUser && !hasPass {
+ errs = append(errs, ValidationError{
+ Field: field + ".password",
+ Message: "password is required when username is set",
+ })
+ }
+ if hasPass && !hasUser {
+ errs = append(errs, ValidationError{
+ Field: field + ".username",
+ Message: "username is required when password is set",
+ })
+ }
+
+ return errs
+}
+
+// BrowserProxyFlags returns credential-free --proxy-server/--proxy-bypass-list flags; auth is delivered via CDP.
+func BrowserProxyFlags(p BrowserProxyConfig) []string {
+ if p.IsZero() {
+ return nil
+ }
+ scheme, host, port, err := ParseProxyServer(p.Server)
+ if err != nil {
+ // Caller should have validated; fail open rather than crash the launch.
+ return nil
+ }
+ authority := net.JoinHostPort(host, strconv.Itoa(port))
+ flags := []string{
+ fmt.Sprintf("--proxy-server=%s://%s", scheme, authority),
+ }
+ if bypass := joinBypassList(p.BypassList); bypass != "" {
+ flags = append(flags, "--proxy-bypass-list="+bypass)
+ }
+ return flags
+}
+
+func joinBypassList(items []string) string {
+ cleaned := make([]string, 0, len(items))
+ for _, it := range items {
+ trimmed := strings.TrimSpace(it)
+ if trimmed == "" {
+ continue
+ }
+ cleaned = append(cleaned, trimmed)
+ }
+ return strings.Join(cleaned, ";")
+}
diff --git a/internal/config/browser_proxy_test.go b/internal/config/browser_proxy_test.go
new file mode 100644
index 00000000..a6734bbe
--- /dev/null
+++ b/internal/config/browser_proxy_test.go
@@ -0,0 +1,484 @@
+package config
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+)
+
+func TestValidateBrowserProxy_TableDriven(t *testing.T) {
+ tests := []struct {
+ name string
+ proxy BrowserProxyConfig
+ wantErr bool
+ wantSub string
+ }{
+ {name: "empty disables proxy", proxy: BrowserProxyConfig{}},
+ {name: "good http",
+ proxy: BrowserProxyConfig{Server: "http://proxy.example.com:8080"}},
+ {name: "good https",
+ proxy: BrowserProxyConfig{Server: "https://proxy.example.com:8443"}},
+ {name: "good socks5",
+ proxy: BrowserProxyConfig{Server: "socks5://10.0.0.1:1080"}},
+ {name: "good socks4",
+ proxy: BrowserProxyConfig{Server: "socks4://10.0.0.1:1080"}},
+ {name: "good with bypass list",
+ proxy: BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ BypassList: []string{"*.local", "127.0.0.1"},
+ }},
+ {name: "good with credentials",
+ proxy: BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Username: "alice",
+ Password: "s3cr3t",
+ }},
+ {name: "bad scheme",
+ proxy: BrowserProxyConfig{Server: "ftp://proxy.example.com:21"},
+ wantErr: true, wantSub: "scheme"},
+ {name: "missing scheme",
+ proxy: BrowserProxyConfig{Server: "proxy.example.com:8080"},
+ wantErr: true, wantSub: "scheme"},
+ {name: "missing host",
+ proxy: BrowserProxyConfig{Server: "http://:8080"},
+ wantErr: true, wantSub: "host"},
+ {name: "missing port",
+ proxy: BrowserProxyConfig{Server: "http://proxy.example.com"},
+ wantErr: true, wantSub: "host:port"},
+ {name: "port out of range",
+ proxy: BrowserProxyConfig{Server: "http://proxy.example.com:99999"},
+ wantErr: true, wantSub: "port"},
+ {name: "embedded credentials rejected",
+ proxy: BrowserProxyConfig{Server: "http://user:[email protected]:8080"},
+ wantErr: true, wantSub: "embedded credentials"},
+ {name: "username without password",
+ proxy: BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Username: "alice",
+ },
+ wantErr: true, wantSub: "password is required"},
+ {name: "password without username",
+ proxy: BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Password: "secret",
+ },
+ wantErr: true, wantSub: "username is required"},
+ {name: "bypass with whitespace",
+ proxy: BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ BypassList: []string{"foo bar"},
+ },
+ wantErr: true, wantSub: "whitespace"},
+ {name: "bypass with semicolon",
+ proxy: BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ BypassList: []string{"a;b"},
+ },
+ wantErr: true, wantSub: "';'"},
+ {name: "empty bypass entry",
+ proxy: BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ BypassList: []string{""},
+ },
+ wantErr: true, wantSub: "must not be empty"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ errs := ValidateBrowserProxy("browser.proxy", tt.proxy)
+ if tt.wantErr {
+ if len(errs) == 0 {
+ t.Fatalf("expected validation error, got none")
+ }
+ if tt.wantSub != "" {
+ joined := ""
+ for _, e := range errs {
+ joined += e.Error() + "\n"
+ }
+ if !strings.Contains(joined, tt.wantSub) {
+ t.Errorf("expected error to contain %q, got: %s", tt.wantSub, joined)
+ }
+ }
+ return
+ }
+ if len(errs) > 0 {
+ t.Fatalf("unexpected validation errors: %v", errs)
+ }
+ })
+ }
+}
+
+func TestValidateBrowserProxy_GeoBlock(t *testing.T) {
+ t.Run("good geo accepted", func(t *testing.T) {
+ errs := ValidateBrowserProxy("browser.proxy", BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Geo: &BrowserProxyGeoConfig{
+ Timezone: "Europe/London",
+ Locale: "en-GB",
+ WebRTCIP: "203.0.113.7",
+ CountryISO: "GB",
+ },
+ })
+ if len(errs) != 0 {
+ t.Fatalf("expected no errors, got %v", errs)
+ }
+ })
+ t.Run("bad timezone rejected", func(t *testing.T) {
+ errs := ValidateBrowserProxy("browser.proxy", BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Geo: &BrowserProxyGeoConfig{Timezone: "Not/AZone"},
+ })
+ if len(errs) == 0 {
+ t.Fatal("expected validation error for bad timezone")
+ }
+ })
+ t.Run("bad locale rejected", func(t *testing.T) {
+ errs := ValidateBrowserProxy("browser.proxy", BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Geo: &BrowserProxyGeoConfig{Locale: "EN-gb"},
+ })
+ if len(errs) == 0 {
+ t.Fatal("expected validation error for bad locale")
+ }
+ })
+ t.Run("bad webrtc IP rejected", func(t *testing.T) {
+ errs := ValidateBrowserProxy("browser.proxy", BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Geo: &BrowserProxyGeoConfig{WebRTCIP: "not-an-ip"},
+ })
+ if len(errs) == 0 {
+ t.Fatal("expected validation error for bad webrtc IP")
+ }
+ })
+ t.Run("empty geo block accepted", func(t *testing.T) {
+ errs := ValidateBrowserProxy("browser.proxy", BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Geo: &BrowserProxyGeoConfig{},
+ })
+ if len(errs) != 0 {
+ t.Fatalf("empty geo should not fail validation, got %v", errs)
+ }
+ })
+}
+
+func TestMigrateLegacyBrowserConfig_GeoCarriesIntoSynthesizedTarget(t *testing.T) {
+ bc := &BrowserConfig{
+ Provider: BrowserProviderChrome,
+ Proxy: BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Geo: &BrowserProxyGeoConfig{
+ Timezone: "Europe/London",
+ Locale: "en-GB",
+ },
+ },
+ }
+ synthesized, conflict := migrateLegacyBrowserConfig(bc)
+ if !synthesized || conflict {
+ t.Fatalf("expected synthesized=true conflict=false, got %v/%v", synthesized, conflict)
+ }
+ target, ok := bc.Targets[DefaultBrowserTargetName]
+ if !ok {
+ t.Fatal("default target not synthesized")
+ }
+ if target.Proxy.Geo == nil {
+ t.Fatal("geo block missing from synthesized target")
+ }
+ if target.Proxy.Geo.Timezone != "Europe/London" || target.Proxy.Geo.Locale != "en-GB" {
+ t.Errorf("geo not migrated correctly: %+v", target.Proxy.Geo)
+ }
+}
+
+func TestBrowserProxyRedacted(t *testing.T) {
+ t.Run("masks non-empty password", func(t *testing.T) {
+ p := BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ BypassList: []string{"*.local"},
+ Username: "alice",
+ Password: "s3cr3t",
+ }
+ r := p.Redacted()
+ if r.Password != "***" {
+ t.Errorf("expected redacted password '***', got %q", r.Password)
+ }
+ if p.Password != "s3cr3t" {
+ t.Errorf("original password mutated: %q", p.Password)
+ }
+ if r.Server != p.Server || r.Username != p.Username {
+ t.Errorf("non-secret fields mutated: %+v", r)
+ }
+ if len(r.BypassList) != 1 || r.BypassList[0] != "*.local" {
+ t.Errorf("bypass list lost: %+v", r.BypassList)
+ }
+ r.BypassList[0] = "mutated"
+ if p.BypassList[0] != "*.local" {
+ t.Errorf("redaction did not deep-copy bypass list")
+ }
+ })
+
+ t.Run("empty password stays empty", func(t *testing.T) {
+ p := BrowserProxyConfig{Server: "http://proxy.example.com:8080"}
+ r := p.Redacted()
+ if r.Password != "" {
+ t.Errorf("expected empty password, got %q", r.Password)
+ }
+ })
+}
+
+func TestBrowserProxyFlags(t *testing.T) {
+ t.Run("disabled proxy emits no flags", func(t *testing.T) {
+ flags := BrowserProxyFlags(BrowserProxyConfig{})
+ if len(flags) != 0 {
+ t.Fatalf("expected no flags, got %v", flags)
+ }
+ })
+
+ t.Run("server only", func(t *testing.T) {
+ flags := BrowserProxyFlags(BrowserProxyConfig{Server: "http://proxy.example.com:8080"})
+ if len(flags) != 1 {
+ t.Fatalf("expected 1 flag, got %v", flags)
+ }
+ want := "--proxy-server=http://proxy.example.com:8080"
+ if flags[0] != want {
+ t.Errorf("want %q, got %q", want, flags[0])
+ }
+ })
+
+ t.Run("with bypass list", func(t *testing.T) {
+ flags := BrowserProxyFlags(BrowserProxyConfig{
+ Server: "socks5://10.0.0.1:1080",
+ BypassList: []string{"*.local", "127.0.0.1"},
+ })
+ if len(flags) != 2 {
+ t.Fatalf("expected 2 flags, got %v", flags)
+ }
+ if flags[0] != "--proxy-server=socks5://10.0.0.1:1080" {
+ t.Errorf("unexpected flag[0]: %q", flags[0])
+ }
+ if flags[1] != "--proxy-bypass-list=*.local;127.0.0.1" {
+ t.Errorf("unexpected flag[1]: %q", flags[1])
+ }
+ })
+
+ t.Run("ipv6 host stays bracketed", func(t *testing.T) {
+ flags := BrowserProxyFlags(BrowserProxyConfig{Server: "http://[2001:db8::1]:8080"})
+ if len(flags) != 1 {
+ t.Fatalf("expected 1 flag, got %v", flags)
+ }
+ if flags[0] != "--proxy-server=http://[2001:db8::1]:8080" {
+ t.Errorf("unexpected IPv6 proxy flag: %q", flags[0])
+ }
+ })
+
+ t.Run("credentials never leak into flag", func(t *testing.T) {
+ flags := BrowserProxyFlags(BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Username: "alice",
+ Password: "s3cr3t",
+ })
+ for _, f := range flags {
+ if strings.Contains(f, "alice") || strings.Contains(f, "s3cr3t") {
+ t.Errorf("credential leaked into Chrome flag: %q", f)
+ }
+ }
+ })
+}
+
+func TestMigrateLegacyBrowserConfig_ProxyCarriesIntoSynthesizedTarget(t *testing.T) {
+ bc := &BrowserConfig{
+ Provider: BrowserProviderChrome,
+ Proxy: BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Username: "alice",
+ Password: "s3cr3t",
+ },
+ }
+ synthesized, conflict := migrateLegacyBrowserConfig(bc)
+ if !synthesized || conflict {
+ t.Fatalf("expected synthesized=true conflict=false, got synthesized=%v conflict=%v", synthesized, conflict)
+ }
+ target, ok := bc.Targets[DefaultBrowserTargetName]
+ if !ok {
+ t.Fatalf("default target was not synthesized")
+ }
+ if target.Proxy.Server != "http://proxy.example.com:8080" {
+ t.Errorf("proxy server not migrated, got %q", target.Proxy.Server)
+ }
+ if target.Proxy.Password != "s3cr3t" {
+ t.Errorf("proxy password not migrated, got %q", target.Proxy.Password)
+ }
+}
+
+func TestApplyTargetOverride_TargetProxyReplacesGlobal(t *testing.T) {
+ cfg := &RuntimeConfig{
+ BrowserProvider: BrowserProviderChrome,
+ Proxy: BrowserProxyConfig{
+ Server: "http://global.example.com:8080",
+ Username: "global-user",
+ Password: "global-pass",
+ BypassList: []string{"*.global.test"},
+ },
+ Targets: BrowserTargetsConfig{
+ "with-proxy": {
+ Provider: BrowserProviderChrome,
+ Proxy: BrowserProxyConfig{
+ Server: "socks5://target.example.com:1080",
+ BypassList: []string{"*.target.test"},
+ },
+ },
+ "inherits": {
+ Provider: BrowserProviderChrome,
+ },
+ },
+ }
+
+ t.Run("target proxy replaces global entirely", func(t *testing.T) {
+ out := ApplyTargetOverride(cfg, "with-proxy")
+ if out.Proxy.Server != "socks5://target.example.com:1080" {
+ t.Errorf("server not overridden, got %q", out.Proxy.Server)
+ }
+ if out.Proxy.Username != "" || out.Proxy.Password != "" {
+ t.Errorf("global credentials leaked into target proxy: %+v", out.Proxy)
+ }
+ if len(out.Proxy.BypassList) != 1 || out.Proxy.BypassList[0] != "*.target.test" {
+ t.Errorf("target bypass list not used: %+v", out.Proxy.BypassList)
+ }
+ if cfg.Proxy.Server != "http://global.example.com:8080" {
+ t.Errorf("input cfg.Proxy mutated: %+v", cfg.Proxy)
+ }
+ })
+
+ t.Run("target without proxy inherits global", func(t *testing.T) {
+ out := ApplyTargetOverride(cfg, "inherits")
+ if out.Proxy.Server != "http://global.example.com:8080" {
+ t.Errorf("expected to inherit global, got %q", out.Proxy.Server)
+ }
+ if out.Proxy.Username != "global-user" {
+ t.Errorf("expected to inherit global credentials")
+ }
+ })
+}
+
+func TestApplyFileConfigToRuntime_ProxyGeoCopied(t *testing.T) {
+ cfg := &RuntimeConfig{}
+ fc := &FileConfig{
+ Browser: BrowserConfig{
+ Proxy: BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Geo: &BrowserProxyGeoConfig{
+ Timezone: "Europe/London",
+ Locale: "en-GB",
+ WebRTCIP: "203.0.113.7",
+ CountryISO: "GB",
+ },
+ },
+ },
+ }
+
+ ApplyFileConfigToRuntime(cfg, fc)
+
+ if cfg.Proxy.Geo == nil {
+ t.Fatal("proxy geo was not copied to runtime config")
+ }
+ if *cfg.Proxy.Geo != *fc.Browser.Proxy.Geo {
+ t.Fatalf("runtime proxy geo = %+v, want %+v", *cfg.Proxy.Geo, *fc.Browser.Proxy.Geo)
+ }
+ fc.Browser.Proxy.Geo.Timezone = "America/New_York"
+ if cfg.Proxy.Geo.Timezone != "Europe/London" {
+ t.Fatalf("runtime proxy geo aliases file config: %+v", cfg.Proxy.Geo)
+ }
+}
+
+func TestFileConfig_ProxyRoundTrip(t *testing.T) {
+ t.Run("proxy omitted when empty", func(t *testing.T) {
+ fc := FileConfig{
+ Browser: BrowserConfig{Provider: BrowserProviderChrome},
+ }
+ raw, err := json.Marshal(fc)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ if strings.Contains(string(raw), `"proxy"`) {
+ t.Errorf("empty proxy should be omitted, got: %s", string(raw))
+ }
+ })
+
+ t.Run("geo omitted when nil", func(t *testing.T) {
+ fc := FileConfig{
+ Browser: BrowserConfig{
+ Provider: BrowserProviderChrome,
+ Proxy: BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ },
+ },
+ }
+ raw, err := json.Marshal(fc)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ if strings.Contains(string(raw), `"geo"`) {
+ t.Errorf("nil geo should be omitted, got: %s", string(raw))
+ }
+ })
+
+ t.Run("geo round-trips when configured", func(t *testing.T) {
+ fc := FileConfig{
+ Browser: BrowserConfig{
+ Provider: BrowserProviderChrome,
+ Proxy: BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Geo: &BrowserProxyGeoConfig{
+ Timezone: "Europe/London",
+ Locale: "en-GB",
+ WebRTCIP: "203.0.113.7",
+ CountryISO: "GB",
+ },
+ },
+ },
+ }
+ raw, err := json.Marshal(fc)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ var rt FileConfig
+ if err := json.Unmarshal(raw, &rt); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if rt.Browser.Proxy.Geo == nil {
+ t.Fatal("geo lost in round-trip")
+ }
+ if *rt.Browser.Proxy.Geo != *fc.Browser.Proxy.Geo {
+ t.Errorf("geo did not round-trip: got %+v want %+v", *rt.Browser.Proxy.Geo, *fc.Browser.Proxy.Geo)
+ }
+ })
+
+ t.Run("proxy emitted when configured", func(t *testing.T) {
+ fc := FileConfig{
+ Browser: BrowserConfig{
+ Provider: BrowserProviderChrome,
+ Proxy: BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Username: "alice",
+ Password: "s3cr3t",
+ },
+ },
+ }
+ raw, err := json.Marshal(fc)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ // On-disk format intentionally stores raw password; redaction happens at log/HTTP boundaries.
+ if !strings.Contains(string(raw), `"password":"s3cr3t"`) {
+ t.Errorf("on-disk config should contain raw password, got: %s", string(raw))
+ }
+
+ var rt FileConfig
+ if err := json.Unmarshal(raw, &rt); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if rt.Browser.Proxy.Server != fc.Browser.Proxy.Server ||
+ rt.Browser.Proxy.Username != fc.Browser.Proxy.Username ||
+ rt.Browser.Proxy.Password != fc.Browser.Proxy.Password {
+ t.Errorf("proxy did not round-trip: got %+v want %+v", rt.Browser.Proxy, fc.Browser.Proxy)
+ }
+ })
+}
diff --git a/internal/config/browser_targets.go b/internal/config/browser_targets.go
new file mode 100644
index 00000000..ca6587fe
--- /dev/null
+++ b/internal/config/browser_targets.go
@@ -0,0 +1,422 @@
+package config
+
+import (
+ "fmt"
+ "regexp"
+ "sort"
+ "strings"
+)
+
+// DefaultBrowserTargetName is the synthetic target name produced by the legacy-config migration shim.
+const DefaultBrowserTargetName = "default"
+
+var browserTargetNameRegex = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`)
+
+func IsValidBrowserTargetName(name string) bool {
+ return browserTargetNameRegex.MatchString(name)
+}
+
+func isRecognizedBrowserTargetProvider(p string) bool {
+ switch strings.ToLower(strings.TrimSpace(p)) {
+ case BrowserProviderChrome, BrowserProviderCloak:
+ return true
+ default:
+ return false
+ }
+}
+
+func cloneBrowserTargetsConfig(in BrowserTargetsConfig) BrowserTargetsConfig {
+ if len(in) == 0 {
+ return nil
+ }
+ out := make(BrowserTargetsConfig, len(in))
+ for name, target := range in {
+ out[name] = cloneBrowserTarget(target)
+ }
+ return out
+}
+
+func cloneBrowserTarget(in BrowserTargetConfig) BrowserTargetConfig {
+ out := in
+ out.Cloak = cloneCloakBrowserConfig(in.Cloak)
+ out.Proxy = cloneBrowserProxyConfig(in.Proxy)
+ return out
+}
+
+func cloneCloakBrowserConfig(in CloakBrowserConfig) CloakBrowserConfig {
+ out := in
+ if in.StorageQuotaMB != nil {
+ v := *in.StorageQuotaMB
+ out.StorageQuotaMB = &v
+ }
+ if in.DisableDefaultStealthArgs != nil {
+ v := *in.DisableDefaultStealthArgs
+ out.DisableDefaultStealthArgs = &v
+ }
+ return out
+}
+
+func cloneBrowserProxyConfig(in BrowserProxyConfig) BrowserProxyConfig {
+ out := in
+ out.BypassList = append([]string(nil), in.BypassList...)
+ if in.Geo != nil {
+ geo := *in.Geo
+ out.Geo = &geo
+ }
+ return out
+}
+
+// ValidateBrowserTargets validates targets/defaultTarget/fallbackOrder; returns nil when no targets are configured.
+func ValidateBrowserTargets(bc BrowserConfig) []error {
+ if len(bc.Targets) == 0 {
+ return nil
+ }
+
+ var errs []error
+
+ // Stable iteration order so error output is deterministic.
+ names := make([]string, 0, len(bc.Targets))
+ for name := range bc.Targets {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+
+ for _, name := range names {
+ t := bc.Targets[name]
+ if !IsValidBrowserTargetName(name) {
+ errs = append(errs, ValidationError{
+ Field: fmt.Sprintf("browser.targets.%s", name),
+ Message: fmt.Sprintf("invalid target name %q (must match ^[a-z][a-z0-9-]{0,31}$)", name),
+ })
+ }
+ if strings.TrimSpace(t.Provider) == "" {
+ errs = append(errs, ValidationError{
+ Field: fmt.Sprintf("browser.targets.%s.provider", name),
+ Message: "provider is required",
+ })
+ } else if !isRecognizedBrowserTargetProvider(t.Provider) {
+ errs = append(errs, ValidationError{
+ Field: fmt.Sprintf("browser.targets.%s.provider", name),
+ Message: fmt.Sprintf("unknown provider %q (must be chrome or cloak)", t.Provider),
+ })
+ } else if NormalizeBrowserProvider(t.Provider) == BrowserProviderCloak &&
+ strings.TrimSpace(t.Binary) == "" &&
+ strings.TrimSpace(bc.ChromeBinary) == "" {
+ errs = append(errs, ValidationError{
+ Field: fmt.Sprintf("browser.targets.%s.binary", name),
+ Message: "must be set when provider is cloak, or inherited from browser.binary",
+ })
+ }
+ if strings.TrimSpace(t.ExtraFlags) != "" {
+ errs = append(errs, validateTargetExtraFlags(name, t.ExtraFlags)...)
+ }
+ errs = append(errs, validateCloakBrowserConfigAt(fmt.Sprintf("browser.targets.%s.cloak", name), t.Cloak)...)
+ errs = append(errs, ValidateBrowserProxy(fmt.Sprintf("browser.targets.%s.proxy", name), t.Proxy)...)
+ }
+
+ defaultTarget := strings.TrimSpace(bc.DefaultTarget)
+ if dt := strings.TrimSpace(bc.DefaultTarget); dt != "" {
+ if _, ok := bc.Targets[dt]; !ok {
+ errs = append(errs, ValidationError{
+ Field: "browser.defaultTarget",
+ Message: fmt.Sprintf("references unknown target %q", dt),
+ })
+ }
+ } else if len(bc.Targets) > 1 {
+ errs = append(errs, ValidationError{
+ Field: "browser.defaultTarget",
+ Message: "must be set when multiple targets are configured",
+ })
+ }
+
+ fallbackSeen := make(map[string]int, len(bc.FallbackOrder))
+ for i, name := range bc.FallbackOrder {
+ name = strings.TrimSpace(name)
+ if name == "" {
+ errs = append(errs, ValidationError{
+ Field: fmt.Sprintf("browser.fallbackOrder[%d]", i),
+ Message: "target name must not be empty",
+ })
+ continue
+ }
+ if first, ok := fallbackSeen[name]; ok {
+ errs = append(errs, ValidationError{
+ Field: fmt.Sprintf("browser.fallbackOrder[%d]", i),
+ Message: fmt.Sprintf("duplicates target %q already listed at browser.fallbackOrder[%d]", name, first),
+ })
+ continue
+ }
+ fallbackSeen[name] = i
+ if defaultTarget != "" && name == defaultTarget {
+ errs = append(errs, ValidationError{
+ Field: fmt.Sprintf("browser.fallbackOrder[%d]", i),
+ Message: fmt.Sprintf("must not include defaultTarget %q", name),
+ })
+ }
+ if _, ok := bc.Targets[name]; !ok {
+ errs = append(errs, ValidationError{
+ Field: fmt.Sprintf("browser.fallbackOrder[%d]", i),
+ Message: fmt.Sprintf("references unknown target %q", name),
+ })
+ }
+ }
+
+ return errs
+}
+
+func validateTargetExtraFlags(targetName, raw string) []error {
+ flagErrs := validateChromeExtraFlags(raw)
+ if len(flagErrs) == 0 {
+ return nil
+ }
+ out := make([]error, 0, len(flagErrs))
+ field := fmt.Sprintf("browser.targets.%s.extraFlags", targetName)
+ for _, err := range flagErrs {
+ if ve, ok := err.(ValidationError); ok {
+ ve.Field = field
+ out = append(out, ve)
+ continue
+ }
+ out = append(out, ValidationError{Field: field, Message: err.Error()})
+ }
+ return out
+}
+
+// migrateLegacyBrowserConfig synthesizes targets["default"] from legacy fields when targets is empty.
+// When both blocks are present, explicit targets win and conflict=true so the caller can warn.
+func migrateLegacyBrowserConfig(bc *BrowserConfig) (synthesized bool, conflict bool) {
+ if bc == nil {
+ return false, false
+ }
+
+ hasLegacy := strings.TrimSpace(bc.Provider) != "" ||
+ strings.TrimSpace(bc.ChromeBinary) != "" ||
+ strings.TrimSpace(bc.ChromeExtraFlags) != "" ||
+ hasCloakBrowserConfig(bc.Cloak) ||
+ !bc.Proxy.IsZero()
+
+ if len(bc.Targets) > 0 {
+ if hasLegacy {
+ conflict = true
+ }
+ return false, conflict
+ }
+
+ if !hasLegacy {
+ return false, false
+ }
+
+ provider := NormalizeBrowserProvider(bc.Provider)
+ target := BrowserTargetConfig{
+ Provider: provider,
+ Binary: bc.ChromeBinary,
+ ExtraFlags: bc.ChromeExtraFlags,
+ Cloak: cloneCloakBrowserConfig(bc.Cloak),
+ Proxy: cloneBrowserProxyConfig(bc.Proxy),
+ }
+ bc.Targets = BrowserTargetsConfig{DefaultBrowserTargetName: target}
+ if strings.TrimSpace(bc.DefaultTarget) == "" {
+ bc.DefaultTarget = DefaultBrowserTargetName
+ }
+ return true, false
+}
+
+type ResolvedBrowserTarget struct {
+ Name string
+ Provider string
+ Target BrowserTargetConfig
+ Config *RuntimeConfig
+ Legacy bool
+}
+
+func CloneRuntimeConfig(in *RuntimeConfig) *RuntimeConfig {
+ if in == nil {
+ return nil
+ }
+ out := *in
+ out.CookieSecure = cloneBoolPtr(in.CookieSecure)
+ out.AllowedDomains = cloneStringSlice(in.AllowedDomains)
+ out.DownloadAllowedDomains = cloneStringSlice(in.DownloadAllowedDomains)
+ out.TrustedProxyCIDRs = cloneStringSlice(in.TrustedProxyCIDRs)
+ out.TrustedResolveCIDRs = cloneStringSlice(in.TrustedResolveCIDRs)
+ out.ExtensionPaths = cloneStringSlice(in.ExtensionPaths)
+ out.FallbackOrder = cloneStringSlice(in.FallbackOrder)
+ out.AttachAllowHosts = cloneStringSlice(in.AttachAllowHosts)
+ out.AttachAllowSchemes = cloneStringSlice(in.AttachAllowSchemes)
+ out.IDPI.CustomPatterns = cloneStringSlice(in.IDPI.CustomPatterns)
+ out.AutoSolver.Solvers = cloneStringSlice(in.AutoSolver.Solvers)
+ out.Proxy = cloneBrowserProxyConfig(in.Proxy)
+ out.Targets = cloneBrowserTargetsConfig(in.Targets)
+ return &out
+}
+
+func cloneStringSlice(in []string) []string {
+ if len(in) == 0 {
+ return nil
+ }
+ return append([]string(nil), in...)
+}
+
+func cloneBoolPtr(in *bool) *bool {
+ if in == nil {
+ return nil
+ }
+ v := *in
+ return &v
+}
+
+// ResolveDefaultTarget returns the effective default target; empty when no targets are configured.
+func ResolveDefaultTarget(cfg *RuntimeConfig) string {
+ if cfg == nil || len(cfg.Targets) == 0 {
+ return ""
+ }
+ if dt := strings.TrimSpace(cfg.DefaultTarget); dt != "" {
+ if _, ok := cfg.Targets[dt]; ok {
+ return dt
+ }
+ }
+ if len(cfg.Targets) == 1 {
+ for name := range cfg.Targets {
+ return name
+ }
+ }
+ return ""
+}
+
+func ResolveDefaultBrowserTarget(cfg *RuntimeConfig) (*ResolvedBrowserTarget, error) {
+ if cfg == nil || len(cfg.Targets) == 0 {
+ return &ResolvedBrowserTarget{
+ Provider: NormalizeBrowserProvider(runtimeProvider(cfg)),
+ Config: CloneRuntimeConfig(cfg),
+ Legacy: true,
+ }, nil
+ }
+
+ name := ResolveDefaultTarget(cfg)
+ if name == "" {
+ return nil, fmt.Errorf("no default browser target configured and none requested")
+ }
+ return resolveBrowserTargetByName(cfg, name)
+}
+
+func ResolveExplicitBrowserTarget(cfg *RuntimeConfig, requested string) (*ResolvedBrowserTarget, error) {
+ requested = strings.TrimSpace(requested)
+ if requested == "" {
+ return nil, fmt.Errorf("browser target name is required")
+ }
+ if cfg == nil || len(cfg.Targets) == 0 {
+ return nil, fmt.Errorf("no browser targets configured; cannot resolve %q", requested)
+ }
+ if !IsValidBrowserTargetName(requested) {
+ return nil, fmt.Errorf("invalid browser target name %q (must match ^[a-z][a-z0-9-]{0,31}$)", requested)
+ }
+ return resolveBrowserTargetByName(cfg, requested)
+}
+
+func resolveBrowserTargetByName(cfg *RuntimeConfig, name string) (*ResolvedBrowserTarget, error) {
+ t, ok := cfg.Targets[name]
+ if !ok {
+ return nil, fmt.Errorf("browser target %q not found", name)
+ }
+ t = cloneBrowserTarget(t)
+ effective := CloneRuntimeConfig(cfg)
+ applyTargetToRuntime(effective, t)
+ return &ResolvedBrowserTarget{
+ Name: name,
+ Provider: effective.BrowserProvider,
+ Target: t,
+ Config: effective,
+ }, nil
+}
+
+func runtimeProvider(cfg *RuntimeConfig) string {
+ if cfg == nil {
+ return ""
+ }
+ return cfg.BrowserProvider
+}
+
+func applyTargetToRuntime(out *RuntimeConfig, t BrowserTargetConfig) {
+ if out == nil {
+ return
+ }
+ out.BrowserProvider = NormalizeBrowserProvider(t.Provider)
+ if strings.TrimSpace(t.Binary) != "" {
+ out.ChromeBinary = t.Binary
+ }
+ if strings.TrimSpace(t.ExtraFlags) != "" {
+ out.ChromeExtraFlags = t.ExtraFlags
+ }
+ out.Cloak = mergeCloakConfig(out.Cloak, t.Cloak)
+ if !t.Proxy.IsZero() {
+ out.Proxy = cloneBrowserProxyConfig(t.Proxy)
+ }
+}
+
+// ResolveRequestedTarget validates a public target parameter. New call sites
+// should use ResolveDefaultBrowserTarget or ResolveExplicitBrowserTarget so the
+// empty-string semantics are explicit.
+func ResolveRequestedTarget(cfg *RuntimeConfig, requested string) (targetName, provider string, err error) {
+ var resolved *ResolvedBrowserTarget
+ if strings.TrimSpace(requested) == "" {
+ resolved, err = ResolveDefaultBrowserTarget(cfg)
+ } else {
+ resolved, err = ResolveExplicitBrowserTarget(cfg, requested)
+ }
+ if err != nil || resolved == nil {
+ return "", "", err
+ }
+ if resolved.Legacy {
+ return "", "", nil
+ }
+ return resolved.Name, resolved.Provider, nil
+}
+
+// ApplyTargetOverride is a legacy compatibility wrapper for older tests and
+// callers. New code should use ResolveDefaultBrowserTarget or
+// ResolveExplicitBrowserTarget and pass the returned effective Config through
+// the launch path.
+func ApplyTargetOverride(cfg *RuntimeConfig, targetName string) *RuntimeConfig {
+ if cfg == nil {
+ return cfg
+ }
+ targetName = strings.TrimSpace(targetName)
+ if targetName == "" {
+ return cfg
+ }
+ resolved, err := ResolveExplicitBrowserTarget(cfg, targetName)
+ if err != nil {
+ return cfg
+ }
+ return resolved.Config
+}
+
+// mergeCloakConfig deep-merges target over global: target wins on non-zero/non-nil fields.
+func mergeCloakConfig(global CloakBrowserRuntimeConfig, target CloakBrowserConfig) CloakBrowserRuntimeConfig {
+ out := global
+ if target.FingerprintSeed != "" {
+ out.FingerprintSeed = target.FingerprintSeed
+ }
+ if target.Platform != "" {
+ out.Platform = target.Platform
+ }
+ if target.Locale != "" {
+ out.Locale = target.Locale
+ }
+ if target.Timezone != "" {
+ out.Timezone = target.Timezone
+ }
+ if target.WebRTCIP != "" {
+ out.WebRTCIP = target.WebRTCIP
+ }
+ if target.FontsDir != "" {
+ out.FontsDir = target.FontsDir
+ }
+ if target.StorageQuotaMB != nil {
+ out.StorageQuotaMB = *target.StorageQuotaMB
+ }
+ if target.DisableDefaultStealthArgs != nil {
+ out.DisableDefaultStealthArgs = *target.DisableDefaultStealthArgs
+ }
+ return out
+}
diff --git a/internal/config/browser_targets_test.go b/internal/config/browser_targets_test.go
new file mode 100644
index 00000000..67fc4022
--- /dev/null
+++ b/internal/config/browser_targets_test.go
@@ -0,0 +1,1023 @@
+package config
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+)
+
+func TestMigrateLegacyBrowserConfig_LegacyOnlySynthesizesDefaultTarget(t *testing.T) {
+ bc := BrowserConfig{
+ Provider: BrowserProviderChrome,
+ ChromeBinary: "/usr/bin/chrome",
+ }
+ synthesized, conflict := migrateLegacyBrowserConfig(&bc)
+ if !synthesized {
+ t.Fatalf("expected synthesized=true, got false")
+ }
+ if conflict {
+ t.Fatalf("expected conflict=false, got true")
+ }
+ if bc.DefaultTarget != DefaultBrowserTargetName {
+ t.Fatalf("DefaultTarget = %q, want %q", bc.DefaultTarget, DefaultBrowserTargetName)
+ }
+ tgt, ok := bc.Targets[DefaultBrowserTargetName]
+ if !ok {
+ t.Fatalf("targets[%q] missing", DefaultBrowserTargetName)
+ }
+ if tgt.Provider != BrowserProviderChrome {
+ t.Fatalf("target.Provider = %q, want chrome", tgt.Provider)
+ }
+ if tgt.Binary != "/usr/bin/chrome" {
+ t.Fatalf("target.Binary = %q, want /usr/bin/chrome", tgt.Binary)
+ }
+}
+
+func TestMigrateLegacyBrowserConfig_CloakLegacyCopiesCloakSubBlock(t *testing.T) {
+ bc := BrowserConfig{
+ Provider: BrowserProviderCloak,
+ ChromeBinary: "/opt/cloak/chrome",
+ Cloak: CloakBrowserConfig{
+ FingerprintSeed: "42",
+ Platform: "linux",
+ },
+ }
+ synthesized, _ := migrateLegacyBrowserConfig(&bc)
+ if !synthesized {
+ t.Fatalf("expected synthesized=true")
+ }
+ tgt := bc.Targets[DefaultBrowserTargetName]
+ if tgt.Cloak.FingerprintSeed != "42" || tgt.Cloak.Platform != "linux" {
+ t.Fatalf("cloak sub-block not copied; got %+v", tgt.Cloak)
+ }
+}
+
+func TestMigrateLegacyBrowserConfig_DeepClonesLegacyTargetFields(t *testing.T) {
+ quota := 128
+ disableStealth := true
+ bc := BrowserConfig{
+ Provider: BrowserProviderChrome,
+ Cloak: CloakBrowserConfig{
+ StorageQuotaMB: &quota,
+ DisableDefaultStealthArgs: &disableStealth,
+ },
+ Proxy: BrowserProxyConfig{
+ Server: "http://proxy.example:8080",
+ BypassList: []string{"localhost"},
+ Geo: &BrowserProxyGeoConfig{Timezone: "UTC"},
+ },
+ }
+ synthesized, _ := migrateLegacyBrowserConfig(&bc)
+ if !synthesized {
+ t.Fatalf("expected synthesized=true")
+ }
+
+ quota = 256
+ disableStealth = false
+ bc.Proxy.BypassList[0] = "mutated"
+ bc.Proxy.Geo.Timezone = "Europe/London"
+
+ tgt := bc.Targets[DefaultBrowserTargetName]
+ if tgt.Cloak.StorageQuotaMB == nil || *tgt.Cloak.StorageQuotaMB != 128 {
+ t.Fatalf("target quota shared with legacy config: %+v", tgt.Cloak.StorageQuotaMB)
+ }
+ if tgt.Cloak.DisableDefaultStealthArgs == nil || !*tgt.Cloak.DisableDefaultStealthArgs {
+ t.Fatalf("target stealth pointer shared with legacy config: %+v", tgt.Cloak.DisableDefaultStealthArgs)
+ }
+ if got := tgt.Proxy.BypassList[0]; got != "localhost" {
+ t.Fatalf("target proxy bypass shared with legacy config: %q", got)
+ }
+ if got := tgt.Proxy.Geo.Timezone; got != "UTC" {
+ t.Fatalf("target proxy geo shared with legacy config: %q", got)
+ }
+}
+
+func TestMigrateLegacyBrowserConfig_TargetsOnlyLeftIntact(t *testing.T) {
+ bc := BrowserConfig{
+ DefaultTarget: "chrome-local",
+ Targets: BrowserTargetsConfig{
+ "chrome-local": {Provider: BrowserProviderChrome, Binary: "/usr/bin/chrome"},
+ },
+ }
+ synthesized, conflict := migrateLegacyBrowserConfig(&bc)
+ if synthesized {
+ t.Fatalf("expected synthesized=false when targets are already present")
+ }
+ if conflict {
+ t.Fatalf("expected conflict=false when no legacy fields are set")
+ }
+ if bc.DefaultTarget != "chrome-local" {
+ t.Fatalf("DefaultTarget mutated: %q", bc.DefaultTarget)
+ }
+ if len(bc.Targets) != 1 {
+ t.Fatalf("Targets mutated: %+v", bc.Targets)
+ }
+}
+
+func TestMigrateLegacyBrowserConfig_BothPresentExplicitWinsAndFlagsConflict(t *testing.T) {
+ bc := BrowserConfig{
+ Provider: BrowserProviderChrome,
+ ChromeBinary: "/legacy/chrome",
+ DefaultTarget: "explicit",
+ Targets: BrowserTargetsConfig{
+ "explicit": {Provider: BrowserProviderChrome, Binary: "/explicit/chrome"},
+ },
+ }
+ synthesized, conflict := migrateLegacyBrowserConfig(&bc)
+ if synthesized {
+ t.Fatalf("explicit targets must NOT be overwritten (synthesized should be false)")
+ }
+ if !conflict {
+ t.Fatalf("expected conflict=true when both blocks are set")
+ }
+ if _, ok := bc.Targets[DefaultBrowserTargetName]; ok {
+ t.Fatalf("must not synthesize 'default' when explicit targets exist")
+ }
+ if bc.DefaultTarget != "explicit" {
+ t.Fatalf("explicit defaultTarget overwritten: %q", bc.DefaultTarget)
+ }
+ // Legacy fields preserved on the file config for round-trip.
+ if bc.Provider != BrowserProviderChrome || bc.ChromeBinary != "/legacy/chrome" {
+ t.Fatalf("legacy fields lost; got Provider=%q Binary=%q", bc.Provider, bc.ChromeBinary)
+ }
+}
+
+func TestMigrateLegacyBrowserConfig_EmptyConfigNoop(t *testing.T) {
+ bc := BrowserConfig{}
+ synthesized, conflict := migrateLegacyBrowserConfig(&bc)
+ if synthesized || conflict {
+ t.Fatalf("empty browser config should be a no-op; got synth=%v conflict=%v", synthesized, conflict)
+ }
+ if len(bc.Targets) != 0 || bc.DefaultTarget != "" {
+ t.Fatalf("empty config mutated: %+v", bc)
+ }
+}
+
+func TestValidateBrowserTargets_NoTargets_Nil(t *testing.T) {
+ if errs := ValidateBrowserTargets(BrowserConfig{}); errs != nil {
+ t.Fatalf("expected nil errors for empty targets; got %v", errs)
+ }
+}
+
+func TestValidateBrowserTargets_GoodConfig_NoErrors(t *testing.T) {
+ bc := BrowserConfig{
+ DefaultTarget: "chrome-local",
+ FallbackOrder: []string{"cloak-primary"},
+ Targets: BrowserTargetsConfig{
+ "chrome-local": {Provider: BrowserProviderChrome, Binary: "/usr/bin/chrome"},
+ "cloak-primary": {Provider: BrowserProviderCloak, Binary: "/opt/cloak/chrome"},
+ },
+ }
+ if errs := ValidateBrowserTargets(bc); len(errs) != 0 {
+ t.Fatalf("expected no errors; got %v", errs)
+ }
+}
+
+func TestValidateBrowserTargets_RejectsBadTargetName(t *testing.T) {
+ bc := BrowserConfig{
+ DefaultTarget: "Bad_Name",
+ Targets: BrowserTargetsConfig{
+ "Bad_Name": {Provider: BrowserProviderChrome},
+ },
+ }
+ errs := ValidateBrowserTargets(bc)
+ if len(errs) == 0 {
+ t.Fatalf("expected error for bad target name")
+ }
+ found := false
+ for _, e := range errs {
+ if strings.Contains(e.Error(), "invalid target name") {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("missing invalid-name error; got %v", errs)
+ }
+}
+
+func TestValidateBrowserTargets_RejectsUnknownProvider(t *testing.T) {
+ bc := BrowserConfig{
+ DefaultTarget: "ok",
+ Targets: BrowserTargetsConfig{
+ "ok": {Provider: "lightpanda"},
+ },
+ }
+ errs := ValidateBrowserTargets(bc)
+ found := false
+ for _, e := range errs {
+ if strings.Contains(e.Error(), "unknown provider") {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("expected unknown-provider error; got %v", errs)
+ }
+}
+
+func TestValidateBrowserTargets_RejectsMissingProvider(t *testing.T) {
+ bc := BrowserConfig{
+ DefaultTarget: "ok",
+ Targets: BrowserTargetsConfig{
+ "ok": {Binary: "/foo"},
+ },
+ }
+ errs := ValidateBrowserTargets(bc)
+ found := false
+ for _, e := range errs {
+ if strings.Contains(e.Error(), "provider is required") {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("expected required-provider error; got %v", errs)
+ }
+}
+
+func TestValidateBrowserTargets_RejectsCloakTargetWithoutBinary(t *testing.T) {
+ bc := BrowserConfig{
+ DefaultTarget: "cloak",
+ Targets: BrowserTargetsConfig{
+ "cloak": {Provider: BrowserProviderCloak},
+ },
+ }
+ errs := ValidateBrowserTargets(bc)
+ found := false
+ for _, e := range errs {
+ if strings.Contains(e.Error(), "browser.targets.cloak.binary") {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("expected cloak target binary error; got %v", errs)
+ }
+}
+
+func TestValidateBrowserTargets_CloakTargetCanInheritGlobalBinary(t *testing.T) {
+ bc := BrowserConfig{
+ ChromeBinary: "/opt/cloak/chrome",
+ DefaultTarget: "cloak",
+ ChromeExtraFlags: "--global-flag",
+ Targets: BrowserTargetsConfig{
+ "cloak": {Provider: BrowserProviderCloak},
+ },
+ }
+ if errs := ValidateBrowserTargets(bc); len(errs) != 0 {
+ t.Fatalf("expected no errors; got %v", errs)
+ }
+}
+
+func TestValidateBrowserTargets_DanglingFallbackReference(t *testing.T) {
+ bc := BrowserConfig{
+ DefaultTarget: "a",
+ FallbackOrder: []string{"missing"},
+ Targets: BrowserTargetsConfig{
+ "a": {Provider: BrowserProviderChrome},
+ },
+ }
+ errs := ValidateBrowserTargets(bc)
+ found := false
+ for _, e := range errs {
+ if strings.Contains(e.Error(), "fallbackOrder") && strings.Contains(e.Error(), "missing") {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("expected dangling-fallback error; got %v", errs)
+ }
+}
+
+func TestValidateBrowserTargets_RejectsFallbackDuplicateAndDefaultSelfReference(t *testing.T) {
+ bc := BrowserConfig{
+ DefaultTarget: "a",
+ FallbackOrder: []string{"b", "a", "b"},
+ Targets: BrowserTargetsConfig{
+ "a": {Provider: BrowserProviderChrome},
+ "b": {Provider: BrowserProviderChrome},
+ },
+ }
+ errs := ValidateBrowserTargets(bc)
+ var sawSelf, sawDuplicate bool
+ for _, e := range errs {
+ msg := e.Error()
+ if strings.Contains(msg, "must not include defaultTarget") {
+ sawSelf = true
+ }
+ if strings.Contains(msg, "duplicates target") {
+ sawDuplicate = true
+ }
+ }
+ if !sawSelf || !sawDuplicate {
+ t.Fatalf("expected self-reference and duplicate errors; got %v", errs)
+ }
+}
+
+func TestValidateBrowserTargets_RejectsUnsafeTargetExtraFlags(t *testing.T) {
+ bc := BrowserConfig{
+ DefaultTarget: "a",
+ Targets: BrowserTargetsConfig{
+ "a": {Provider: BrowserProviderChrome, ExtraFlags: "--disable-web-security"},
+ },
+ }
+ errs := ValidateBrowserTargets(bc)
+ found := false
+ for _, e := range errs {
+ if strings.Contains(e.Error(), "browser.targets.a.extraFlags") {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("expected target extraFlags validation error; got %v", errs)
+ }
+}
+
+func TestValidateBrowserTargets_ValidatesTargetCloakConfig(t *testing.T) {
+ bc := BrowserConfig{
+ DefaultTarget: "cloak",
+ Targets: BrowserTargetsConfig{
+ "cloak": {
+ Provider: BrowserProviderCloak,
+ Binary: "/opt/cloak/chrome",
+ Cloak: CloakBrowserConfig{Locale: "en-gb"},
+ },
+ },
+ }
+ errs := ValidateBrowserTargets(bc)
+ found := false
+ for _, e := range errs {
+ if strings.Contains(e.Error(), "browser.targets.cloak.cloak") {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("expected target cloak validation error; got %v", errs)
+ }
+}
+
+func TestValidateBrowserTargets_DefaultTargetMissingWithMultipleTargets(t *testing.T) {
+ bc := BrowserConfig{
+ Targets: BrowserTargetsConfig{
+ "a": {Provider: BrowserProviderChrome},
+ "b": {Provider: BrowserProviderChrome},
+ },
+ }
+ errs := ValidateBrowserTargets(bc)
+ found := false
+ for _, e := range errs {
+ if strings.Contains(e.Error(), "browser.defaultTarget") && strings.Contains(e.Error(), "multiple") {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("expected missing-defaultTarget error; got %v", errs)
+ }
+}
+
+func TestValidateBrowserTargets_DefaultTargetReferencingUnknown(t *testing.T) {
+ bc := BrowserConfig{
+ DefaultTarget: "ghost",
+ Targets: BrowserTargetsConfig{
+ "a": {Provider: BrowserProviderChrome},
+ },
+ }
+ errs := ValidateBrowserTargets(bc)
+ found := false
+ for _, e := range errs {
+ if strings.Contains(e.Error(), "browser.defaultTarget") && strings.Contains(e.Error(), "ghost") {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("expected unknown defaultTarget error; got %v", errs)
+ }
+}
+
+func TestValidateBrowserTargets_SingleTargetNoDefaultIsAllowed(t *testing.T) {
+ bc := BrowserConfig{
+ Targets: BrowserTargetsConfig{
+ "only": {Provider: BrowserProviderChrome},
+ },
+ }
+ if errs := ValidateBrowserTargets(bc); len(errs) != 0 {
+ t.Fatalf("single target without defaultTarget should validate; got %v", errs)
+ }
+}
+
+func TestResolveDefaultTarget_ReturnsExplicit(t *testing.T) {
+ cfg := &RuntimeConfig{
+ DefaultTarget: "primary",
+ Targets: BrowserTargetsConfig{
+ "primary": {Provider: BrowserProviderChrome},
+ "backup": {Provider: BrowserProviderChrome},
+ },
+ }
+ if got := ResolveDefaultTarget(cfg); got != "primary" {
+ t.Fatalf("ResolveDefaultTarget = %q, want primary", got)
+ }
+}
+
+func TestResolveDefaultTarget_SingleTargetAutoPicks(t *testing.T) {
+ cfg := &RuntimeConfig{
+ Targets: BrowserTargetsConfig{
+ "only": {Provider: BrowserProviderChrome},
+ },
+ }
+ if got := ResolveDefaultTarget(cfg); got != "only" {
+ t.Fatalf("ResolveDefaultTarget = %q, want only", got)
+ }
+}
+
+func TestResolveDefaultTarget_NoTargetsReturnsEmpty(t *testing.T) {
+ cfg := &RuntimeConfig{}
+ if got := ResolveDefaultTarget(cfg); got != "" {
+ t.Fatalf("ResolveDefaultTarget = %q, want empty", got)
+ }
+}
+
+func TestResolveDefaultBrowserTarget_LegacyNoTargetsReturnsFreshConfig(t *testing.T) {
+ cookieSecure := true
+ cfg := &RuntimeConfig{
+ BrowserProvider: BrowserProviderCloak,
+ CookieSecure: &cookieSecure,
+ AllowedDomains: []string{"example.com"},
+ }
+ resolved, err := ResolveDefaultBrowserTarget(cfg)
+ if err != nil {
+ t.Fatalf("unexpected err: %v", err)
+ }
+ if resolved == nil || !resolved.Legacy {
+ t.Fatalf("resolved legacy = %+v, want legacy result", resolved)
+ }
+ if resolved.Name != "" || resolved.Provider != BrowserProviderCloak {
+ t.Fatalf("resolved = %+v, want unnamed cloak legacy target", resolved)
+ }
+ if resolved.Config == nil || resolved.Config == cfg {
+ t.Fatalf("resolved.Config should be a fresh clone, got %+v", resolved.Config)
+ }
+
+ resolved.Config.AllowedDomains[0] = "mutated.example"
+ *resolved.Config.CookieSecure = false
+ if cfg.AllowedDomains[0] != "example.com" {
+ t.Fatalf("legacy resolved config shared AllowedDomains with input: %+v", cfg.AllowedDomains)
+ }
+ if cfg.CookieSecure == nil || !*cfg.CookieSecure {
+ t.Fatalf("legacy resolved config shared CookieSecure pointer with input: %+v", cfg.CookieSecure)
+ }
+}
+
+func TestResolveDefaultBrowserTarget_SingleTargetPromotesEffectiveConfig(t *testing.T) {
+ cfg := &RuntimeConfig{
+ BrowserProvider: BrowserProviderChrome,
+ ChromeBinary: "/global/chrome",
+ ChromeExtraFlags: "--global-flag",
+ Targets: BrowserTargetsConfig{
+ "only": {
+ Provider: BrowserProviderCloak,
+ Binary: "/opt/cloak/chrome",
+ ExtraFlags: "--target-flag",
+ Cloak: CloakBrowserConfig{Timezone: "UTC"},
+ },
+ },
+ }
+ resolved, err := ResolveDefaultBrowserTarget(cfg)
+ if err != nil {
+ t.Fatalf("unexpected err: %v", err)
+ }
+ if resolved.Name != "only" || resolved.Provider != BrowserProviderCloak || resolved.Legacy {
+ t.Fatalf("resolved = %+v, want non-legacy cloak target named only", resolved)
+ }
+ if resolved.Config == cfg {
+ t.Fatalf("resolved.Config should not reuse input pointer")
+ }
+ if resolved.Config.BrowserProvider != BrowserProviderCloak {
+ t.Fatalf("effective provider = %q, want cloak", resolved.Config.BrowserProvider)
+ }
+ if resolved.Config.ChromeBinary != "/opt/cloak/chrome" {
+ t.Fatalf("effective binary = %q, want /opt/cloak/chrome", resolved.Config.ChromeBinary)
+ }
+ if resolved.Config.ChromeExtraFlags != "--target-flag" {
+ t.Fatalf("effective extraFlags = %q, want --target-flag", resolved.Config.ChromeExtraFlags)
+ }
+ if resolved.Config.Cloak.Timezone != "UTC" {
+ t.Fatalf("effective cloak timezone = %q, want UTC", resolved.Config.Cloak.Timezone)
+ }
+ if cfg.BrowserProvider != BrowserProviderChrome || cfg.ChromeBinary != "/global/chrome" {
+ t.Fatalf("input cfg was mutated: %+v", cfg)
+ }
+}
+
+func TestResolveExplicitBrowserTarget_RejectsEmptyName(t *testing.T) {
+ cfg := &RuntimeConfig{
+ Targets: BrowserTargetsConfig{
+ "only": {Provider: BrowserProviderChrome},
+ },
+ }
+ if _, err := ResolveExplicitBrowserTarget(cfg, " "); err == nil {
+ t.Fatal("expected error for empty explicit browser target")
+ }
+}
+
+func TestResolveExplicitBrowserTarget_ConfigDoesNotAliasOriginal(t *testing.T) {
+ cookieSecure := true
+ cfg := &RuntimeConfig{
+ BrowserProvider: BrowserProviderChrome,
+ CookieSecure: &cookieSecure,
+ AllowedDomains: []string{"allowed.example"},
+ DownloadAllowedDomains: []string{"download.example"},
+ TrustedProxyCIDRs: []string{"10.0.0.0/24"},
+ TrustedResolveCIDRs: []string{"192.168.0.0/24"},
+ ExtensionPaths: []string{"/ext/global"},
+ FallbackOrder: []string{"backup"},
+ AttachAllowHosts: []string{"localhost"},
+ AttachAllowSchemes: []string{"ws"},
+ IDPI: IDPIConfig{CustomPatterns: []string{"ignore-me"}},
+ AutoSolver: AutoSolverConfig{Solvers: []string{"semantic"}},
+ Proxy: BrowserProxyConfig{Server: "http://global.example:8080", BypassList: []string{"global"}, Geo: &BrowserProxyGeoConfig{Timezone: "UTC"}},
+ Cloak: CloakBrowserRuntimeConfig{FingerprintSeed: "global"},
+ DefaultTarget: "proxy",
+ Targets: BrowserTargetsConfig{
+ "proxy": {
+ Provider: BrowserProviderChrome,
+ Proxy: BrowserProxyConfig{
+ Server: "http://proxy.example:8080",
+ BypassList: []string{"target"},
+ Geo: &BrowserProxyGeoConfig{Timezone: "UTC"},
+ },
+ Cloak: CloakBrowserConfig{
+ FingerprintSeed: "target",
+ StorageQuotaMB: intPtr(256),
+ },
+ },
+ "backup": {Provider: BrowserProviderChrome},
+ },
+ }
+
+ resolved, err := ResolveExplicitBrowserTarget(cfg, "proxy")
+ if err != nil {
+ t.Fatalf("unexpected err: %v", err)
+ }
+ got := resolved.Config
+ if got == cfg {
+ t.Fatal("resolved config reused input pointer")
+ }
+ if got.Targets == nil || len(got.Targets) != len(cfg.Targets) {
+ t.Fatalf("resolved targets = %+v, want cloned targets map", got.Targets)
+ }
+
+ *got.CookieSecure = false
+ got.AllowedDomains[0] = "mutated"
+ got.DownloadAllowedDomains[0] = "mutated"
+ got.TrustedProxyCIDRs[0] = "mutated"
+ got.TrustedResolveCIDRs[0] = "mutated"
+ got.ExtensionPaths[0] = "mutated"
+ got.FallbackOrder[0] = "mutated"
+ got.AttachAllowHosts[0] = "mutated"
+ got.AttachAllowSchemes[0] = "mutated"
+ got.IDPI.CustomPatterns[0] = "mutated"
+ got.AutoSolver.Solvers[0] = "mutated"
+ got.Proxy.BypassList[0] = "mutated"
+ got.Proxy.Geo.Timezone = "Europe/London"
+ resolved.Target.Proxy.BypassList[0] = "mutated-resolved-target"
+ resolved.Target.Proxy.Geo.Timezone = "America/New_York"
+ target := got.Targets["proxy"]
+ target.Proxy.BypassList[0] = "mutated-target-map"
+ target.Proxy.Geo.Timezone = "Asia/Tokyo"
+ target.Cloak.StorageQuotaMB = intPtr(512)
+ got.Targets["proxy"] = target
+
+ if cfg.CookieSecure == nil || !*cfg.CookieSecure {
+ t.Fatalf("CookieSecure pointer shared with resolved config")
+ }
+ if cfg.AllowedDomains[0] != "allowed.example" ||
+ cfg.DownloadAllowedDomains[0] != "download.example" ||
+ cfg.TrustedProxyCIDRs[0] != "10.0.0.0/24" ||
+ cfg.TrustedResolveCIDRs[0] != "192.168.0.0/24" ||
+ cfg.ExtensionPaths[0] != "/ext/global" ||
+ cfg.FallbackOrder[0] != "backup" ||
+ cfg.AttachAllowHosts[0] != "localhost" ||
+ cfg.AttachAllowSchemes[0] != "ws" ||
+ cfg.IDPI.CustomPatterns[0] != "ignore-me" ||
+ cfg.AutoSolver.Solvers[0] != "semantic" {
+ t.Fatalf("resolved config shared a top-level slice with input: %+v", cfg)
+ }
+ if cfg.Proxy.BypassList[0] != "global" || cfg.Proxy.Geo.Timezone != "UTC" {
+ t.Fatalf("global proxy shared with resolved config: %+v", cfg.Proxy)
+ }
+ originalTarget := cfg.Targets["proxy"]
+ if originalTarget.Proxy.BypassList[0] != "target" || originalTarget.Proxy.Geo.Timezone != "UTC" {
+ t.Fatalf("target proxy shared with resolved config: %+v", originalTarget.Proxy)
+ }
+ if originalTarget.Cloak.StorageQuotaMB == nil || *originalTarget.Cloak.StorageQuotaMB != 256 {
+ t.Fatalf("target cloak pointer shared with resolved config: %+v", originalTarget.Cloak.StorageQuotaMB)
+ }
+}
+
+func TestResolveRequestedTarget_LegacyEmptyRequested(t *testing.T) {
+ cfg := &RuntimeConfig{}
+ name, provider, err := ResolveRequestedTarget(cfg, "")
+ if err != nil {
+ t.Fatalf("unexpected err: %v", err)
+ }
+ if name != "" || provider != "" {
+ t.Fatalf("got (%q, %q), want empty/empty", name, provider)
+ }
+}
+
+func TestResolveRequestedTarget_LegacyWithRequestedErrors(t *testing.T) {
+ cfg := &RuntimeConfig{}
+ _, _, err := ResolveRequestedTarget(cfg, "chrome")
+ if err == nil {
+ t.Fatal("expected error when requesting target with no targets configured")
+ }
+ if !strings.Contains(err.Error(), "no browser targets configured") {
+ t.Fatalf("err = %v, want 'no browser targets configured'", err)
+ }
+}
+
+func TestResolveRequestedTarget_TargetsEmptyRequestedReturnsDefault(t *testing.T) {
+ cfg := &RuntimeConfig{
+ DefaultTarget: "primary",
+ Targets: BrowserTargetsConfig{
+ "primary": {Provider: BrowserProviderChrome},
+ "backup": {Provider: BrowserProviderCloak},
+ },
+ }
+ name, provider, err := ResolveRequestedTarget(cfg, "")
+ if err != nil {
+ t.Fatalf("unexpected err: %v", err)
+ }
+ if name != "primary" || provider != BrowserProviderChrome {
+ t.Fatalf("got (%q, %q), want (primary, chrome)", name, provider)
+ }
+}
+
+func TestResolveRequestedTarget_TargetsMultiNoDefaultErrors(t *testing.T) {
+ cfg := &RuntimeConfig{
+ Targets: BrowserTargetsConfig{
+ "a": {Provider: BrowserProviderChrome},
+ "b": {Provider: BrowserProviderChrome},
+ },
+ }
+ _, _, err := ResolveRequestedTarget(cfg, "")
+ if err == nil {
+ t.Fatal("expected error when no default and multiple targets")
+ }
+ if !strings.Contains(err.Error(), "no default browser target") {
+ t.Fatalf("err = %v, want 'no default browser target'", err)
+ }
+}
+
+func TestResolveRequestedTarget_ValidRequestedReturnsProvider(t *testing.T) {
+ cfg := &RuntimeConfig{
+ DefaultTarget: "primary",
+ Targets: BrowserTargetsConfig{
+ "primary": {Provider: BrowserProviderChrome},
+ "cloak-1": {Provider: BrowserProviderCloak},
+ },
+ }
+ name, provider, err := ResolveRequestedTarget(cfg, "cloak-1")
+ if err != nil {
+ t.Fatalf("unexpected err: %v", err)
+ }
+ if name != "cloak-1" || provider != BrowserProviderCloak {
+ t.Fatalf("got (%q, %q), want (cloak-1, cloak)", name, provider)
+ }
+}
+
+func TestResolveRequestedTarget_UnknownRequestedErrors(t *testing.T) {
+ cfg := &RuntimeConfig{
+ DefaultTarget: "primary",
+ Targets: BrowserTargetsConfig{
+ "primary": {Provider: BrowserProviderChrome},
+ },
+ }
+ _, _, err := ResolveRequestedTarget(cfg, "ghost")
+ if err == nil {
+ t.Fatal("expected error for unknown requested target")
+ }
+ if !strings.Contains(err.Error(), "not found") {
+ t.Fatalf("err = %v, want 'not found'", err)
+ }
+}
+
+func TestResolveRequestedTarget_InvalidNameErrors(t *testing.T) {
+ cfg := &RuntimeConfig{
+ DefaultTarget: "primary",
+ Targets: BrowserTargetsConfig{
+ "primary": {Provider: BrowserProviderChrome},
+ },
+ }
+ _, _, err := ResolveRequestedTarget(cfg, "Bad_Name")
+ if err == nil {
+ t.Fatal("expected error for invalid target name")
+ }
+ if !strings.Contains(err.Error(), "invalid browser target name") {
+ t.Fatalf("err = %v, want 'invalid browser target name'", err)
+ }
+}
+
+func TestIsValidBrowserTargetName(t *testing.T) {
+ cases := []struct {
+ name string
+ ok bool
+ }{
+ {"chrome", true},
+ {"chrome-local", true},
+ {"a", true},
+ {"a1", true},
+ {"a-b-c-1", true},
+ {"", false},
+ {"Chrome", false},
+ {"1chrome", false},
+ {"-chrome", false},
+ {"chrome_local", false},
+ {"chrome.local", false},
+ {strings.Repeat("a", 33), false},
+ {strings.Repeat("a", 32), true},
+ }
+ for _, tc := range cases {
+ if got := IsValidBrowserTargetName(tc.name); got != tc.ok {
+ t.Errorf("IsValidBrowserTargetName(%q) = %v, want %v", tc.name, got, tc.ok)
+ }
+ }
+}
+
+func TestFileConfig_TargetsRoundTrip(t *testing.T) {
+ fc := FileConfig{
+ Browser: BrowserConfig{
+ Provider: BrowserProviderChrome,
+ ChromeBinary: "/usr/bin/chrome",
+ DefaultTarget: "chrome-local",
+ FallbackOrder: []string{"chrome-local"},
+ Targets: BrowserTargetsConfig{
+ "chrome-local": {Provider: BrowserProviderChrome, Binary: "/usr/bin/chrome"},
+ },
+ },
+ }
+ data, err := json.Marshal(fc)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ if !strings.Contains(string(data), `"targets"`) {
+ t.Fatalf("marshal output missing targets block:\n%s", data)
+ }
+ if !strings.Contains(string(data), `"defaultTarget":"chrome-local"`) {
+ t.Fatalf("marshal output missing defaultTarget:\n%s", data)
+ }
+ var back FileConfig
+ if err := json.Unmarshal(data, &back); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if back.Browser.DefaultTarget != "chrome-local" {
+ t.Fatalf("DefaultTarget lost: %q", back.Browser.DefaultTarget)
+ }
+ if _, ok := back.Browser.Targets["chrome-local"]; !ok {
+ t.Fatalf("Targets[chrome-local] lost; got %+v", back.Browser.Targets)
+ }
+ // Legacy fields preserved.
+ if back.Browser.Provider != BrowserProviderChrome || back.Browser.ChromeBinary != "/usr/bin/chrome" {
+ t.Fatalf("legacy fields lost: %+v", back.Browser)
+ }
+}
+
+func TestFileConfig_LegacyOnlyMarshalOmitsNewKeys(t *testing.T) {
+ fc := FileConfig{
+ Browser: BrowserConfig{
+ Provider: BrowserProviderChrome,
+ ChromeBinary: "/usr/bin/chrome",
+ },
+ }
+ data, err := json.Marshal(fc)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ s := string(data)
+ for _, k := range []string{`"targets"`, `"defaultTarget"`, `"fallbackOrder"`} {
+ if strings.Contains(s, k) {
+ t.Errorf("legacy-only config emitted %s in JSON:\n%s", k, s)
+ }
+ }
+}
+
+func baseRuntimeForOverride() *RuntimeConfig {
+ return &RuntimeConfig{
+ BrowserProvider: BrowserProviderChrome,
+ ChromeBinary: "/global/chrome",
+ ChromeExtraFlags: "--global-flag",
+ Cloak: CloakBrowserRuntimeConfig{
+ FingerprintSeed: "global-seed",
+ Platform: "linux",
+ Locale: "en-US",
+ StorageQuotaMB: 100,
+ },
+ }
+}
+
+func TestApplyTargetOverride_EmptyTargetName_ReturnsUnchanged(t *testing.T) {
+ cfg := baseRuntimeForOverride()
+ got := ApplyTargetOverride(cfg, "")
+ if got != cfg {
+ t.Fatalf("expected same pointer back for empty target name")
+ }
+}
+
+func TestApplyTargetOverride_UnknownTarget_ReturnsUnchanged(t *testing.T) {
+ cfg := baseRuntimeForOverride()
+ cfg.Targets = BrowserTargetsConfig{
+ "chrome": BrowserTargetConfig{Provider: BrowserProviderChrome},
+ }
+ got := ApplyTargetOverride(cfg, "missing")
+ if got != cfg {
+ t.Fatalf("expected same pointer back for unknown target")
+ }
+}
+
+func TestApplyTargetOverride_NilCfg_ReturnsNil(t *testing.T) {
+ if got := ApplyTargetOverride(nil, "anything"); got != nil {
+ t.Fatalf("expected nil for nil cfg")
+ }
+}
+
+func TestApplyTargetOverride_OverridesProviderBinaryFlags(t *testing.T) {
+ cfg := baseRuntimeForOverride()
+ cfg.Targets = BrowserTargetsConfig{
+ "cloak-eu": BrowserTargetConfig{
+ Provider: BrowserProviderCloak,
+ Binary: "/opt/cloak/cloakbrowser",
+ ExtraFlags: "--target-flag",
+ },
+ }
+ got := ApplyTargetOverride(cfg, "cloak-eu")
+ if got == cfg {
+ t.Fatalf("expected a new pointer, got input pointer back")
+ }
+ if got.BrowserProvider != BrowserProviderCloak {
+ t.Errorf("provider = %q, want %q", got.BrowserProvider, BrowserProviderCloak)
+ }
+ if got.ChromeBinary != "/opt/cloak/cloakbrowser" {
+ t.Errorf("binary = %q, want /opt/cloak/cloakbrowser", got.ChromeBinary)
+ }
+ if got.ChromeExtraFlags != "--target-flag" {
+ t.Errorf("extraFlags = %q, want --target-flag", got.ChromeExtraFlags)
+ }
+ // Input MUST be untouched.
+ if cfg.BrowserProvider != BrowserProviderChrome ||
+ cfg.ChromeBinary != "/global/chrome" ||
+ cfg.ChromeExtraFlags != "--global-flag" {
+ t.Errorf("input cfg was mutated: %+v", cfg)
+ }
+}
+
+func TestApplyTargetOverride_EmptyBinary_KeepsGlobalBinary(t *testing.T) {
+ cfg := baseRuntimeForOverride()
+ cfg.Targets = BrowserTargetsConfig{
+ "cloak": BrowserTargetConfig{
+ Provider: BrowserProviderCloak,
+ // no Binary, no ExtraFlags
+ },
+ }
+ got := ApplyTargetOverride(cfg, "cloak")
+ if got.ChromeBinary != "/global/chrome" {
+ t.Errorf("binary = %q, want global /global/chrome (inherit)", got.ChromeBinary)
+ }
+ if got.ChromeExtraFlags != "--global-flag" {
+ t.Errorf("extraFlags = %q, want global --global-flag (inherit)", got.ChromeExtraFlags)
+ }
+ if got.BrowserProvider != BrowserProviderCloak {
+ t.Errorf("provider = %q, want cloak", got.BrowserProvider)
+ }
+}
+
+func TestApplyTargetOverride_CloakDeepMerge_PartialTarget(t *testing.T) {
+ cfg := baseRuntimeForOverride()
+ cfg.Targets = BrowserTargetsConfig{
+ "cloak": BrowserTargetConfig{
+ Provider: BrowserProviderCloak,
+ Cloak: CloakBrowserConfig{
+ // Override seed + timezone; leave others zero.
+ FingerprintSeed: "target-seed",
+ Timezone: "Europe/London",
+ },
+ },
+ }
+ got := ApplyTargetOverride(cfg, "cloak")
+ if got.Cloak.FingerprintSeed != "target-seed" {
+ t.Errorf("FingerprintSeed = %q, want target-seed", got.Cloak.FingerprintSeed)
+ }
+ if got.Cloak.Timezone != "Europe/London" {
+ t.Errorf("Timezone = %q, want Europe/London", got.Cloak.Timezone)
+ }
+ // Preserved from global.
+ if got.Cloak.Platform != "linux" {
+ t.Errorf("Platform = %q, want preserved linux", got.Cloak.Platform)
+ }
+ if got.Cloak.Locale != "en-US" {
+ t.Errorf("Locale = %q, want preserved en-US", got.Cloak.Locale)
+ }
+ if got.Cloak.StorageQuotaMB != 100 {
+ t.Errorf("StorageQuotaMB = %d, want preserved 100", got.Cloak.StorageQuotaMB)
+ }
+ // Input still untouched.
+ if cfg.Cloak.FingerprintSeed != "global-seed" || cfg.Cloak.Timezone != "" {
+ t.Errorf("input cloak mutated: %+v", cfg.Cloak)
+ }
+}
+
+func TestApplyTargetOverride_CloakEmpty_PreservesGlobalCloak(t *testing.T) {
+ cfg := baseRuntimeForOverride()
+ cfg.Targets = BrowserTargetsConfig{
+ "cloak": BrowserTargetConfig{
+ Provider: BrowserProviderCloak,
+ // Cloak left zero.
+ },
+ }
+ got := ApplyTargetOverride(cfg, "cloak")
+ if got.Cloak != cfg.Cloak {
+ t.Errorf("expected cloak unchanged from global; got %+v want %+v", got.Cloak, cfg.Cloak)
+ }
+}
+
+func TestApplyTargetOverride_CloakUnion_NonOverlappingFields(t *testing.T) {
+ cfg := baseRuntimeForOverride()
+ cfg.Cloak = CloakBrowserRuntimeConfig{FingerprintSeed: "g"}
+ cfg.Targets = BrowserTargetsConfig{
+ "cloak": BrowserTargetConfig{
+ Provider: BrowserProviderCloak,
+ Cloak: CloakBrowserConfig{Platform: "windows"},
+ },
+ }
+ got := ApplyTargetOverride(cfg, "cloak")
+ if got.Cloak.FingerprintSeed != "g" {
+ t.Errorf("FingerprintSeed = %q, want g", got.Cloak.FingerprintSeed)
+ }
+ if got.Cloak.Platform != "windows" {
+ t.Errorf("Platform = %q, want windows", got.Cloak.Platform)
+ }
+}
+
+func TestApplyTargetOverride_CloakOverlap_TargetWins(t *testing.T) {
+ cfg := baseRuntimeForOverride()
+ cfg.Cloak = CloakBrowserRuntimeConfig{
+ FingerprintSeed: "global-seed",
+ StorageQuotaMB: 100,
+ DisableDefaultStealthArgs: false,
+ }
+ cfg.Targets = BrowserTargetsConfig{
+ "cloak": BrowserTargetConfig{
+ Provider: BrowserProviderCloak,
+ Cloak: CloakBrowserConfig{
+ FingerprintSeed: "target-seed",
+ StorageQuotaMB: intPtr(2048),
+ DisableDefaultStealthArgs: boolPtr(true),
+ },
+ },
+ }
+ got := ApplyTargetOverride(cfg, "cloak")
+ if got.Cloak.FingerprintSeed != "target-seed" {
+ t.Errorf("FingerprintSeed = %q, want target-seed", got.Cloak.FingerprintSeed)
+ }
+ if got.Cloak.StorageQuotaMB != 2048 {
+ t.Errorf("StorageQuotaMB = %d, want 2048", got.Cloak.StorageQuotaMB)
+ }
+ if !got.Cloak.DisableDefaultStealthArgs {
+ t.Errorf("DisableDefaultStealthArgs = false, want true")
+ }
+ // Input cloak still intact.
+ if cfg.Cloak.FingerprintSeed != "global-seed" || cfg.Cloak.StorageQuotaMB != 100 ||
+ cfg.Cloak.DisableDefaultStealthArgs {
+ t.Errorf("input cloak mutated: %+v", cfg.Cloak)
+ }
+}
+
+func TestApplyTargetOverride_ClonesTargetProxyAndTargetsMap(t *testing.T) {
+ cfg := baseRuntimeForOverride()
+ cfg.Proxy = BrowserProxyConfig{
+ Server: "http://global.example:8080",
+ BypassList: []string{"global"},
+ }
+ cfg.Targets = BrowserTargetsConfig{
+ "proxy": {
+ Provider: BrowserProviderChrome,
+ Proxy: BrowserProxyConfig{
+ Server: "http://proxy.example:8080",
+ BypassList: []string{"localhost"},
+ Geo: &BrowserProxyGeoConfig{Timezone: "UTC"},
+ },
+ },
+ }
+
+ got := ApplyTargetOverride(cfg, "proxy")
+ got.Proxy.BypassList[0] = "mutated"
+ got.Proxy.Geo.Timezone = "Europe/London"
+ got.Targets["proxy"] = BrowserTargetConfig{Provider: BrowserProviderCloak}
+
+ original := cfg.Targets["proxy"]
+ if original.Proxy.BypassList[0] != "localhost" {
+ t.Fatalf("target proxy bypass mutated through override: %+v", original.Proxy.BypassList)
+ }
+ if original.Proxy.Geo.Timezone != "UTC" {
+ t.Fatalf("target proxy geo mutated through override: %+v", original.Proxy.Geo)
+ }
+ if original.Provider != BrowserProviderChrome {
+ t.Fatalf("target map shared with override: %+v", original)
+ }
+}
diff --git a/internal/config/capabilities.go b/internal/config/capabilities.go
new file mode 100644
index 00000000..344c82f7
--- /dev/null
+++ b/internal/config/capabilities.go
@@ -0,0 +1,74 @@
+package config
+
+import "strings"
+
+// BrowserCapability is a well-known capability name that a provider may advertise. Advisory only.
+type BrowserCapability string
+
+const (
+ CapCDP BrowserCapability = "cdp"
+ CapHeadless BrowserCapability = "headless"
+ CapPDF BrowserCapability = "pdf"
+ CapExtensions BrowserCapability = "extensions"
+ CapNativeStealth BrowserCapability = "nativeStealth"
+ CapDownloads BrowserCapability = "downloads"
+ CapNetworkInterception BrowserCapability = "networkInterception"
+)
+
+// providerCapabilities is declared in stable order so JSON serialization is deterministic.
+var providerCapabilities = map[string][]BrowserCapability{
+ BrowserProviderChrome: {
+ CapCDP,
+ CapHeadless,
+ CapPDF,
+ CapExtensions,
+ CapDownloads,
+ CapNetworkInterception,
+ },
+ BrowserProviderCloak: {
+ CapCDP,
+ CapHeadless,
+ CapPDF,
+ CapExtensions,
+ CapDownloads,
+ CapNetworkInterception,
+ CapNativeStealth,
+ },
+}
+
+// lookupProviderCapabilities returns ok=false for unknown providers so callers can distinguish "no
+// caps declared" from NormalizeBrowserProvider's default-to-chrome fallback.
+func lookupProviderCapabilities(provider string) ([]BrowserCapability, bool) {
+ trimmed := strings.ToLower(strings.TrimSpace(provider))
+ if _, known := providerCapabilities[trimmed]; !known {
+ return nil, false
+ }
+ normalized := NormalizeBrowserProvider(provider)
+ src, ok := providerCapabilities[normalized]
+ return src, ok
+}
+
+// ProviderCapabilities returns a defensive copy; unknown providers yield an empty slice.
+func ProviderCapabilities(provider string) []BrowserCapability {
+ src, ok := lookupProviderCapabilities(provider)
+ if !ok {
+ return nil
+ }
+ out := make([]BrowserCapability, len(src))
+ copy(out, src)
+ return out
+}
+
+// HasCapability reports whether provider declares c; unknown providers return false.
+func HasCapability(provider string, c BrowserCapability) bool {
+ src, ok := lookupProviderCapabilities(provider)
+ if !ok {
+ return false
+ }
+ for _, cap := range src {
+ if cap == c {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/config/capabilities_test.go b/internal/config/capabilities_test.go
new file mode 100644
index 00000000..92f8a455
--- /dev/null
+++ b/internal/config/capabilities_test.go
@@ -0,0 +1,99 @@
+package config
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestProviderCapabilities_Chrome(t *testing.T) {
+ got := ProviderCapabilities(BrowserProviderChrome)
+ want := []BrowserCapability{
+ CapCDP,
+ CapHeadless,
+ CapPDF,
+ CapExtensions,
+ CapDownloads,
+ CapNetworkInterception,
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("chrome capabilities = %v, want %v", got, want)
+ }
+}
+
+func TestProviderCapabilities_Cloak(t *testing.T) {
+ got := ProviderCapabilities(BrowserProviderCloak)
+ want := []BrowserCapability{
+ CapCDP,
+ CapHeadless,
+ CapPDF,
+ CapExtensions,
+ CapDownloads,
+ CapNetworkInterception,
+ CapNativeStealth,
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("cloak capabilities = %v, want %v", got, want)
+ }
+
+ // Guards against accidental divergence: cloak must be chrome + nativeStealth.
+ chrome := ProviderCapabilities(BrowserProviderChrome)
+ for _, c := range chrome {
+ if !HasCapability(BrowserProviderCloak, c) {
+ t.Fatalf("cloak missing chrome capability %q", c)
+ }
+ }
+ if !HasCapability(BrowserProviderCloak, CapNativeStealth) {
+ t.Fatalf("cloak missing nativeStealth capability")
+ }
+ if HasCapability(BrowserProviderChrome, CapNativeStealth) {
+ t.Fatalf("chrome unexpectedly declares nativeStealth")
+ }
+}
+
+func TestProviderCapabilities_UnknownProvider_Empty(t *testing.T) {
+ for _, name := range []string{"lightpanda", "firefox", "", " ", "unknown"} {
+ got := ProviderCapabilities(name)
+ if len(got) != 0 {
+ t.Fatalf("provider %q: expected empty slice, got %v", name, got)
+ }
+ }
+}
+
+func TestHasCapability_KnownCap_True(t *testing.T) {
+ if !HasCapability(BrowserProviderChrome, CapCDP) {
+ t.Fatalf("chrome should declare cdp")
+ }
+ if !HasCapability(BrowserProviderCloak, CapNativeStealth) {
+ t.Fatalf("cloak should declare nativeStealth")
+ }
+ if !HasCapability(" Chrome ", CapHeadless) {
+ t.Fatalf("mixed-case chrome should declare headless")
+ }
+}
+
+func TestHasCapability_KnownProvider_UnknownCap_False(t *testing.T) {
+ if HasCapability(BrowserProviderChrome, CapNativeStealth) {
+ t.Fatalf("chrome should not declare nativeStealth")
+ }
+ if HasCapability(BrowserProviderChrome, BrowserCapability("nonexistent")) {
+ t.Fatalf("chrome should not declare a fabricated capability")
+ }
+ if HasCapability("lightpanda", CapCDP) {
+ t.Fatalf("unknown provider should report no capabilities")
+ }
+}
+
+func TestProviderCapabilities_ReturnsCopy(t *testing.T) {
+ first := ProviderCapabilities(BrowserProviderChrome)
+ if len(first) == 0 {
+ t.Fatalf("expected non-empty chrome capabilities")
+ }
+ first[0] = BrowserCapability("mutated")
+ second := ProviderCapabilities(BrowserProviderChrome)
+ if second[0] != CapCDP {
+ t.Fatalf("mutation leaked into table: second[0] = %q", second[0])
+ }
+ if reflect.DeepEqual(first, second) {
+ t.Fatalf("mutated slice should differ from a fresh lookup")
+ }
+}
diff --git a/internal/config/config_file.go b/internal/config/config_file.go
index 89c111b9..6d5d77c3 100644
--- a/internal/config/config_file.go
+++ b/internal/config/config_file.go
@@ -135,6 +135,7 @@ func DefaultFileConfig() FileConfig {
maxRedirects := -1
trustLoopbackProxy := false
attachEnabled := false
+ attachForwardProxyAuth := false
activityEnabled := true
activitySessionIdleSec := 1800
activityRetentionDays := 30
@@ -200,9 +201,10 @@ func DefaultFileConfig() FileConfig {
MaxRedirects: &maxRedirects,
TrustLoopbackProxy: &trustLoopbackProxy,
Attach: AttachConfig{
- Enabled: &attachEnabled,
- AllowHosts: []string{"127.0.0.1", "localhost", "::1"},
- AllowSchemes: []string{"ws", "wss"},
+ Enabled: &attachEnabled,
+ AllowHosts: []string{"127.0.0.1", "localhost", "::1"},
+ AllowSchemes: []string{"ws", "wss", "http", "https"},
+ ForwardProxyAuth: &attachForwardProxyAuth,
},
IDPI: IDPIConfig{
Enabled: true,
diff --git a/internal/config/config_file_json.go b/internal/config/config_file_json.go
index 857e7457..f720fcb0 100644
--- a/internal/config/config_file_json.go
+++ b/internal/config/config_file_json.go
@@ -37,6 +37,11 @@ type browserConfigJSON struct {
ChromeExtraFlags string `json:"extraFlags"`
Cloak *cloakBrowserConfigJSON `json:"cloak,omitempty"`
ExtensionPaths []string `json:"extensionPaths"`
+ // Pointer so omitempty drops the field for legacy configs (byte-identical round-trip).
+ Proxy *BrowserProxyConfig `json:"proxy,omitempty"`
+ DefaultTarget string `json:"defaultTarget,omitempty"`
+ FallbackOrder []string `json:"fallbackOrder,omitempty"`
+ Targets BrowserTargetsConfig `json:"targets,omitempty"`
}
type cloakBrowserConfigJSON struct {
@@ -100,9 +105,10 @@ type securityConfigJSON struct {
}
type attachJSON struct {
- Enabled *bool `json:"enabled"`
- AllowHosts []string `json:"allowHosts"`
- AllowSchemes []string `json:"allowSchemes"`
+ Enabled *bool `json:"enabled"`
+ AllowHosts []string `json:"allowHosts"`
+ AllowSchemes []string `json:"allowSchemes"`
+ ForwardProxyAuth *bool `json:"forwardProxyAuth"`
}
type idpiConfigJSON struct {
diff --git a/internal/config/config_file_marshal.go b/internal/config/config_file_marshal.go
index f1fb2f02..2a45137c 100644
--- a/internal/config/config_file_marshal.go
+++ b/internal/config/config_file_marshal.go
@@ -47,16 +47,6 @@ func cloakBrowserConfigJSONFromFile(provider string, c CloakBrowserConfig) *cloa
if !hasCloakBrowserConfig(c) {
return nil
}
- if !IsCloakBrowserProvider(provider) &&
- c.FingerprintSeed == "" &&
- c.Platform == "" &&
- c.Locale == "" &&
- c.Timezone == "" &&
- c.WebRTCIP == "" &&
- c.FontsDir == "" &&
- c.StorageQuotaMB == nil {
- return nil
- }
return &cloakBrowserConfigJSON{
FingerprintSeed: c.FingerprintSeed,
Platform: c.Platform,
@@ -69,6 +59,26 @@ func cloakBrowserConfigJSONFromFile(provider string, c CloakBrowserConfig) *cloa
}
}
+// browserProxyJSONFromFile returns nil when proxy is disabled so omitempty drops the field.
+func browserProxyJSONFromFile(p BrowserProxyConfig) *BrowserProxyConfig {
+ if p.IsZero() {
+ return nil
+ }
+ out := BrowserProxyConfig{
+ Server: p.Server,
+ Username: p.Username,
+ Password: p.Password,
+ }
+ if len(p.BypassList) > 0 {
+ out.BypassList = append([]string(nil), p.BypassList...)
+ }
+ if p.Geo != nil && !p.Geo.IsZero() {
+ geoCopy := *p.Geo
+ out.Geo = &geoCopy
+ }
+ return &out
+}
+
func cloakBrowserConfigFromRuntime(cfg *RuntimeConfig) CloakBrowserConfig {
if cfg == nil {
return CloakBrowserConfig{}
@@ -81,7 +91,8 @@ func cloakBrowserConfigFromRuntime(cfg *RuntimeConfig) CloakBrowserConfig {
c.Timezone != "" ||
c.WebRTCIP != "" ||
c.FontsDir != "" ||
- c.StorageQuotaMB > 0
+ c.StorageQuotaMB > 0 ||
+ !c.DisableDefaultStealthArgs
out := CloakBrowserConfig{
FingerprintSeed: c.FingerprintSeed,
Platform: c.Platform,
@@ -90,7 +101,7 @@ func cloakBrowserConfigFromRuntime(cfg *RuntimeConfig) CloakBrowserConfig {
WebRTCIP: c.WebRTCIP,
FontsDir: c.FontsDir,
}
- if c.StorageQuotaMB > 0 {
+ if c.StorageQuotaMB > 0 || IsCloakBrowserProvider(cfg.BrowserProvider) {
out.StorageQuotaMB = intPtrIfNonNegative(c.StorageQuotaMB)
}
if hasRuntimeCloak {
@@ -152,6 +163,10 @@ func (fc FileConfig) MarshalJSON() ([]byte, error) {
ChromeExtraFlags: fc.Browser.ChromeExtraFlags,
Cloak: cloakBrowserConfigJSONFromFile(fc.Browser.Provider, fc.Browser.Cloak),
ExtensionPaths: copyStringSlice(fc.Browser.ExtensionPaths),
+ Proxy: browserProxyJSONFromFile(fc.Browser.Proxy),
+ DefaultTarget: fc.Browser.DefaultTarget,
+ FallbackOrder: fc.Browser.FallbackOrder,
+ Targets: fc.Browser.Targets,
},
InstanceDefaults: instanceDefaultsConfigJSON{
Mode: fc.InstanceDefaults.Mode,
@@ -193,9 +208,10 @@ func (fc FileConfig) MarshalJSON() ([]byte, error) {
TrustedResolveCIDRs: copyStringSlice(fc.Security.TrustedResolveCIDRs),
TrustLoopbackProxy: fc.Security.TrustLoopbackProxy,
Attach: attachJSON{
- Enabled: fc.Security.Attach.Enabled,
- AllowHosts: copyStringSlice(fc.Security.Attach.AllowHosts),
- AllowSchemes: copyStringSlice(fc.Security.Attach.AllowSchemes),
+ Enabled: fc.Security.Attach.Enabled,
+ AllowHosts: copyStringSlice(fc.Security.Attach.AllowHosts),
+ AllowSchemes: copyStringSlice(fc.Security.Attach.AllowSchemes),
+ ForwardProxyAuth: fc.Security.Attach.ForwardProxyAuth,
},
IDPI: idpiConfigJSON{
Enabled: fc.Security.IDPI.Enabled,
@@ -347,6 +363,7 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
maxRedirects := cfg.MaxRedirects
trustLoopbackProxy := cfg.TrustLoopbackProxy
attachEnabled := cfg.AttachEnabled
+ attachForwardProxyAuth := cfg.AttachForwardProxyAuth
start := cfg.InstancePortStart
end := cfg.InstancePortEnd
restartMaxRestarts := cfg.RestartMaxRestarts
@@ -414,6 +431,10 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
ChromeExtraFlags: cfg.ChromeExtraFlags,
Cloak: cloakBrowserConfigFromRuntime(cfg),
ExtensionPaths: append([]string(nil), cfg.ExtensionPaths...),
+ Proxy: cloneBrowserProxyConfig(cfg.Proxy),
+ DefaultTarget: cfg.DefaultTarget,
+ FallbackOrder: append([]string(nil), cfg.FallbackOrder...),
+ Targets: cloneBrowserTargetsConfig(cfg.Targets),
},
InstanceDefaults: InstanceDefaultsConfig{
Mode: mode,
@@ -454,9 +475,10 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
TrustedResolveCIDRs: append([]string(nil), cfg.TrustedResolveCIDRs...),
TrustLoopbackProxy: &trustLoopbackProxy,
Attach: AttachConfig{
- Enabled: &attachEnabled,
- AllowHosts: append([]string(nil), cfg.AttachAllowHosts...),
- AllowSchemes: append([]string(nil), cfg.AttachAllowSchemes...),
+ Enabled: &attachEnabled,
+ AllowHosts: append([]string(nil), cfg.AttachAllowHosts...),
+ AllowSchemes: append([]string(nil), cfg.AttachAllowSchemes...),
+ ForwardProxyAuth: &attachForwardProxyAuth,
},
IDPI: cfg.IDPI,
},
diff --git a/internal/config/config_file_test.go b/internal/config/config_file_test.go
index 1298988e..2f595480 100644
--- a/internal/config/config_file_test.go
+++ b/internal/config/config_file_test.go
@@ -30,12 +30,16 @@ func TestDefaultFileConfig(t *testing.T) {
if fc.MultiInstance.Strategy != "always-on" {
t.Errorf("DefaultFileConfig.MultiInstance.Strategy = %v, want always-on", fc.MultiInstance.Strategy)
}
- if len(fc.Security.Attach.AllowSchemes) != 2 || fc.Security.Attach.AllowSchemes[0] != "ws" || fc.Security.Attach.AllowSchemes[1] != "wss" {
- t.Errorf("DefaultFileConfig.Security.Attach.AllowSchemes = %v, want [ws wss]", fc.Security.Attach.AllowSchemes)
+ wantSchemes := []string{"ws", "wss", "http", "https"}
+ if strings.Join(fc.Security.Attach.AllowSchemes, ",") != strings.Join(wantSchemes, ",") {
+ t.Errorf("DefaultFileConfig.Security.Attach.AllowSchemes = %v, want %v", fc.Security.Attach.AllowSchemes, wantSchemes)
}
if fc.Security.Attach.Enabled == nil || *fc.Security.Attach.Enabled {
t.Errorf("DefaultFileConfig.Security.Attach.Enabled = %v, want explicit false", formatBoolPtr(fc.Security.Attach.Enabled))
}
+ if fc.Security.Attach.ForwardProxyAuth == nil || *fc.Security.Attach.ForwardProxyAuth {
+ t.Errorf("DefaultFileConfig.Security.Attach.ForwardProxyAuth = %v, want explicit false", formatBoolPtr(fc.Security.Attach.ForwardProxyAuth))
+ }
wantExtensionsDir := defaultExtensionsDir(userConfigDir())
if len(fc.Browser.ExtensionPaths) != 1 || fc.Browser.ExtensionPaths[0] != wantExtensionsDir {
t.Errorf("DefaultFileConfig.Browser.ExtensionPaths = %v, want [%q]", fc.Browser.ExtensionPaths, wantExtensionsDir)
@@ -197,6 +201,65 @@ func TestConfigSchemaURLUsesClosestOlderOrEqualPublishedSchema(t *testing.T) {
}
}
+func TestFileConfigFromRuntime_PreservesBrowserTargets(t *testing.T) {
+ quota := 256
+ disableStealth := true
+ cfg := &RuntimeConfig{
+ BrowserProvider: BrowserProviderChrome,
+ DefaultTarget: "chrome-local",
+ FallbackOrder: []string{"cloak-primary"},
+ Targets: BrowserTargetsConfig{
+ "chrome-local": {
+ Provider: BrowserProviderChrome,
+ Binary: "/usr/bin/chrome",
+ ExtraFlags: "--ash-no-nudges",
+ Proxy: BrowserProxyConfig{
+ Server: "http://proxy.example:8080",
+ BypassList: []string{"localhost"},
+ Geo: &BrowserProxyGeoConfig{Timezone: "UTC"},
+ },
+ },
+ "cloak-primary": {
+ Provider: BrowserProviderCloak,
+ Binary: "/opt/cloak/chrome",
+ Cloak: CloakBrowserConfig{
+ StorageQuotaMB: &quota,
+ DisableDefaultStealthArgs: &disableStealth,
+ },
+ },
+ },
+ }
+
+ fc := FileConfigFromRuntime(cfg)
+ if fc.Browser.DefaultTarget != "chrome-local" {
+ t.Fatalf("DefaultTarget = %q, want chrome-local", fc.Browser.DefaultTarget)
+ }
+ if got := strings.Join(fc.Browser.FallbackOrder, ","); got != "cloak-primary" {
+ t.Fatalf("FallbackOrder = %q, want cloak-primary", got)
+ }
+ if len(fc.Browser.Targets) != 2 {
+ t.Fatalf("Targets len = %d, want 2", len(fc.Browser.Targets))
+ }
+ if fc.Browser.Targets["chrome-local"].Proxy.BypassList[0] != "localhost" {
+ t.Fatalf("proxy bypass not preserved: %+v", fc.Browser.Targets["chrome-local"].Proxy)
+ }
+ if fc.Browser.Targets["cloak-primary"].Cloak.StorageQuotaMB == nil ||
+ *fc.Browser.Targets["cloak-primary"].Cloak.StorageQuotaMB != 256 {
+ t.Fatalf("cloak target quota not preserved: %+v", fc.Browser.Targets["cloak-primary"].Cloak)
+ }
+
+ fc.Browser.FallbackOrder[0] = "mutated"
+ target := fc.Browser.Targets["chrome-local"]
+ target.Proxy.BypassList[0] = "mutated"
+ fc.Browser.Targets["chrome-local"] = target
+ if cfg.FallbackOrder[0] != "cloak-primary" {
+ t.Fatalf("runtime fallbackOrder shared with file config: %+v", cfg.FallbackOrder)
+ }
+ if cfg.Targets["chrome-local"].Proxy.BypassList[0] != "localhost" {
+ t.Fatalf("runtime target proxy shared with file config: %+v", cfg.Targets["chrome-local"].Proxy)
+ }
+}
+
// TestIsLegacyConfig tests the format detection logic.
func TestIsLegacyConfig(t *testing.T) {
tests := []struct {
@@ -380,6 +443,9 @@ func TestDefaultFileConfigJSON(t *testing.T) {
if parsed.Security.Attach.Enabled == nil || *parsed.Security.Attach.Enabled {
t.Errorf("round-trip Security.Attach.Enabled = %v, want explicit false", formatBoolPtr(parsed.Security.Attach.Enabled))
}
+ if parsed.Security.Attach.ForwardProxyAuth == nil || *parsed.Security.Attach.ForwardProxyAuth {
+ t.Errorf("round-trip Security.Attach.ForwardProxyAuth = %v, want explicit false", formatBoolPtr(parsed.Security.Attach.ForwardProxyAuth))
+ }
if parsed.Observability.Activity.StateDir != "" {
t.Errorf("round-trip Observability.Activity.StateDir = %q, want empty string", parsed.Observability.Activity.StateDir)
}
@@ -518,6 +584,35 @@ func TestFileConfigJSONEmitsCloakBrowserConfig(t *testing.T) {
}
}
+func TestFileConfigJSONEmitsExplicitCloakFalseOnChromeProvider(t *testing.T) {
+ disableDefaultStealthArgs := false
+ fc := DefaultFileConfig()
+ fc.Browser.Provider = BrowserProviderChrome
+ fc.Browser.Cloak = CloakBrowserConfig{DisableDefaultStealthArgs: &disableDefaultStealthArgs}
+
+ data, err := json.Marshal(fc)
+ if err != nil {
+ t.Fatalf("json.Marshal(FileConfig) error = %v", err)
+ }
+ if !strings.Contains(string(data), `"disableDefaultStealthArgs":false`) {
+ t.Fatalf("explicit false cloak setting not preserved in JSON: %s", data)
+ }
+}
+
+func TestFileConfigFromRuntimeEmitsCloakStorageQuotaZeroForCloakProvider(t *testing.T) {
+ fc := FileConfigFromRuntime(&RuntimeConfig{
+ BrowserProvider: BrowserProviderCloak,
+ ChromeBinary: "/opt/cloakbrowser/chrome",
+ Cloak: CloakBrowserRuntimeConfig{
+ StorageQuotaMB: 0,
+ DisableDefaultStealthArgs: true,
+ },
+ })
+ if fc.Browser.Cloak.StorageQuotaMB == nil || *fc.Browser.Cloak.StorageQuotaMB != 0 {
+ t.Fatalf("StorageQuotaMB = %v, want explicit 0", fc.Browser.Cloak.StorageQuotaMB)
+ }
+}
+
func boolPtr(b bool) *bool {
return &b
}
diff --git a/internal/config/config_load.go b/internal/config/config_load.go
index 1dd7f6db..03879571 100644
--- a/internal/config/config_load.go
+++ b/internal/config/config_load.go
@@ -113,7 +113,7 @@ func Load() *RuntimeConfig {
// Attach defaults
AttachEnabled: false,
AttachAllowHosts: []string{"127.0.0.1", "localhost", "::1"},
- AttachAllowSchemes: []string{"ws", "wss"},
+ AttachAllowSchemes: []string{"ws", "wss", "http", "https"},
// IDPI defaults
IDPI: IDPIConfig{
@@ -228,6 +228,45 @@ func Load() *RuntimeConfig {
return cfg
}
+// ConfigFileStatus reports on-disk config state without invoking Load (used by `pinchtab doctor`).
+type ConfigFileStatus struct {
+ Path string
+ DefaultPath string
+ EnvOverride bool
+ Found bool
+ ParseErr error
+}
+
+// InspectConfigFile reports config-file load status with no side effects.
+func InspectConfigFile() ConfigFileStatus {
+ defaultPath := filepath.Join(userConfigDir(), "config.json")
+ path := envOr("PINCHTAB_CONFIG", defaultPath)
+ status := ConfigFileStatus{
+ Path: path,
+ DefaultPath: defaultPath,
+ EnvOverride: os.Getenv("PINCHTAB_CONFIG") != "",
+ }
+
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return status
+ }
+ status.Found = true
+
+ if isLegacyConfig(data) {
+ var lc legacyFileConfig
+ if err := json.Unmarshal(data, &lc); err != nil {
+ status.ParseErr = err
+ }
+ return status
+ }
+ var fc FileConfig
+ if err := json.Unmarshal(data, &fc); err != nil {
+ status.ParseErr = err
+ }
+ return status
+}
+
func envOr(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
@@ -333,6 +372,9 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
if fc.Security.Attach.Enabled != nil {
cfg.AttachEnabled = *fc.Security.Attach.Enabled
}
+ if fc.Security.Attach.ForwardProxyAuth != nil {
+ cfg.AttachForwardProxyAuth = *fc.Security.Attach.ForwardProxyAuth
+ }
cfg.AttachAllowHosts = append([]string(nil), fc.Security.Attach.AllowHosts...)
cfg.AttachAllowSchemes = append([]string(nil), fc.Security.Attach.AllowSchemes...)
cfg.TrustedProxyCIDRs = append([]string(nil), fc.Security.TrustedProxyCIDRs...)
@@ -406,7 +448,18 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
cfg.Sessions.Agent.MaxLifetime = time.Duration(*fc.Sessions.Agent.MaxLifetimeSec) * time.Second
}
- // Browser
+ // Migration shim must run before consuming legacy provider/binary/cloak fields below.
+ if synthesized, conflict := migrateLegacyBrowserConfig(&fc.Browser); conflict {
+ slog.Warn("config has both browser.targets and legacy browser.provider/binary/cloak set; explicit targets win, legacy fields ignored for target resolution")
+ } else if synthesized {
+ slog.Debug("migrated legacy browser config into browser.targets.default")
+ }
+ if len(fc.Browser.Targets) > 0 {
+ cfg.Targets = cloneBrowserTargetsConfig(fc.Browser.Targets)
+ cfg.DefaultTarget = fc.Browser.DefaultTarget
+ cfg.FallbackOrder = append([]string(nil), fc.Browser.FallbackOrder...)
+ }
+
if fc.Browser.Provider != "" {
cfg.BrowserProvider = NormalizeBrowserProvider(fc.Browser.Provider)
if IsCloakBrowserProvider(cfg.BrowserProvider) && fc.Browser.Cloak.DisableDefaultStealthArgs == nil {
@@ -426,6 +479,18 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
cfg.ChromeExtraFlags = SanitizeChromeExtraFlags(fc.Browser.ChromeExtraFlags)
}
applyCloakBrowserConfigToRuntime(cfg, fc.Browser.Cloak)
+ if !fc.Browser.Proxy.IsZero() {
+ cfg.Proxy = BrowserProxyConfig{
+ Server: fc.Browser.Proxy.Server,
+ BypassList: append([]string(nil), fc.Browser.Proxy.BypassList...),
+ Username: fc.Browser.Proxy.Username,
+ Password: fc.Browser.Proxy.Password,
+ }
+ if fc.Browser.Proxy.Geo != nil {
+ geoCopy := *fc.Browser.Proxy.Geo
+ cfg.Proxy.Geo = &geoCopy
+ }
+ }
if fc.Browser.ExtensionPaths != nil {
cfg.ExtensionPaths = append([]string(nil), fc.Browser.ExtensionPaths...)
}
@@ -540,6 +605,9 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
if fc.Security.Attach.Enabled != nil {
cfg.AttachEnabled = *fc.Security.Attach.Enabled
}
+ if fc.Security.Attach.ForwardProxyAuth != nil {
+ cfg.AttachForwardProxyAuth = *fc.Security.Attach.ForwardProxyAuth
+ }
if len(fc.Security.Attach.AllowHosts) > 0 {
cfg.AttachAllowHosts = append([]string(nil), fc.Security.Attach.AllowHosts...)
}
@@ -672,7 +740,7 @@ func applyCloakBrowserConfigToRuntime(cfg *RuntimeConfig, cloak CloakBrowserConf
cfg.Cloak.WebRTCIP = cloak.WebRTCIP
}
if cloak.FontsDir != "" {
- cfg.Cloak.FontsDir = cloak.FontsDir
+ cfg.Cloak.FontsDir = filepath.Clean(cloak.FontsDir)
}
if cloak.StorageQuotaMB != nil {
cfg.Cloak.StorageQuotaMB = *cloak.StorageQuotaMB
diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.go
index 9d9defb6..76898188 100644
--- a/internal/config/config_load_test.go
+++ b/internal/config/config_load_test.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"os"
"path/filepath"
+ "strings"
"testing"
"time"
)
@@ -93,8 +94,12 @@ func TestLoadConfigDefaults(t *testing.T) {
if cfg.AttachEnabled {
t.Errorf("default AttachEnabled = %v, want false", cfg.AttachEnabled)
}
- if len(cfg.AttachAllowSchemes) != 2 || cfg.AttachAllowSchemes[0] != "ws" || cfg.AttachAllowSchemes[1] != "wss" {
- t.Errorf("default AttachAllowSchemes = %v, want [ws wss]", cfg.AttachAllowSchemes)
+ if cfg.AttachForwardProxyAuth {
+ t.Errorf("default AttachForwardProxyAuth = %v, want false", cfg.AttachForwardProxyAuth)
+ }
+ wantAttachSchemes := []string{"ws", "wss", "http", "https"}
+ if strings.Join(cfg.AttachAllowSchemes, ",") != strings.Join(wantAttachSchemes, ",") {
+ t.Errorf("default AttachAllowSchemes = %v, want %v", cfg.AttachAllowSchemes, wantAttachSchemes)
}
if !cfg.IDPI.Enabled {
t.Errorf("default IDPI.Enabled = %v, want true", cfg.IDPI.Enabled)
@@ -425,6 +430,9 @@ func TestApplyFileConfigToRuntimeResetsSecurityFlagsToSafeDefaults(t *testing.T)
if cfg.AttachEnabled {
t.Errorf("ApplyFileConfigToRuntime AttachEnabled = %v, want false", cfg.AttachEnabled)
}
+ if cfg.AttachForwardProxyAuth {
+ t.Errorf("ApplyFileConfigToRuntime AttachForwardProxyAuth = %v, want false", cfg.AttachForwardProxyAuth)
+ }
if !cfg.IDPI.Enabled {
t.Errorf("ApplyFileConfigToRuntime IDPI.Enabled = %v, want true", cfg.IDPI.Enabled)
}
@@ -536,9 +544,10 @@ func TestApplyFileConfigToRuntime_CopiesAttachConfig(t *testing.T) {
fc := &FileConfig{
Security: SecurityConfig{
Attach: AttachConfig{
- Enabled: &enabled,
- AllowHosts: []string{"127.0.0.1", "pinchtab-bridge"},
- AllowSchemes: []string{"http", "https"},
+ Enabled: &enabled,
+ AllowHosts: []string{"127.0.0.1", "pinchtab-bridge"},
+ AllowSchemes: []string{"http", "https"},
+ ForwardProxyAuth: &enabled,
},
},
}
@@ -556,6 +565,9 @@ func TestApplyFileConfigToRuntime_CopiesAttachConfig(t *testing.T) {
if len(cfg.AttachAllowSchemes) != 2 || cfg.AttachAllowSchemes[0] != "http" {
t.Fatalf("ApplyFileConfigToRuntime AttachAllowSchemes = %v, want copied schemes", cfg.AttachAllowSchemes)
}
+ if !cfg.AttachForwardProxyAuth {
+ t.Fatalf("ApplyFileConfigToRuntime AttachForwardProxyAuth = %v, want true", cfg.AttachForwardProxyAuth)
+ }
}
func TestRuntimeConfig_EffectiveTransferLimitsFallbackAndClamp(t *testing.T) {
diff --git a/internal/config/config_types.go b/internal/config/config_types.go
index 95481afd..6f66a0c6 100644
--- a/internal/config/config_types.go
+++ b/internal/config/config_types.go
@@ -73,6 +73,10 @@ type RuntimeConfig struct {
// external Chrome — pinchtab only owns the CDP connection.
CDPAttachURL string
Cloak CloakBrowserRuntimeConfig
+ Proxy BrowserProxyConfig
+ Targets BrowserTargetsConfig
+ DefaultTarget string
+ FallbackOrder []string
ExtensionPaths []string
UserAgent string
NoAnimations bool
@@ -98,9 +102,14 @@ type RuntimeConfig struct {
RestartStableAfter time.Duration // Stable runtime window that resets the restart counter (0 = strategy default)
// Attach settings
- AttachEnabled bool
- AttachAllowHosts []string
- AttachAllowSchemes []string
+ AttachEnabled bool
+ AttachAllowHosts []string
+ AttachAllowSchemes []string
+ AttachForwardProxyAuth bool
+
+ // RemoteCDPURL: when set, bridge attaches to an external browser via CDP instead of launching Chrome. Not persisted.
+ RemoteCDPURL string
+ RemoteBrowserName string
// IDPI (Indirect Prompt Injection defense) settings
IDPI IDPIConfig
@@ -302,6 +311,25 @@ type BrowserConfig struct {
ChromeExtraFlags string `json:"extraFlags,omitempty"`
Cloak CloakBrowserConfig `json:"cloak,omitempty"`
ExtensionPaths []string `json:"extensionPaths,omitempty"`
+
+ Proxy BrowserProxyConfig `json:"proxy,omitempty"`
+
+ DefaultTarget string `json:"defaultTarget,omitempty"`
+ FallbackOrder []string `json:"fallbackOrder,omitempty"`
+ Targets BrowserTargetsConfig `json:"targets,omitempty"`
+}
+
+// BrowserTargetsConfig maps target name -> target config. Names must match `^[a-z][a-z0-9-]{0,31}$`.
+type BrowserTargetsConfig map[string]BrowserTargetConfig
+
+// BrowserTargetConfig is a single named browser target. See docs/architecture/browser-targets.md.
+type BrowserTargetConfig struct {
+ Provider string `json:"provider,omitempty"`
+ Binary string `json:"binary,omitempty"`
+ ExtraFlags string `json:"extraFlags,omitempty"`
+ Cloak CloakBrowserConfig `json:"cloak,omitempty"`
+ // Proxy, when Server is non-empty, replaces the global BrowserConfig.Proxy entirely (no merge).
+ Proxy BrowserProxyConfig `json:"proxy,omitempty"`
}
type CloakBrowserConfig struct {
@@ -403,9 +431,10 @@ type MultiInstanceRestartConfig struct {
}
type AttachConfig struct {
- Enabled *bool `json:"enabled,omitempty"`
- AllowHosts []string `json:"allowHosts,omitempty"`
- AllowSchemes []string `json:"allowSchemes,omitempty"`
+ Enabled *bool `json:"enabled,omitempty"`
+ AllowHosts []string `json:"allowHosts,omitempty"`
+ AllowSchemes []string `json:"allowSchemes,omitempty"`
+ ForwardProxyAuth *bool `json:"forwardProxyAuth,omitempty"`
}
type TimeoutsConfig struct {
diff --git a/internal/config/editor_get.go b/internal/config/editor_get.go
index c2a8d5e1..a40beb6c 100644
--- a/internal/config/editor_get.go
+++ b/internal/config/editor_get.go
@@ -332,6 +332,8 @@ func getAttachField(a *AttachConfig, field string) (string, error) {
return strings.Join(a.AllowHosts, ","), nil
case "allowSchemes":
return strings.Join(a.AllowSchemes, ","), nil
+ case "forwardProxyAuth":
+ return formatBoolPtr(a.ForwardProxyAuth), nil
default:
return "", fmt.Errorf("unknown field security.attach.%s", field)
}
diff --git a/internal/config/editor_get_test.go b/internal/config/editor_get_test.go
index b1e7a208..651504f9 100644
--- a/internal/config/editor_get_test.go
+++ b/internal/config/editor_get_test.go
@@ -145,8 +145,10 @@ func TestGetConfigValue_NilPointerReturnsEmpty(t *testing.T) {
func TestGetConfigValue_AttachSlices(t *testing.T) {
fc := &FileConfig{}
+ forwardProxyAuth := true
fc.Security.Attach.AllowHosts = []string{"127.0.0.1", "localhost"}
fc.Security.Attach.AllowSchemes = []string{"ws", "wss"}
+ fc.Security.Attach.ForwardProxyAuth = &forwardProxyAuth
hosts, err := GetConfigValue(fc, "security.attach.allowHosts")
if err != nil {
@@ -163,6 +165,14 @@ func TestGetConfigValue_AttachSlices(t *testing.T) {
if schemes != "ws,wss" {
t.Errorf("allowSchemes = %q, want %q", schemes, "ws,wss")
}
+
+ forward, err := GetConfigValue(fc, "security.attach.forwardProxyAuth")
+ if err != nil {
+ t.Fatalf("GetConfigValue(security.attach.forwardProxyAuth) error = %v", err)
+ }
+ if forward != "true" {
+ t.Errorf("forwardProxyAuth = %q, want %q", forward, "true")
+ }
}
func TestGetConfigValue_UnknownPaths(t *testing.T) {
diff --git a/internal/config/editor_set.go b/internal/config/editor_set.go
index 32f0682d..933b64db 100644
--- a/internal/config/editor_set.go
+++ b/internal/config/editor_set.go
@@ -525,6 +525,12 @@ func setAttachField(a *AttachConfig, field, value string) error {
a.AllowHosts = parseCSVList(value)
case "allowSchemes":
a.AllowSchemes = parseCSVList(value)
+ case "forwardProxyAuth":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("security.attach.forwardProxyAuth: %w", err)
+ }
+ a.ForwardProxyAuth = &b
default:
return fmt.Errorf("unknown field security.attach.%s", field)
}
diff --git a/internal/config/editor_set_test.go b/internal/config/editor_set_test.go
index 1be502d3..7cd5fe26 100644
--- a/internal/config/editor_set_test.go
+++ b/internal/config/editor_set_test.go
@@ -195,7 +195,11 @@ func TestSetConfigValue_AttachFields(t *testing.T) {
{"security.attach.allowSchemes", "ws,wss", func(fc *FileConfig) bool {
return len(fc.Security.Attach.AllowSchemes) == 2 && fc.Security.Attach.AllowSchemes[0] == "ws"
}, false},
+ {"security.attach.forwardProxyAuth", "true", func(fc *FileConfig) bool {
+ return fc.Security.Attach.ForwardProxyAuth != nil && *fc.Security.Attach.ForwardProxyAuth
+ }, false},
{"security.attach.enabled", "maybe", nil, true},
+ {"security.attach.forwardProxyAuth", "maybe", nil, true},
{"security.attach.unknown", "value", nil, true},
}
diff --git a/internal/config/geo/http_provider_todo.go b/internal/config/geo/http_provider_todo.go
new file mode 100644
index 00000000..b9c9ab3c
--- /dev/null
+++ b/internal/config/geo/http_provider_todo.go
@@ -0,0 +1,36 @@
+package geo
+
+// TODO(P4b-future): HTTP-backed GeoProvider.
+//
+// P4b ships only Noop and Static. A future phase will add an
+// `HTTPGeoProvider` that resolves the proxy egress IP against an external
+// service (ipinfo.io, Maxmind GeoLite2, ip-api, etc.) so users can wire
+// "automatic" geo alignment without supplying browser.proxy.geo.* by hand.
+//
+// Contract (proposed):
+//
+// type HTTPGeoProvider struct {
+// Endpoint string // e.g. "https://ipinfo.io/{ip}/json"
+// Token string // optional bearer/api key, redacted in logs
+// Client *http.Client // injected for testability; nil → http.DefaultClient with a short timeout
+// Cache GeoCache // in-memory TTL cache keyed by IP
+// }
+//
+// func (h HTTPGeoProvider) Lookup(ctx context.Context, ip string) (Info, error) {
+// // 1. ip == "" → return Info{}, nil (best-effort, never fail)
+// // 2. cache hit → return cached Info, nil
+// // 3. ctx-aware GET to Endpoint, parse provider-specific JSON, map to
+// // Info, cache, return.
+// // 4. on any HTTP/parse error → return Info{}, nil and log at Warn.
+// // Geo alignment is a hint, not a hard requirement; a bad lookup
+// // must not block launch.
+// }
+//
+// Open questions deferred until then:
+// - Configuration surface (browser.proxy.geo.http.{endpoint,token,ttl}?).
+// - Whether to support multiple providers with failover.
+// - Cache eviction policy and TTL default.
+// - How to surface lookup status in /stealth/status or the dashboard.
+//
+// Until those are settled, this file intentionally contains no executable
+// code so we don't ship a half-wired network path.
diff --git a/internal/config/geo/provider.go b/internal/config/geo/provider.go
new file mode 100644
index 00000000..95683edb
--- /dev/null
+++ b/internal/config/geo/provider.go
@@ -0,0 +1,68 @@
+// Package geo maps a proxy IP to geographic alignment data (timezone, locale, WebRTC IP, country)
+// used to align browser fingerprint surfaces with the proxy's apparent location.
+package geo
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "regexp"
+ "strings"
+ "time"
+)
+
+// Provider is best-effort: implementations MUST handle empty IP by returning zero Info, nil.
+type Provider interface {
+ Lookup(ctx context.Context, ip string) (Info, error)
+}
+
+// Info carries fingerprint-alignment fields; zero-value fields mean "no opinion".
+type Info struct {
+ Timezone string
+ Locale string
+ WebRTCIP string
+ CountryISO string
+}
+
+func (i Info) IsZero() bool {
+ return i == Info{}
+}
+
+type Noop struct{}
+
+func (Noop) Lookup(context.Context, string) (Info, error) { return Info{}, nil }
+
+// Static returns the configured Info for every call; driven by browser.proxy.geo.*.
+type Static struct {
+ Info Info
+}
+
+func (s Static) Lookup(context.Context, string) (Info, error) { return s.Info, nil }
+
+var localeRegex = regexp.MustCompile(`^[a-z]{2,3}(-[A-Z]{2})?$`)
+var countryRegex = regexp.MustCompile(`^[A-Z]{2}$`)
+
+// Validate skips zero-value fields so partial geo blocks are accepted.
+func Validate(info Info) error {
+ if tz := strings.TrimSpace(info.Timezone); tz != "" {
+ if _, err := time.LoadLocation(tz); err != nil {
+ return fmt.Errorf("timezone %q is not a valid IANA zone: %w", tz, err)
+ }
+ }
+ if loc := strings.TrimSpace(info.Locale); loc != "" {
+ if !localeRegex.MatchString(loc) {
+ return fmt.Errorf("locale %q must match BCP-47 form like \"en\" or \"en-GB\"", loc)
+ }
+ }
+ if ip := strings.TrimSpace(info.WebRTCIP); ip != "" {
+ if net.ParseIP(ip) == nil {
+ return fmt.Errorf("webrtcIP %q is not a valid IP address", ip)
+ }
+ }
+ if cc := strings.TrimSpace(info.CountryISO); cc != "" {
+ if !countryRegex.MatchString(cc) {
+ return fmt.Errorf("countryISO %q must be a 2-letter ISO 3166-1 alpha-2 code", cc)
+ }
+ }
+ return nil
+}
diff --git a/internal/config/geo/provider_test.go b/internal/config/geo/provider_test.go
new file mode 100644
index 00000000..ebc68dc5
--- /dev/null
+++ b/internal/config/geo/provider_test.go
@@ -0,0 +1,95 @@
+package geo
+
+import (
+ "context"
+ "strings"
+ "testing"
+)
+
+func TestNoop_ReturnsZeroInfo(t *testing.T) {
+ got, err := Noop{}.Lookup(context.Background(), "1.2.3.4")
+ if err != nil {
+ t.Fatalf("Noop.Lookup() error = %v", err)
+ }
+ if !got.IsZero() {
+ t.Fatalf("Noop.Lookup() = %+v, want zero", got)
+ }
+}
+
+func TestNoop_EmptyIPSafe(t *testing.T) {
+ got, err := Noop{}.Lookup(context.Background(), "")
+ if err != nil {
+ t.Fatalf("Noop.Lookup(\"\") error = %v", err)
+ }
+ if !got.IsZero() {
+ t.Fatalf("Noop.Lookup(\"\") = %+v, want zero", got)
+ }
+}
+
+func TestStatic_ReturnsConfiguredInfo(t *testing.T) {
+ want := Info{
+ Timezone: "Europe/London",
+ Locale: "en-GB",
+ WebRTCIP: "203.0.113.7",
+ CountryISO: "GB",
+ }
+ got, err := Static{Info: want}.Lookup(context.Background(), "ignored")
+ if err != nil {
+ t.Fatalf("Static.Lookup() error = %v", err)
+ }
+ if got != want {
+ t.Fatalf("Static.Lookup() = %+v, want %+v", got, want)
+ }
+}
+
+func TestStatic_EmptyIPStillReturnsConfigured(t *testing.T) {
+ want := Info{Timezone: "Europe/London"}
+ got, _ := Static{Info: want}.Lookup(context.Background(), "")
+ if got != want {
+ t.Fatalf("Static.Lookup(\"\") = %+v, want %+v", got, want)
+ }
+}
+
+func TestValidate(t *testing.T) {
+ tests := []struct {
+ name string
+ info Info
+ wantErr bool
+ wantSub string
+ }{
+ {name: "zero info accepted"},
+ {name: "full good info", info: Info{
+ Timezone: "Europe/London", Locale: "en-GB", WebRTCIP: "203.0.113.7", CountryISO: "GB",
+ }},
+ {name: "good language-only locale", info: Info{Locale: "en"}},
+ {name: "good 3-letter language", info: Info{Locale: "fil"}},
+ {name: "good ipv6 webrtc", info: Info{WebRTCIP: "2001:db8::1"}},
+ {name: "bad timezone", info: Info{Timezone: "Not/AZone"}, wantErr: true, wantSub: "timezone"},
+ {name: "bad locale lowercase region", info: Info{Locale: "en-gb"}, wantErr: true, wantSub: "locale"},
+ {name: "bad locale long region", info: Info{Locale: "en-GBR"}, wantErr: true, wantSub: "locale"},
+ {name: "bad locale digit", info: Info{Locale: "e1"}, wantErr: true, wantSub: "locale"},
+ {name: "bad webrtc IP", info: Info{WebRTCIP: "not-an-ip"}, wantErr: true, wantSub: "webrtcIP"},
+ {name: "bad country lowercase", info: Info{CountryISO: "gb"}, wantErr: true, wantSub: "countryISO"},
+ {name: "bad country 3-letter", info: Info{CountryISO: "GBR"}, wantErr: true, wantSub: "countryISO"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := Validate(tt.info)
+ if tt.wantErr {
+ if err == nil {
+ t.Fatalf("Validate(%+v) = nil, want error", tt.info)
+ }
+ if tt.wantSub != "" && !strings.Contains(err.Error(), tt.wantSub) {
+ t.Errorf("Validate(%+v) error = %v, want substring %q", tt.info, err, tt.wantSub)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("Validate(%+v) unexpected error = %v", tt.info, err)
+ }
+ })
+ }
+}
+
+var _ Provider = Noop{}
+var _ Provider = Static{}
diff --git a/internal/config/validate.go b/internal/config/validate.go
index 9f9b06fe..9a0a912c 100644
--- a/internal/config/validate.go
+++ b/internal/config/validate.go
@@ -3,8 +3,13 @@ package config
import (
"fmt"
"net"
+ "os"
+ "path/filepath"
+ "regexp"
"strconv"
"strings"
+
+ "github.com/pinchtab/pinchtab/internal/config/geo"
)
// ValidationError represents a configuration validation error.
@@ -62,6 +67,8 @@ func ValidateFileConfig(fc *FileConfig) []error {
})
}
errs = append(errs, validateCloakBrowserConfig(fc.Browser.Cloak)...)
+ errs = append(errs, ValidateBrowserProxy("browser.proxy", fc.Browser.Proxy)...)
+ errs = append(errs, ValidateBrowserTargets(fc.Browser)...)
if fc.MultiInstance.InstancePortStart != nil && fc.MultiInstance.InstancePortEnd != nil {
if *fc.MultiInstance.InstancePortStart > *fc.MultiInstance.InstancePortEnd {
@@ -370,30 +377,60 @@ func isValidBrowserProvider(provider string) bool {
}
}
+var cloakFingerprintSeedRegex = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
+
func validateCloakBrowserConfig(cloak CloakBrowserConfig) []error {
+ return validateCloakBrowserConfigAt("browser.cloak", cloak)
+}
+
+func validateCloakBrowserConfigAt(fieldPrefix string, cloak CloakBrowserConfig) []error {
var errs []error
if cloak.Platform != "" && !isValidCloakPlatform(cloak.Platform) {
errs = append(errs, ValidationError{
- Field: "browser.cloak.platform",
+ Field: fieldPrefix + ".platform",
Message: fmt.Sprintf("invalid value %q (must be windows, macos, or linux)", cloak.Platform),
})
}
if cloak.StorageQuotaMB != nil && *cloak.StorageQuotaMB < 0 {
errs = append(errs, ValidationError{
- Field: "browser.cloak.storageQuotaMB",
+ Field: fieldPrefix + ".storageQuotaMB",
Message: fmt.Sprintf("must be >= 0 (got %d)", *cloak.StorageQuotaMB),
})
}
- for field, value := range map[string]string{
- "browser.cloak.fingerprintSeed": cloak.FingerprintSeed,
- "browser.cloak.locale": cloak.Locale,
- "browser.cloak.timezone": cloak.Timezone,
- "browser.cloak.webrtcIP": cloak.WebRTCIP,
- } {
- if strings.ContainsAny(strings.TrimSpace(value), " \t\n\r") {
+ if seed := strings.TrimSpace(cloak.FingerprintSeed); seed != "" && !cloakFingerprintSeedRegex.MatchString(seed) {
+ errs = append(errs, ValidationError{
+ Field: fieldPrefix + ".fingerprintSeed",
+ Message: "must be 1-128 characters of letters, numbers, dot, underscore, colon, or hyphen",
+ })
+ }
+ if err := geo.Validate(geo.Info{Timezone: cloak.Timezone, Locale: cloak.Locale}); err != nil {
+ errs = append(errs, ValidationError{
+ Field: fieldPrefix,
+ Message: err.Error(),
+ })
+ }
+ if ip := strings.TrimSpace(cloak.WebRTCIP); ip != "" && !strings.EqualFold(ip, "auto") && net.ParseIP(ip) == nil {
+ errs = append(errs, ValidationError{
+ Field: fieldPrefix + ".webrtcIP",
+ Message: fmt.Sprintf("webrtcIP %q must be \"auto\" or a valid IP address", cloak.WebRTCIP),
+ })
+ }
+ if dir := strings.TrimSpace(cloak.FontsDir); dir != "" {
+ clean := filepath.Clean(dir)
+ if clean != dir {
errs = append(errs, ValidationError{
- Field: field,
- Message: "must not contain whitespace",
+ Field: fieldPrefix + ".fontsDir",
+ Message: fmt.Sprintf("must be a clean path (got %q, clean form is %q)", dir, clean),
+ })
+ } else if st, err := os.Stat(dir); err != nil {
+ errs = append(errs, ValidationError{
+ Field: fieldPrefix + ".fontsDir",
+ Message: fmt.Sprintf("must be an existing directory: %v", err),
+ })
+ } else if !st.IsDir() {
+ errs = append(errs, ValidationError{
+ Field: fieldPrefix + ".fontsDir",
+ Message: "must be an existing directory",
})
}
}
diff --git a/internal/config/validate_test.go b/internal/config/validate_test.go
index 4b1f4715..e713fd45 100644
--- a/internal/config/validate_test.go
+++ b/internal/config/validate_test.go
@@ -472,6 +472,7 @@ func TestValidateFileConfig_ChromeExtraFlags(t *testing.T) {
func TestValidateFileConfig_CloakBrowser(t *testing.T) {
quota := 2048
+ fontsDir := t.TempDir()
valid := &FileConfig{
Browser: BrowserConfig{
Provider: BrowserProviderCloak,
@@ -482,6 +483,7 @@ func TestValidateFileConfig_CloakBrowser(t *testing.T) {
Locale: "en-GB",
Timezone: "Europe/London",
WebRTCIP: "auto",
+ FontsDir: fontsDir,
StorageQuotaMB: &quota,
},
},
@@ -533,6 +535,42 @@ func TestValidateFileConfig_CloakBrowser(t *testing.T) {
}},
want: "browser.cloak.fingerprintSeed",
},
+ {
+ name: "invalid timezone",
+ fc: &FileConfig{Browser: BrowserConfig{
+ Provider: BrowserProviderCloak,
+ ChromeBinary: "/opt/cloakbrowser/chrome",
+ Cloak: CloakBrowserConfig{Timezone: "Not/AZone"},
+ }},
+ want: "browser.cloak",
+ },
+ {
+ name: "invalid locale",
+ fc: &FileConfig{Browser: BrowserConfig{
+ Provider: BrowserProviderCloak,
+ ChromeBinary: "/opt/cloakbrowser/chrome",
+ Cloak: CloakBrowserConfig{Locale: "en-gb"},
+ }},
+ want: "browser.cloak",
+ },
+ {
+ name: "invalid webrtc ip",
+ fc: &FileConfig{Browser: BrowserConfig{
+ Provider: BrowserProviderCloak,
+ ChromeBinary: "/opt/cloakbrowser/chrome",
+ Cloak: CloakBrowserConfig{WebRTCIP: "not-an-ip"},
+ }},
+ want: "browser.cloak.webrtcIP",
+ },
+ {
+ name: "fonts dir must exist",
+ fc: &FileConfig{Browser: BrowserConfig{
+ Provider: BrowserProviderCloak,
+ ChromeBinary: "/opt/cloakbrowser/chrome",
+ Cloak: CloakBrowserConfig{FontsDir: "/definitely/not/a/real/fonts/dir"},
+ }},
+ want: "browser.cloak.fontsDir",
+ },
}
for _, tt := range tests {
diff --git a/internal/dashboard/config_api.go b/internal/dashboard/config_api.go
index 90526f2c..927c444e 100644
--- a/internal/dashboard/config_api.go
+++ b/internal/dashboard/config_api.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"io"
"net/http"
+ "reflect"
"strings"
"sync"
"time"
@@ -172,6 +173,7 @@ func (c *ConfigAPI) HandlePutConfig(w http.ResponseWriter, r *http.Request) {
return
}
config.NormalizeFileConfigAliasesFromJSON(&normalized, body)
+ preserveWriteOnlyConfigFields(&normalized, current)
if errs := config.ValidateFileConfig(&normalized); len(errs) > 0 {
messages := make([]string, 0, len(errs))
@@ -183,7 +185,12 @@ func (c *ConfigAPI) HandlePutConfig(w http.ResponseWriter, r *http.Request) {
})
return
}
- preserveWriteOnlyConfigFields(&normalized, current)
+ changes := sensitiveConfigChanges(current, &normalized)
+ if changes.requiresElevation && !c.hasConfigWriteElevation(r) {
+ authn.AuditWarn(r, "config.update_elevation_required", "changes", changes.names)
+ httpx.ErrorCode(w, http.StatusForbidden, "session_elevation_required", "re-enter the API token before changing proxy or security settings", false, nil)
+ return
+ }
if err := config.SaveFileConfig(&normalized, path); err != nil {
httpx.Error(w, 500, err)
return
@@ -198,6 +205,12 @@ func (c *ConfigAPI) HandlePutConfig(w http.ResponseWriter, r *http.Request) {
}
restartReasons := c.restartReasonsFor(normalized)
+ if changes.proxyChanged {
+ authn.AuditLog(r, "config.proxy_changed",
+ "scopes", changes.proxyScopes,
+ "proxies", changes.proxyAudit,
+ )
+ }
authn.AuditLog(r, "config.updated",
"restartRequired", len(restartReasons) > 0,
"restartReasons", restartReasons,
@@ -205,6 +218,87 @@ func (c *ConfigAPI) HandlePutConfig(w http.ResponseWriter, r *http.Request) {
httpx.JSON(w, 200, c.configEnvelopeFor(normalized, path, restartReasons))
}
+type sensitiveConfigChangeSet struct {
+ requiresElevation bool
+ proxyChanged bool
+ names []string
+ proxyScopes []string
+ proxyAudit []proxyAuditChange
+}
+
+type proxyAuditChange struct {
+ Scope string `json:"scope"`
+ Server string `json:"server"`
+}
+
+func sensitiveConfigChanges(current, next *config.FileConfig) sensitiveConfigChangeSet {
+ var out sensitiveConfigChangeSet
+ if current == nil || next == nil {
+ return out
+ }
+ if !reflect.DeepEqual(current.Security, next.Security) {
+ out.requiresElevation = true
+ out.names = append(out.names, "security")
+ }
+ if !reflect.DeepEqual(current.Browser.Proxy, next.Browser.Proxy) {
+ out.requiresElevation = true
+ out.proxyChanged = true
+ out.names = append(out.names, "browser.proxy")
+ out.proxyScopes = append(out.proxyScopes, "browser.proxy")
+ out.proxyAudit = append(out.proxyAudit, proxyAuditChange{
+ Scope: "browser.proxy",
+ Server: next.Browser.Proxy.Redacted().Server,
+ })
+ }
+ for _, name := range changedTargetProxyNames(current.Browser.Targets, next.Browser.Targets) {
+ out.requiresElevation = true
+ out.proxyChanged = true
+ field := "browser.targets." + name + ".proxy"
+ out.names = append(out.names, field)
+ out.proxyScopes = append(out.proxyScopes, field)
+ out.proxyAudit = append(out.proxyAudit, proxyAuditChange{
+ Scope: field,
+ Server: next.Browser.Targets[name].Proxy.Redacted().Server,
+ })
+ }
+ return out
+}
+
+func changedTargetProxyNames(current, next config.BrowserTargetsConfig) []string {
+ seen := make(map[string]struct{}, len(current)+len(next))
+ names := make([]string, 0, len(current)+len(next))
+ for name := range current {
+ if _, ok := seen[name]; !ok {
+ seen[name] = struct{}{}
+ names = append(names, name)
+ }
+ }
+ for name := range next {
+ if _, ok := seen[name]; !ok {
+ seen[name] = struct{}{}
+ names = append(names, name)
+ }
+ }
+ var changed []string
+ for _, name := range names {
+ if !reflect.DeepEqual(current[name].Proxy, next[name].Proxy) {
+ changed = append(changed, name)
+ }
+ }
+ return changed
+}
+
+func (c *ConfigAPI) hasConfigWriteElevation(r *http.Request) bool {
+ if c == nil || c.runtime == nil || strings.TrimSpace(c.runtime.Token) == "" {
+ return true
+ }
+ creds := authn.CredentialsFromRequest(r)
+ if creds.Method != authn.MethodCookie {
+ return true
+ }
+ return c.sessions != nil && c.sessions.IsElevated(creds.Value, c.runtime.Token)
+}
+
func (c *ConfigAPI) healthInfo(includeSecurity bool) (healthEnvelope, error) {
_, _, restartReasons, err := c.currentConfig()
if err != nil {
@@ -333,6 +427,16 @@ func redactToken(cfg config.FileConfig) config.FileConfig {
cfg.AutoSolver.External.CapsolverKey = ""
cfg.AutoSolver.External.TwoCaptchaKey = ""
cfg.AutoSolver.Credentials = config.AutoSolverCredentialsConf{}
+ cfg.Browser.Proxy = cfg.Browser.Proxy.Redacted()
+ if len(cfg.Browser.Targets) > 0 {
+ // Copy before mutating: maps are reference types.
+ copied := make(config.BrowserTargetsConfig, len(cfg.Browser.Targets))
+ for name, t := range cfg.Browser.Targets {
+ t.Proxy = t.Proxy.Redacted()
+ copied[name] = t
+ }
+ cfg.Browser.Targets = copied
+ }
return cfg
}
@@ -355,6 +459,25 @@ func preserveWriteOnlyConfigFields(dst, src *config.FileConfig) {
preserveCredString(&dst.AutoSolver.Credentials.Form.Field1, src.AutoSolver.Credentials.Form.Field1)
preserveCredString(&dst.AutoSolver.Credentials.Form.Field2, src.AutoSolver.Credentials.Form.Field2)
preserveCredString(&dst.AutoSolver.Credentials.Form.Email, src.AutoSolver.Credentials.Form.Email)
+
+ // Restore the on-disk proxy password when the dashboard echoes back the redaction mask.
+ preserveProxyPassword(&dst.Browser.Proxy, src.Browser.Proxy)
+ for name, t := range dst.Browser.Targets {
+ if srcT, ok := src.Browser.Targets[name]; ok {
+ preserveProxyPassword(&t.Proxy, srcT.Proxy)
+ dst.Browser.Targets[name] = t
+ }
+ }
+}
+
+// preserveProxyPassword keeps the on-disk password when the inbound PUT is blank or the "***" mask.
+func preserveProxyPassword(dst *config.BrowserProxyConfig, src config.BrowserProxyConfig) {
+ if dst == nil {
+ return
+ }
+ if dst.Password == "" || dst.Password == "***" {
+ dst.Password = src.Password
+ }
}
// preserveCredString keeps the existing src value when dst is empty (i.e. the
diff --git a/internal/dashboard/config_api_test.go b/internal/dashboard/config_api_test.go
index daf47f8d..026f7827 100644
--- a/internal/dashboard/config_api_test.go
+++ b/internal/dashboard/config_api_test.go
@@ -3,6 +3,7 @@ package dashboard
import (
"bytes"
"encoding/json"
+ "log/slog"
"net/http"
"net/http/httptest"
"os"
@@ -14,6 +15,7 @@ import (
"time"
"github.com/pinchtab/pinchtab/internal/authn"
+ "github.com/pinchtab/pinchtab/internal/browsersession"
"github.com/pinchtab/pinchtab/internal/config"
)
@@ -191,6 +193,12 @@ func TestHandlePutConfigPreservesWriteOnlySecretsFromRedactedGetPayload(t *testi
fc.AutoSolver.External.TwoCaptchaKey = "twocaptcha-secret"
api := newConfigAPITestAPI(t, fc)
+ sessions := browsersession.NewManager(browsersession.Config{ElevationWindow: time.Minute})
+ sessionID, err := sessions.Create("secret-token")
+ if err != nil {
+ t.Fatalf("Create session: %v", err)
+ }
+ api.SetSessionManager(sessions)
getReq := httptest.NewRequest(http.MethodGet, "/api/config", nil)
getRes := httptest.NewRecorder()
@@ -208,6 +216,7 @@ func TestHandlePutConfigPreservesWriteOnlySecretsFromRedactedGetPayload(t *testi
}
putReq := httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewReader(body))
+ putReq.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
putRes := httptest.NewRecorder()
api.HandlePutConfig(putRes, putReq)
if putRes.Code != http.StatusOK {
@@ -295,6 +304,139 @@ func TestHandlePutConfigRejectsWriteOnlyTokenField(t *testing.T) {
}
}
+func TestHandlePutConfigRequiresElevationForProxyChangeWithDashboardCookie(t *testing.T) {
+ fc := config.DefaultFileConfig()
+ fc.Server.Token = "secret-token"
+ api := newConfigAPITestAPI(t, fc)
+ sessions := browsersession.NewManager(browsersession.Config{ElevationWindow: time.Minute})
+ sessionID, err := sessions.Create("secret-token")
+ if err != nil {
+ t.Fatalf("Create session: %v", err)
+ }
+ api.SetSessionManager(sessions)
+
+ payload := config.DefaultFileConfig()
+ payload.Browser.Proxy = config.BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Username: "alice",
+ Password: "secret",
+ }
+ body, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("Marshal() error = %v", err)
+ }
+
+ req := httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewReader(body))
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ w := httptest.NewRecorder()
+ api.HandlePutConfig(w, req)
+
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("HandlePutConfig() status = %d, want %d; body=%s", w.Code, http.StatusForbidden, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "session_elevation_required") {
+ t.Fatalf("response = %q, want session_elevation_required", w.Body.String())
+ }
+}
+
+func TestHandlePutConfigAllowsElevatedProxyChange(t *testing.T) {
+ fc := config.DefaultFileConfig()
+ fc.Server.Token = "secret-token"
+ api := newConfigAPITestAPI(t, fc)
+ sessions := browsersession.NewManager(browsersession.Config{ElevationWindow: time.Minute})
+ sessionID, err := sessions.Create("secret-token")
+ if err != nil {
+ t.Fatalf("Create session: %v", err)
+ }
+ if !sessions.Elevate(sessionID, "secret-token") {
+ t.Fatal("Elevate() = false, want true")
+ }
+ api.SetSessionManager(sessions)
+
+ payload := config.DefaultFileConfig()
+ payload.Browser.Proxy = config.BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Username: "alice",
+ Password: "secret",
+ }
+ body, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("Marshal() error = %v", err)
+ }
+
+ req := httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewReader(body))
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ w := httptest.NewRecorder()
+ api.HandlePutConfig(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("HandlePutConfig() status = %d, want %d; body=%s", w.Code, http.StatusOK, w.Body.String())
+ }
+}
+
+func TestHandlePutConfigAuditsProxyChangeServers(t *testing.T) {
+ fc := config.DefaultFileConfig()
+ fc.Server.Token = "secret-token"
+ api := newConfigAPITestAPI(t, fc)
+ sessions := browsersession.NewManager(browsersession.Config{ElevationWindow: time.Minute})
+ sessionID, err := sessions.Create("secret-token")
+ if err != nil {
+ t.Fatalf("Create session: %v", err)
+ }
+ if !sessions.Elevate(sessionID, "secret-token") {
+ t.Fatal("Elevate() = false, want true")
+ }
+ api.SetSessionManager(sessions)
+
+ payload := config.DefaultFileConfig()
+ payload.Browser.Proxy = config.BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Username: "alice",
+ Password: "secret",
+ }
+ payload.Browser.Targets = config.BrowserTargetsConfig{
+ "proxy-target": {
+ Provider: config.BrowserProviderChrome,
+ Proxy: config.BrowserProxyConfig{
+ Server: "socks5://10.0.0.1:1080",
+ Username: "bob",
+ Password: "target-secret",
+ },
+ },
+ }
+ body, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("Marshal() error = %v", err)
+ }
+
+ req := httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewReader(body))
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ w := httptest.NewRecorder()
+ logs := captureDashboardSlog(t, func() {
+ api.HandlePutConfig(w, req)
+ })
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("HandlePutConfig() status = %d, want %d; body=%s", w.Code, http.StatusOK, w.Body.String())
+ }
+ for _, needle := range []string{
+ `"event":"config.proxy_changed"`,
+ `"scope":"browser.proxy"`,
+ `"server":"http://proxy.example.com:8080"`,
+ `"scope":"browser.targets.proxy-target.proxy"`,
+ `"server":"socks5://10.0.0.1:1080"`,
+ } {
+ if !strings.Contains(logs, needle) {
+ t.Fatalf("expected audit log to contain %q\n%s", needle, logs)
+ }
+ }
+ for _, secret := range []string{"secret-token", "secret", "target-secret"} {
+ if strings.Contains(logs, secret) {
+ t.Fatalf("audit log leaked secret %q\n%s", secret, logs)
+ }
+ }
+}
+
func TestHandleHealthIncludesAgentCount(t *testing.T) {
fc := config.DefaultFileConfig()
api := newConfigAPITestAPI(t, fc)
@@ -317,6 +459,16 @@ func TestHandleHealthIncludesAgentCount(t *testing.T) {
}
}
+func captureDashboardSlog(t *testing.T, fn func()) string {
+ t.Helper()
+ var buf bytes.Buffer
+ old := slog.Default()
+ slog.SetDefault(slog.New(slog.NewJSONHandler(&buf, nil)))
+ defer slog.SetDefault(old)
+ fn()
+ return buf.String()
+}
+
func TestHandleHealthSecurityVisibilityByAuthMethod(t *testing.T) {
fc := config.DefaultFileConfig()
api := newConfigAPITestAPI(t, fc)
@@ -393,9 +545,41 @@ func TestRedactTokenCoversAllSensitiveFields(t *testing.T) {
fc.Security.StateEncryptionKey = &encKey
fc.AutoSolver.External.CapsolverKey = "test-capsolver-key"
fc.AutoSolver.External.TwoCaptchaKey = "test-twocaptcha-key"
+ fc.Browser.Proxy = config.BrowserProxyConfig{
+ Server: "http://proxy.example.com:8080",
+ Username: "alice",
+ Password: "raw-proxy-password",
+ }
+ fc.Browser.Targets = config.BrowserTargetsConfig{
+ "with-proxy": {
+ Provider: config.BrowserProviderChrome,
+ Proxy: config.BrowserProxyConfig{
+ Server: "socks5://10.0.0.1:1080",
+ Username: "bob",
+ Password: "target-proxy-password",
+ },
+ },
+ }
redacted := redactToken(fc)
+ // Masked to "***" (not empty) so the dashboard knows credentials are configured.
+ if redacted.Browser.Proxy.Password != "***" {
+ t.Errorf("Browser.Proxy.Password not redacted: got %q", redacted.Browser.Proxy.Password)
+ }
+ if redacted.Browser.Proxy.Server != fc.Browser.Proxy.Server {
+ t.Errorf("Browser.Proxy.Server should be preserved, got %q", redacted.Browser.Proxy.Server)
+ }
+ if tp := redacted.Browser.Targets["with-proxy"].Proxy.Password; tp != "***" {
+ t.Errorf("per-target proxy password not redacted: got %q", tp)
+ }
+ if fc.Browser.Proxy.Password != "raw-proxy-password" {
+ t.Errorf("redactToken mutated source Browser.Proxy.Password: %q", fc.Browser.Proxy.Password)
+ }
+ if fc.Browser.Targets["with-proxy"].Proxy.Password != "target-proxy-password" {
+ t.Errorf("redactToken mutated source target proxy password")
+ }
+
// Use reflection to find any sensitive fields that weren't redacted
var unredacted []string
findSensitiveFields(reflect.ValueOf(redacted), "", &unredacted)
@@ -442,7 +626,7 @@ func findSensitiveFields(v reflect.Value, path string, unredacted *[]string) {
}
}
- if isSensitive && !isZeroValue(fieldVal) {
+ if isSensitive && !isZeroValue(fieldVal) && !isMaskedString(fieldVal) {
*unredacted = append(*unredacted, fieldPath)
}
@@ -453,6 +637,13 @@ func findSensitiveFields(v reflect.Value, path string, unredacted *[]string) {
}
}
+func isMaskedString(v reflect.Value) bool {
+ if v.Kind() == reflect.String {
+ return v.String() == "***"
+ }
+ return false
+}
+
func isZeroValue(v reflect.Value) bool {
if v.Kind() == reflect.Ptr {
return v.IsNil()
diff --git a/internal/doctor/checks_binary.go b/internal/doctor/checks_binary.go
new file mode 100644
index 00000000..e7e5386e
--- /dev/null
+++ b/internal/doctor/checks_binary.go
@@ -0,0 +1,105 @@
+package doctor
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "os/exec"
+ "strings"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func resolveBinary(cfg *config.RuntimeConfig) string {
+ if cfg == nil {
+ return ""
+ }
+ return strings.TrimSpace(cfg.ChromeBinary)
+}
+
+func checkBinaryExists(_ context.Context, cfg *config.RuntimeConfig) CheckResult {
+ bin := resolveBinary(cfg)
+ if bin == "" {
+ return CheckResult{
+ Status: StatusSkip,
+ Detail: "browser.binary not set — relying on system-discovered chrome",
+ }
+ }
+ info, err := os.Stat(bin)
+ if err != nil {
+ return CheckResult{
+ Status: StatusFail,
+ Detail: fmt.Sprintf("%s: %v", bin, err),
+ Err: err,
+ }
+ }
+ if info.IsDir() {
+ return CheckResult{
+ Status: StatusFail,
+ Detail: fmt.Sprintf("%s is a directory", bin),
+ }
+ }
+ return CheckResult{
+ Status: StatusPass,
+ Detail: bin,
+ }
+}
+
+func checkBinaryExecutable(_ context.Context, cfg *config.RuntimeConfig) CheckResult {
+ bin := resolveBinary(cfg)
+ if bin == "" {
+ return CheckResult{Status: StatusSkip, Detail: "browser.binary not set — relying on system-discovered chrome"}
+ }
+ info, err := os.Stat(bin)
+ if err != nil {
+ return CheckResult{Status: StatusFail, Detail: err.Error(), Err: err}
+ }
+ mode := info.Mode()
+ if mode&0o111 == 0 {
+ return CheckResult{
+ Status: StatusFail,
+ Detail: fmt.Sprintf("file mode %#o has no executable bit", mode.Perm()),
+ }
+ }
+ return CheckResult{
+ Status: StatusPass,
+ Detail: fmt.Sprintf("file mode %#o", mode.Perm()),
+ }
+}
+
+func checkBinaryStarts(ctx context.Context, cfg *config.RuntimeConfig) CheckResult {
+ bin := resolveBinary(cfg)
+ if bin == "" {
+ return CheckResult{Status: StatusSkip, Detail: "browser.binary not set — relying on system-discovered chrome"}
+ }
+ cctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+
+ cmd := exec.CommandContext(cctx, bin, "--version")
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ return CheckResult{
+ Status: StatusFail,
+ Detail: fmt.Sprintf("--version failed: %v", err),
+ Err: err,
+ }
+ }
+ version := parseVersionLine(string(out))
+ if version == "" {
+ version = strings.TrimSpace(string(out))
+ }
+ return CheckResult{
+ Status: StatusPass,
+ Detail: version,
+ }
+}
+
+func parseVersionLine(s string) string {
+ for _, line := range strings.Split(s, "\n") {
+ if t := strings.TrimSpace(line); t != "" {
+ return t
+ }
+ }
+ return ""
+}
diff --git a/internal/doctor/checks_cdp.go b/internal/doctor/checks_cdp.go
new file mode 100644
index 00000000..0da3e556
--- /dev/null
+++ b/internal/doctor/checks_cdp.go
@@ -0,0 +1,192 @@
+package doctor
+
+import (
+ "bufio"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "regexp"
+ "time"
+
+ bridgeruntime "github.com/pinchtab/pinchtab/internal/bridge/runtime"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type probeResult struct {
+ Port int
+ VersionURL string
+}
+
+var devtoolsRe = regexp.MustCompile(`DevTools listening on ws://[^:]+:(\d+)/`)
+
+// launchAndProbe starts binary headless, waits for the DevTools banner,
+// confirms /json/version responds, and tears the browser down before return.
+func launchAndProbe(ctx context.Context, binary string, extraArgs []string, timeout time.Duration) (probeResult, error) {
+ cctx, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+
+ tmpDir, err := os.MkdirTemp("", "pinchtab-doctor-*")
+ if err != nil {
+ return probeResult{}, fmt.Errorf("create user-data-dir: %w", err)
+ }
+ defer func() { _ = os.RemoveAll(tmpDir) }()
+
+ args := []string{
+ "--headless=new",
+ "--remote-debugging-port=0",
+ "--user-data-dir=" + tmpDir,
+ "--no-first-run",
+ "--no-default-browser-check",
+ "--disable-gpu",
+ }
+ args = append(args, extraArgs...)
+
+ cmd := exec.CommandContext(cctx, binary, args...)
+ stderr, err := cmd.StderrPipe()
+ if err != nil {
+ return probeResult{}, fmt.Errorf("attach stderr: %w", err)
+ }
+ if err := cmd.Start(); err != nil {
+ return probeResult{}, fmt.Errorf("start browser: %w", err)
+ }
+
+ portCh := make(chan int, 1)
+ errCh := make(chan error, 1)
+ go scrapeDevtoolsPort(stderr, portCh, errCh)
+
+ // Race: process exit, ctx timeout, port discovered.
+ procExitCh := make(chan error, 1)
+ go func() { procExitCh <- cmd.Wait() }()
+ procReaped := false
+
+ // Ensure the subprocess is reaped on return so we don't leak zombies even
+ // when context cancellation races the parse loop. cmd.Wait is owned by the
+ // goroutine above; this defer only kills and drains that result.
+ defer func() {
+ if procReaped {
+ return
+ }
+ _ = cmd.Process.Kill()
+ select {
+ case <-procExitCh:
+ case <-time.After(2 * time.Second):
+ }
+ }()
+
+ var port int
+ select {
+ case <-cctx.Done():
+ return probeResult{}, fmt.Errorf("timed out waiting for DevTools banner: %w", cctx.Err())
+ case err := <-procExitCh:
+ procReaped = true
+ if err == nil {
+ return probeResult{}, errors.New("browser exited cleanly before exposing DevTools")
+ }
+ return probeResult{}, fmt.Errorf("browser exited before DevTools banner: %w", err)
+ case err := <-errCh:
+ return probeResult{}, err
+ case port = <-portCh:
+ }
+
+ versionURL := fmt.Sprintf("http://127.0.0.1:%d/json/version", port)
+ probe, err := probeCDPVersionWithRetry(cctx, versionURL)
+ if err != nil {
+ return probeResult{Port: port, VersionURL: versionURL}, err
+ }
+ return probeResult{Port: port, VersionURL: probe.VersionURL}, nil
+}
+
+func scrapeDevtoolsPort(r io.ReadCloser, portCh chan<- int, errCh chan<- error) {
+ defer func() { _ = r.Close() }()
+ scanner := bufio.NewScanner(r)
+ scanner.Buffer(make([]byte, 64*1024), 1024*1024)
+ for scanner.Scan() {
+ line := scanner.Text()
+ m := devtoolsRe.FindStringSubmatch(line)
+ if len(m) == 2 {
+ var port int
+ _, err := fmt.Sscanf(m[1], "%d", &port)
+ if err != nil {
+ errCh <- fmt.Errorf("parse DevTools port %q: %w", m[1], err)
+ return
+ }
+ portCh <- port
+ // Drain remaining stderr so the child doesn't block on a full pipe.
+ for scanner.Scan() {
+ }
+ return
+ }
+ }
+ if err := scanner.Err(); err != nil {
+ errCh <- fmt.Errorf("read stderr: %w", err)
+ return
+ }
+ errCh <- errors.New("stderr closed before DevTools banner appeared")
+}
+
+func probeCDPVersionWithRetry(ctx context.Context, url string) (bridgeruntime.CDPVersionProbe, error) {
+ deadline, ok := ctx.Deadline()
+ if !ok {
+ deadline = time.Now().Add(5 * time.Second)
+ }
+ var lastErr error
+ for {
+ if time.Now().After(deadline) {
+ if lastErr == nil {
+ lastErr = errors.New("deadline exceeded")
+ }
+ return bridgeruntime.CDPVersionProbe{}, fmt.Errorf("probe %s: %w", url, lastErr)
+ }
+ probe, err := bridgeruntime.ProbeCDPVersion(ctx, url, nil)
+ if err != nil {
+ lastErr = err
+ time.Sleep(100 * time.Millisecond)
+ continue
+ }
+ return probe, nil
+ }
+}
+
+func checkCDPReachable(ctx context.Context, cfg *config.RuntimeConfig) CheckResult {
+ bin := resolveBinary(cfg)
+ if bin == "" {
+ return CheckResult{Status: StatusSkip, Detail: "skipped — no browser.binary set (see cloakbrowser_present)"}
+ }
+ res, err := launchAndProbe(ctx, bin, nil, 10*time.Second)
+ if err != nil {
+ return CheckResult{Status: StatusFail, Detail: err.Error(), Err: err}
+ }
+ return CheckResult{
+ Status: StatusPass,
+ Detail: fmt.Sprintf("/json/version OK on port %d", res.Port),
+ }
+}
+
+func checkFingerprintFlagsAccepted(ctx context.Context, cfg *config.RuntimeConfig) CheckResult {
+ bin := resolveBinary(cfg)
+ if bin == "" {
+ return CheckResult{Status: StatusSkip, Detail: "skipped — no browser.binary set (see cloakbrowser_present)"}
+ }
+ args := bridgeruntime.CloakBrowserFlagArgs(cfg)
+ if len(args) == 0 {
+ return CheckResult{
+ Status: StatusSkip,
+ Detail: "no cloak fingerprint flags configured",
+ }
+ }
+ res, err := launchAndProbe(ctx, bin, args, 10*time.Second)
+ if err != nil {
+ return CheckResult{
+ Status: StatusFail,
+ Detail: fmt.Sprintf("flags rejected or browser crashed: %v", err),
+ Err: err,
+ }
+ }
+ return CheckResult{
+ Status: StatusPass,
+ Detail: fmt.Sprintf("flags accepted, /json/version OK on port %d", res.Port),
+ }
+}
diff --git a/internal/doctor/checks_fonts.go b/internal/doctor/checks_fonts.go
new file mode 100644
index 00000000..c0108bf5
--- /dev/null
+++ b/internal/doctor/checks_fonts.go
@@ -0,0 +1,47 @@
+package doctor
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/browserprobe"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func isWindowsPlatform(p string) bool {
+ p = strings.ToLower(strings.TrimSpace(p))
+ return p == "windows" || strings.HasPrefix(p, "win")
+}
+
+func checkLinuxFontsPresent(ctx context.Context, cfg *config.RuntimeConfig) CheckResult {
+ host := HostOS()
+ if host != "linux" {
+ return CheckResult{
+ Status: StatusSkip,
+ Detail: fmt.Sprintf("not applicable on %s (only enforced on linux hosts)", host),
+ }
+ }
+ if cfg == nil || !isWindowsPlatform(cfg.Cloak.Platform) {
+ return CheckResult{
+ Status: StatusSkip,
+ Detail: "skipped (cloak.platform != windows)",
+ }
+ }
+
+ probe := browserprobe.ProbeWindowsFingerprintFonts(ctx)
+ if len(probe.Matched) == 0 {
+ detail := "no windows fingerprint fonts found via filesystem scan (install msttcorefonts or mount a Windows fonts dir)"
+ if probe.Source == "fc-list" {
+ detail = fmt.Sprintf("%s found no windows fingerprint fonts (expected one of: %s)", probe.Source, strings.Join(probe.Expected, ", "))
+ }
+ return CheckResult{
+ Status: StatusWarn,
+ Detail: detail,
+ }
+ }
+ return CheckResult{
+ Status: StatusPass,
+ Detail: fmt.Sprintf("%s: %s", probe.Source, strings.Join(probe.Matched, ", ")),
+ }
+}
diff --git a/internal/doctor/checks_system.go b/internal/doctor/checks_system.go
new file mode 100644
index 00000000..7e76bc6b
--- /dev/null
+++ b/internal/doctor/checks_system.go
@@ -0,0 +1,167 @@
+package doctor
+
+import (
+ "context"
+ "fmt"
+ "os/exec"
+ "strings"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/browserprobe"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+// chromeMinVersion is the lowest Chrome we accept: 120 (Dec 2023) ships
+// headless=new and the CDP/BiDi surfaces PinchTab drives.
+const chromeMinVersion = "120.0.0"
+
+// cloakMinVersion matches the documented CloakBrowser floor tested against.
+const cloakMinVersion = "100.0.0"
+
+func runVersion(ctx context.Context, bin string) (string, error) {
+ cctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ out, err := exec.CommandContext(cctx, bin, "--version").CombinedOutput()
+ if err != nil {
+ return "", err
+ }
+ line := parseVersionLine(string(out))
+ if line == "" {
+ line = strings.TrimSpace(string(out))
+ }
+ return line, nil
+}
+
+func checkConfigFile(_ context.Context, _ *config.RuntimeConfig) CheckResult {
+ status := config.InspectConfigFile()
+ if !status.Found {
+ detail := fmt.Sprintf("not found at %s", status.Path)
+ if status.EnvOverride {
+ detail += " (PINCHTAB_CONFIG override; default would be " + status.DefaultPath + ")"
+ } else {
+ detail += " (default search path; set PINCHTAB_CONFIG to override)"
+ }
+ return CheckResult{Status: StatusWarn, Detail: detail}
+ }
+ if status.ParseErr != nil {
+ return CheckResult{
+ Status: StatusFail,
+ Detail: fmt.Sprintf("%s: parse error: %v", status.Path, status.ParseErr),
+ Err: status.ParseErr,
+ }
+ }
+ return CheckResult{
+ Status: StatusPass,
+ Detail: status.Path + " (loaded)",
+ }
+}
+
+// checkChromePresent answers "is any Chrome on this machine?" independent
+// of cfg.ChromeBinary (which the binary_* checks already cover).
+func checkChromePresent(ctx context.Context, _ *config.RuntimeConfig) CheckResult {
+ if HostOS() == "windows" {
+ // TODO(windows): implement Windows install-path discovery.
+ return CheckResult{
+ Status: StatusSkip,
+ Detail: "chrome discovery not implemented on windows",
+ }
+ }
+ discovery := browserprobe.DiscoverChromeBinary(HostOS())
+ if discovery.Found == "" {
+ return CheckResult{
+ Status: StatusFail,
+ Detail: "no chrome/chromium found; probed: " + strings.Join(discovery.Probed, ", "),
+ }
+ }
+ line, err := runVersion(ctx, discovery.Found)
+ if err != nil {
+ return CheckResult{
+ Status: StatusWarn,
+ Detail: fmt.Sprintf("%s: --version failed: %v", discovery.Found, err),
+ Err: err,
+ }
+ }
+ token := extractVersionToken(line)
+ if token == "" {
+ return CheckResult{
+ Status: StatusWarn,
+ Detail: fmt.Sprintf("%s: could not parse version from %q", discovery.Found, line),
+ }
+ }
+ if compareSemver(token, chromeMinVersion) < 0 {
+ return CheckResult{
+ Status: StatusWarn,
+ Detail: fmt.Sprintf("%s -> %s (< required %s)", discovery.Found, token, chromeMinVersion),
+ }
+ }
+ return CheckResult{
+ Status: StatusPass,
+ Detail: fmt.Sprintf("%s -> %s (>= %s)", discovery.Found, token, chromeMinVersion),
+ }
+}
+
+// checkCloakBrowserPresent skips (does not fail) when CloakBrowser is absent
+// and no cloak provider is configured.
+func checkCloakBrowserPresent(ctx context.Context, cfg *config.RuntimeConfig) CheckResult {
+ if HostOS() == "windows" {
+ return CheckResult{
+ Status: StatusSkip,
+ Detail: "cloakbrowser discovery not implemented on windows",
+ }
+ }
+ cloakConfigured := isCloakConfigured(cfg)
+
+ discovery := browserprobe.DiscoverCloakBrowserBinary(HostOS())
+ if discovery.Found == "" {
+ if cloakConfigured {
+ return CheckResult{
+ Status: StatusFail,
+ Detail: "cloakbrowser not found but a cloak provider is configured; set browser.binary or install CloakBrowser. probed: " + strings.Join(discovery.Probed, ", "),
+ }
+ }
+ return CheckResult{
+ Status: StatusSkip,
+ Detail: "not found (skipped — no cloak provider configured)",
+ }
+ }
+ line, err := runVersion(ctx, discovery.Found)
+ if err != nil {
+ return CheckResult{
+ Status: StatusWarn,
+ Detail: fmt.Sprintf("%s: --version failed: %v", discovery.Found, err),
+ Err: err,
+ }
+ }
+ token := extractVersionToken(line)
+ if token == "" {
+ return CheckResult{
+ Status: StatusWarn,
+ Detail: fmt.Sprintf("%s: could not parse version from %q", discovery.Found, line),
+ }
+ }
+ if compareSemver(token, cloakMinVersion) < 0 {
+ return CheckResult{
+ Status: StatusWarn,
+ Detail: fmt.Sprintf("%s -> %s (< required %s)", discovery.Found, token, cloakMinVersion),
+ }
+ }
+ return CheckResult{
+ Status: StatusPass,
+ Detail: fmt.Sprintf("%s -> %s (>= %s)", discovery.Found, token, cloakMinVersion),
+ }
+}
+
+func isCloakConfigured(cfg *config.RuntimeConfig) bool {
+ if cfg == nil {
+ return false
+ }
+ if config.IsCloakBrowserProvider(cfg.BrowserProvider) {
+ return true
+ }
+ for _, t := range cfg.Targets {
+ if config.IsCloakBrowserProvider(t.Provider) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/doctor/checks_system_test.go b/internal/doctor/checks_system_test.go
new file mode 100644
index 00000000..efdd490b
--- /dev/null
+++ b/internal/doctor/checks_system_test.go
@@ -0,0 +1,220 @@
+package doctor
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestCompareSemver(t *testing.T) {
+ cases := []struct {
+ a, b string
+ want int
+ }{
+ {"1.0.0", "1.0.0", 0},
+ {"1.2.3", "1.2.4", -1},
+ {"2.0.0", "1.9.9", 1},
+ {"v120.0.0", "120.0.0", 0},
+ {"V120", "120.0.0", 0},
+ {"146.0.7680.177", "120.0.0", 1},
+ {"99.0.4844.51", "120.0.0", -1},
+ {"120", "120.0.0", 0},
+ {"120.1", "120.0.99", 1},
+ {"1.2.3-alpha", "1.2.3", 0},
+ {"1.2.3+build.5", "1.2.3", 0},
+ {"1.2.3-rc1", "1.2.4", -1},
+ {"120.0.7680a", "120.0.7680", 0},
+ {"", "0.0.0", 0},
+ }
+ for _, c := range cases {
+ t.Run(c.a+"_vs_"+c.b, func(t *testing.T) {
+ if got := compareSemver(c.a, c.b); got != c.want {
+ t.Fatalf("compareSemver(%q,%q) = %d, want %d", c.a, c.b, got, c.want)
+ }
+ })
+ }
+}
+
+func TestExtractVersionToken(t *testing.T) {
+ cases := []struct {
+ in, want string
+ }{
+ {"Google Chrome 146.0.7680.177", "146.0.7680.177"},
+ {"Chromium 99.0.4844.51 snap", "99.0.4844.51"},
+ {"weird (120.0.0)", "120.0.0"},
+ {"no version here", ""},
+ {"", ""},
+ }
+ for _, c := range cases {
+ if got := extractVersionToken(c.in); got != c.want {
+ t.Errorf("extractVersionToken(%q) = %q, want %q", c.in, got, c.want)
+ }
+ }
+}
+
+func TestConfigFile_Found(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "config.json")
+ if err := os.WriteFile(path, []byte(`{"configVersion":"1"}`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PINCHTAB_CONFIG", path)
+ r := checkConfigFile(context.Background(), nil)
+ if r.Status != StatusPass {
+ t.Fatalf("status = %v want pass; detail=%q err=%v", r.Status, r.Detail, r.Err)
+ }
+ if !strings.Contains(r.Detail, path) {
+ t.Errorf("detail %q should contain path %q", r.Detail, path)
+ }
+}
+
+func TestConfigFile_Missing(t *testing.T) {
+ missing := filepath.Join(t.TempDir(), "nope.json")
+ t.Setenv("PINCHTAB_CONFIG", missing)
+ r := checkConfigFile(context.Background(), nil)
+ if r.Status != StatusWarn {
+ t.Fatalf("status = %v want warn; detail=%q", r.Status, r.Detail)
+ }
+ if !strings.Contains(r.Detail, "not found") {
+ t.Errorf("expected 'not found' in detail, got %q", r.Detail)
+ }
+}
+
+func TestConfigFile_ParseError(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "config.json")
+ if err := os.WriteFile(path, []byte("{not json"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PINCHTAB_CONFIG", path)
+ r := checkConfigFile(context.Background(), nil)
+ if r.Status != StatusFail {
+ t.Fatalf("status = %v want fail; detail=%q", r.Status, r.Detail)
+ }
+ if !strings.Contains(r.Detail, "parse error") {
+ t.Errorf("expected 'parse error' in detail, got %q", r.Detail)
+ }
+}
+
+// withStubBinary installs a fake "chrome --version" script as the first
+// $PATH entry for the duration of the test and returns its directory.
+func withStubBinary(t *testing.T, name, versionOutput string) string {
+ t.Helper()
+ if runtime.GOOS == "windows" {
+ t.Skip("stub binary tests require unix shell")
+ }
+ dir := t.TempDir()
+ script := "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then echo '" + versionOutput + "'; fi\n"
+ path := filepath.Join(dir, name)
+ if err := os.WriteFile(path, []byte(script), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PATH", dir)
+ return dir
+}
+
+func TestChromePresent_PassWithRecentVersion(t *testing.T) {
+ withStubBinary(t, "google-chrome", "Google Chrome 146.0.7680.177")
+ r := checkChromePresent(context.Background(), nil)
+ if r.Status != StatusPass {
+ t.Fatalf("status = %v want pass; detail=%q err=%v", r.Status, r.Detail, r.Err)
+ }
+ if !strings.Contains(r.Detail, "146.0.7680.177") {
+ t.Errorf("expected version in detail, got %q", r.Detail)
+ }
+}
+
+func TestChromePresent_WarnOnOldVersion(t *testing.T) {
+ withStubBinary(t, "google-chrome", "Google Chrome 99.0.4844.51")
+ r := checkChromePresent(context.Background(), nil)
+ if r.Status != StatusWarn {
+ t.Fatalf("status = %v want warn; detail=%q", r.Status, r.Detail)
+ }
+ if !strings.Contains(r.Detail, "<") {
+ t.Errorf("expected '< required' marker in detail, got %q", r.Detail)
+ }
+}
+
+func TestChromePresent_FailWhenAbsent(t *testing.T) {
+ t.Setenv("PATH", t.TempDir())
+ // Force shared binary discovery to walk an OS arm with no fallback hits.
+ prev := HostOS
+ defer func() { HostOS = prev }()
+ HostOS = func() string { return "linux" }
+ r := checkChromePresent(context.Background(), nil)
+ if r.Status != StatusFail {
+ t.Fatalf("status = %v want fail; detail=%q", r.Status, r.Detail)
+ }
+ if !strings.Contains(r.Detail, "no chrome") {
+ t.Errorf("expected 'no chrome' detail, got %q", r.Detail)
+ }
+}
+
+func TestChromePresent_SkipOnWindows(t *testing.T) {
+ prev := HostOS
+ defer func() { HostOS = prev }()
+ HostOS = func() string { return "windows" }
+ r := checkChromePresent(context.Background(), nil)
+ if r.Status != StatusSkip {
+ t.Fatalf("status = %v want skip", r.Status)
+ }
+}
+
+func TestCloakBrowserPresent_SkipWhenAbsentAndUnconfigured(t *testing.T) {
+ t.Setenv("PATH", t.TempDir())
+ t.Setenv("HOME", t.TempDir())
+ prev := HostOS
+ defer func() { HostOS = prev }()
+ HostOS = func() string { return "linux" }
+ cfg := &config.RuntimeConfig{BrowserProvider: config.BrowserProviderChrome}
+ r := checkCloakBrowserPresent(context.Background(), cfg)
+ if r.Status != StatusSkip {
+ t.Fatalf("status = %v want skip; detail=%q", r.Status, r.Detail)
+ }
+}
+
+func TestCloakBrowserPresent_FailWhenAbsentAndConfigured(t *testing.T) {
+ t.Setenv("PATH", t.TempDir())
+ t.Setenv("HOME", t.TempDir())
+ prev := HostOS
+ defer func() { HostOS = prev }()
+ HostOS = func() string { return "linux" }
+ cfg := &config.RuntimeConfig{BrowserProvider: config.BrowserProviderCloak}
+ r := checkCloakBrowserPresent(context.Background(), cfg)
+ if r.Status != StatusFail {
+ t.Fatalf("status = %v want fail; detail=%q", r.Status, r.Detail)
+ }
+}
+
+func TestCloakBrowserPresent_FailWhenTargetConfiguredCloak(t *testing.T) {
+ t.Setenv("PATH", t.TempDir())
+ t.Setenv("HOME", t.TempDir())
+ prev := HostOS
+ defer func() { HostOS = prev }()
+ HostOS = func() string { return "linux" }
+ cfg := &config.RuntimeConfig{
+ BrowserProvider: config.BrowserProviderChrome,
+ Targets: config.BrowserTargetsConfig{
+ "cloak-eu": config.BrowserTargetConfig{Provider: config.BrowserProviderCloak},
+ },
+ }
+ r := checkCloakBrowserPresent(context.Background(), cfg)
+ if r.Status != StatusFail {
+ t.Fatalf("status = %v want fail; detail=%q", r.Status, r.Detail)
+ }
+}
+
+func TestCloakBrowserPresent_PassWithStub(t *testing.T) {
+ withStubBinary(t, "cloakbrowser", "CloakBrowser 130.0.6723.91")
+ t.Setenv("HOME", t.TempDir())
+ cfg := &config.RuntimeConfig{BrowserProvider: config.BrowserProviderCloak}
+ r := checkCloakBrowserPresent(context.Background(), cfg)
+ if r.Status != StatusPass {
+ t.Fatalf("status = %v want pass; detail=%q err=%v", r.Status, r.Detail, r.Err)
+ }
+}
diff --git a/internal/doctor/format.go b/internal/doctor/format.go
new file mode 100644
index 00000000..32f30047
--- /dev/null
+++ b/internal/doctor/format.go
@@ -0,0 +1,89 @@
+package doctor
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "time"
+)
+
+type jsonReport struct {
+ Provider string `json:"provider"`
+ Target string `json:"target,omitempty"`
+ Results []CheckResult `json:"results"`
+ Summary Summary `json:"summary"`
+}
+
+func WriteText(w io.Writer, provider, target string, results []CheckResult) {
+ header := fmt.Sprintf("pinchtab doctor (provider=%s", provider)
+ if target != "" {
+ header += ", target=" + target
+ }
+ header += ")"
+ _, _ = fmt.Fprintln(w, header)
+ _, _ = fmt.Fprintln(w)
+
+ for _, r := range results {
+ _, _ = fmt.Fprintln(w, formatResultLine(r))
+ }
+
+ s := Summarize(results)
+ _, _ = fmt.Fprintln(w)
+ _, _ = fmt.Fprintf(w, "%d passed, %d failed, %d skipped, %d warnings.\n",
+ s.Passed, s.Failed, s.Skipped, s.Warnings)
+}
+
+func formatResultLine(r CheckResult) string {
+ marker := statusMarker(r.Status)
+ detail := r.Detail
+ if detail == "" && r.ErrMsg != "" {
+ detail = r.ErrMsg
+ }
+ return fmt.Sprintf("%s %-28s %s (%s)", marker, r.Name, detail, shortDuration(r.Duration))
+}
+
+func statusMarker(s CheckStatus) string {
+ switch s {
+ case StatusPass:
+ return "OK "
+ case StatusFail:
+ return "FAIL"
+ case StatusWarn:
+ return "WARN"
+ case StatusSkip:
+ return "SKIP"
+ default:
+ return "? "
+ }
+}
+
+func shortDuration(d time.Duration) string {
+ if d <= 0 {
+ return "0ms"
+ }
+ if d < time.Millisecond {
+ return "<1ms"
+ }
+ if d < time.Second {
+ return fmt.Sprintf("%dms", d.Milliseconds())
+ }
+ return fmt.Sprintf("%.1fs", d.Seconds())
+}
+
+func WriteJSON(w io.Writer, provider, target string, results []CheckResult) error {
+ // Populate ErrMsg for JSON consumers in case a check forgot to copy from Err.
+ for i := range results {
+ if results[i].Err != nil && results[i].ErrMsg == "" {
+ results[i].ErrMsg = results[i].Err.Error()
+ }
+ }
+ report := jsonReport{
+ Provider: provider,
+ Target: target,
+ Results: results,
+ Summary: Summarize(results),
+ }
+ enc := json.NewEncoder(w)
+ enc.SetIndent("", " ")
+ return enc.Encode(report)
+}
diff --git a/internal/doctor/runner.go b/internal/doctor/runner.go
new file mode 100644
index 00000000..aaa8df28
--- /dev/null
+++ b/internal/doctor/runner.go
@@ -0,0 +1,127 @@
+// Package doctor implements the `pinchtab doctor` diagnostic command.
+package doctor
+
+import (
+ "context"
+ "runtime"
+ "strings"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type CheckStatus string
+
+const (
+ StatusPass CheckStatus = "pass"
+ StatusFail CheckStatus = "fail"
+ StatusWarn CheckStatus = "warn"
+ StatusSkip CheckStatus = "skip"
+)
+
+type CheckResult struct {
+ Name string `json:"name"`
+ Status CheckStatus `json:"status"`
+ Detail string `json:"detail"`
+ Err error `json:"-"`
+ ErrMsg string `json:"error,omitempty"`
+ Duration time.Duration `json:"durationMs"`
+}
+
+type CheckFunc func(ctx context.Context, cfg *config.RuntimeConfig) CheckResult
+
+type CheckEntry struct {
+ Name string
+ Fn CheckFunc
+}
+
+type Summary struct {
+ Passed int `json:"passed"`
+ Failed int `json:"failed"`
+ Warnings int `json:"warnings"`
+ Skipped int `json:"skipped"`
+}
+
+func Summarize(results []CheckResult) Summary {
+ var s Summary
+ for _, r := range results {
+ switch r.Status {
+ case StatusPass:
+ s.Passed++
+ case StatusFail:
+ s.Failed++
+ case StatusWarn:
+ s.Warnings++
+ case StatusSkip:
+ s.Skipped++
+ }
+ }
+ return s
+}
+
+// ExitCode returns 1 when any check failed; skipped/warn do not fail the run.
+func ExitCode(s Summary) int {
+ if s.Failed > 0 {
+ return 1
+ }
+ return 0
+}
+
+// Registry returns the ordered list of checks that apply to cfg. Inapplicable
+// checks are omitted entirely so `--check=<name>` reports "unknown check"
+// rather than silently skipping.
+func Registry(cfg *config.RuntimeConfig) []CheckEntry {
+ entries := []CheckEntry{
+ {Name: "config_file", Fn: checkConfigFile},
+ {Name: "chrome_present", Fn: checkChromePresent},
+ {Name: "cloakbrowser_present", Fn: checkCloakBrowserPresent},
+ {Name: "binary_exists", Fn: checkBinaryExists},
+ {Name: "binary_executable", Fn: checkBinaryExecutable},
+ {Name: "binary_starts", Fn: checkBinaryStarts},
+ }
+ if cfg != nil && config.IsCloakBrowserProvider(cfg.BrowserProvider) {
+ entries = append(entries,
+ CheckEntry{Name: "cdp_reachable", Fn: checkCDPReachable},
+ CheckEntry{Name: "fingerprint_flags_accepted", Fn: checkFingerprintFlagsAccepted},
+ CheckEntry{Name: "linux_fonts_present", Fn: checkLinuxFontsPresent},
+ )
+ }
+ return entries
+}
+
+// Run executes the diagnostic pipeline; when checkFilter is non-empty only
+// the named check runs.
+func Run(ctx context.Context, cfg *config.RuntimeConfig, checkFilter string) []CheckResult {
+ entries := Registry(cfg)
+ checkFilter = strings.TrimSpace(checkFilter)
+
+ out := make([]CheckResult, 0, len(entries))
+ for _, e := range entries {
+ if checkFilter != "" && e.Name != checkFilter {
+ continue
+ }
+ start := time.Now()
+ r := e.Fn(ctx, cfg)
+ r.Name = e.Name
+ if r.Duration == 0 {
+ r.Duration = time.Since(start)
+ }
+ if r.Err != nil && r.ErrMsg == "" {
+ r.ErrMsg = r.Err.Error()
+ }
+ out = append(out, r)
+ }
+ return out
+}
+
+func KnownCheck(cfg *config.RuntimeConfig, name string) bool {
+ for _, e := range Registry(cfg) {
+ if e.Name == name {
+ return true
+ }
+ }
+ return false
+}
+
+// HostOS wraps runtime.GOOS to permit test override.
+var HostOS = func() string { return runtime.GOOS }
diff --git a/internal/doctor/runner_test.go b/internal/doctor/runner_test.go
new file mode 100644
index 00000000..ab6da9b0
--- /dev/null
+++ b/internal/doctor/runner_test.go
@@ -0,0 +1,323 @@
+package doctor
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+
+ bridgeruntime "github.com/pinchtab/pinchtab/internal/bridge/runtime"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestSummarize_Counts(t *testing.T) {
+ results := []CheckResult{
+ {Status: StatusPass},
+ {Status: StatusPass},
+ {Status: StatusFail},
+ {Status: StatusWarn},
+ {Status: StatusSkip},
+ }
+ got := Summarize(results)
+ want := Summary{Passed: 2, Failed: 1, Warnings: 1, Skipped: 1}
+ if got != want {
+ t.Fatalf("Summarize = %+v, want %+v", got, want)
+ }
+}
+
+func TestExitCode(t *testing.T) {
+ cases := []struct {
+ name string
+ s Summary
+ want int
+ }{
+ {"all pass", Summary{Passed: 3}, 0},
+ {"skip only", Summary{Skipped: 3}, 0},
+ {"warn does not fail", Summary{Warnings: 2, Passed: 1}, 0},
+ {"any fail -> 1", Summary{Passed: 1, Failed: 1}, 1},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ if got := ExitCode(c.s); got != c.want {
+ t.Fatalf("ExitCode(%+v) = %d, want %d", c.s, got, c.want)
+ }
+ })
+ }
+}
+
+func TestRun_RegistryOrdering_Chrome(t *testing.T) {
+ cfg := &config.RuntimeConfig{BrowserProvider: config.BrowserProviderChrome, ChromeBinary: "/does/not/exist"}
+ got := Run(context.Background(), cfg, "")
+ wantOrder := []string{
+ "config_file",
+ "chrome_present",
+ "cloakbrowser_present",
+ "binary_exists",
+ "binary_executable",
+ "binary_starts",
+ }
+ if len(got) != len(wantOrder) {
+ t.Fatalf("expected %d results for chrome provider, got %d (%v)", len(wantOrder), len(got), got)
+ }
+ for i, name := range wantOrder {
+ if got[i].Name != name {
+ t.Errorf("result[%d].Name = %q, want %q", i, got[i].Name, name)
+ }
+ }
+}
+
+func TestRun_RegistryOrdering_Cloak(t *testing.T) {
+ cfg := &config.RuntimeConfig{BrowserProvider: config.BrowserProviderCloak, ChromeBinary: "/does/not/exist"}
+ got := Run(context.Background(), cfg, "")
+ wantOrder := []string{
+ "config_file",
+ "chrome_present",
+ "cloakbrowser_present",
+ "binary_exists",
+ "binary_executable",
+ "binary_starts",
+ "cdp_reachable",
+ "fingerprint_flags_accepted",
+ "linux_fonts_present",
+ }
+ if len(got) != len(wantOrder) {
+ t.Fatalf("expected %d results for cloak provider, got %d", len(wantOrder), len(got))
+ }
+ for i, name := range wantOrder {
+ if got[i].Name != name {
+ t.Errorf("result[%d].Name = %q, want %q", i, got[i].Name, name)
+ }
+ }
+}
+
+func TestRun_CheckFilter(t *testing.T) {
+ cfg := &config.RuntimeConfig{BrowserProvider: config.BrowserProviderChrome, ChromeBinary: "/does/not/exist"}
+ got := Run(context.Background(), cfg, "binary_exists")
+ if len(got) != 1 {
+ t.Fatalf("filter binary_exists: got %d results, want 1", len(got))
+ }
+ if got[0].Name != "binary_exists" {
+ t.Errorf("filtered result name = %q, want binary_exists", got[0].Name)
+ }
+}
+
+func TestKnownCheck(t *testing.T) {
+ cfg := &config.RuntimeConfig{BrowserProvider: config.BrowserProviderChrome}
+ if !KnownCheck(cfg, "binary_exists") {
+ t.Error("binary_exists should be known for chrome provider")
+ }
+ if KnownCheck(cfg, "cdp_reachable") {
+ t.Error("cdp_reachable should not be known for chrome provider")
+ }
+ if KnownCheck(cfg, "nonsense") {
+ t.Error("unknown check name should report false")
+ }
+ cloak := &config.RuntimeConfig{BrowserProvider: config.BrowserProviderCloak}
+ if !KnownCheck(cloak, "cdp_reachable") {
+ t.Error("cdp_reachable should be known for cloak provider")
+ }
+}
+
+func TestBinaryExists_MissingFile(t *testing.T) {
+ cfg := &config.RuntimeConfig{ChromeBinary: filepath.Join(t.TempDir(), "nope")}
+ r := checkBinaryExists(context.Background(), cfg)
+ if r.Status != StatusFail {
+ t.Fatalf("status = %v, want fail (err=%v)", r.Status, r.Err)
+ }
+}
+
+func TestBinaryExists_FoundFile(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "fake-chrome")
+ if err := os.WriteFile(path, []byte("#!/bin/sh\necho hi\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ cfg := &config.RuntimeConfig{ChromeBinary: path}
+ r := checkBinaryExists(context.Background(), cfg)
+ if r.Status != StatusPass {
+ t.Fatalf("status = %v, want pass; detail=%q err=%v", r.Status, r.Detail, r.Err)
+ }
+}
+
+func TestBinaryExecutable_NotExecutable(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("file-mode executable bit is not meaningful on Windows")
+ }
+ dir := t.TempDir()
+ path := filepath.Join(dir, "no-exec")
+ if err := os.WriteFile(path, []byte("data"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ cfg := &config.RuntimeConfig{ChromeBinary: path}
+ r := checkBinaryExecutable(context.Background(), cfg)
+ if r.Status != StatusFail {
+ t.Fatalf("status = %v, want fail", r.Status)
+ }
+}
+
+func TestBinaryExecutable_Executable(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "exec")
+ if err := os.WriteFile(path, []byte("#!/bin/sh\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ cfg := &config.RuntimeConfig{ChromeBinary: path}
+ r := checkBinaryExecutable(context.Background(), cfg)
+ if r.Status != StatusPass {
+ t.Fatalf("status = %v, want pass; detail=%q", r.Status, r.Detail)
+ }
+}
+
+func TestBinaryStarts_FakeVersion(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fake binary requires unix")
+ }
+ dir := t.TempDir()
+ path := filepath.Join(dir, "fake-chrome")
+ script := "#!/bin/sh\necho 'Chromium 99.0.0.1'\n"
+ if err := os.WriteFile(path, []byte(script), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ cfg := &config.RuntimeConfig{ChromeBinary: path}
+ r := checkBinaryStarts(context.Background(), cfg)
+ if r.Status != StatusPass {
+ t.Fatalf("status = %v, want pass; detail=%q err=%v", r.Status, r.Detail, r.Err)
+ }
+ if !strings.Contains(r.Detail, "Chromium 99") {
+ t.Errorf("expected version line in detail, got %q", r.Detail)
+ }
+}
+
+func TestBinaryStarts_NonZeroExit(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fake binary requires unix")
+ }
+ dir := t.TempDir()
+ path := filepath.Join(dir, "fake-chrome-fail")
+ if err := os.WriteFile(path, []byte("#!/bin/sh\nexit 3\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ cfg := &config.RuntimeConfig{ChromeBinary: path}
+ r := checkBinaryStarts(context.Background(), cfg)
+ if r.Status != StatusFail {
+ t.Fatalf("status = %v, want fail", r.Status)
+ }
+}
+
+func TestParseVersionLine(t *testing.T) {
+ got := parseVersionLine("\n\nGoogle Chrome 146.0.7680.177\nextra\n")
+ if got != "Google Chrome 146.0.7680.177" {
+ t.Errorf("parseVersionLine = %q", got)
+ }
+}
+
+func TestFontsCheck_SkipsOnNonLinux(t *testing.T) {
+ prev := HostOS
+ defer func() { HostOS = prev }()
+ HostOS = func() string { return "darwin" }
+ cfg := &config.RuntimeConfig{Cloak: config.CloakBrowserRuntimeConfig{Platform: "windows"}}
+ r := checkLinuxFontsPresent(context.Background(), cfg)
+ if r.Status != StatusSkip {
+ t.Fatalf("status = %v, want skip", r.Status)
+ }
+}
+
+func TestFontsCheck_SkipsWhenPlatformNotWindows(t *testing.T) {
+ prev := HostOS
+ defer func() { HostOS = prev }()
+ HostOS = func() string { return "linux" }
+ cfg := &config.RuntimeConfig{Cloak: config.CloakBrowserRuntimeConfig{Platform: "macos"}}
+ r := checkLinuxFontsPresent(context.Background(), cfg)
+ if r.Status != StatusSkip {
+ t.Fatalf("status = %v, want skip", r.Status)
+ }
+}
+
+func TestBuildCloakFingerprintArgs(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ BrowserProvider: config.BrowserProviderCloak,
+ Cloak: config.CloakBrowserRuntimeConfig{
+ FingerprintSeed: "seed-1",
+ Platform: "windows",
+ Timezone: "Europe/London",
+ Locale: "en-GB",
+ WebRTCIP: "1.2.3.4",
+ },
+ }
+ args := bridgeruntime.CloakBrowserFlagArgs(cfg)
+ want := []string{
+ "--fingerprint=seed-1",
+ "--fingerprint-platform=windows",
+ "--fingerprint-locale=en-GB",
+ "--fingerprint-timezone=Europe/London",
+ "--fingerprint-webrtc-ip=1.2.3.4",
+ }
+ if len(args) != len(want) {
+ t.Fatalf("args = %v, want %v", args, want)
+ }
+ for i, a := range args {
+ if a != want[i] {
+ t.Errorf("args[%d] = %q, want %q", i, a, want[i])
+ }
+ }
+}
+
+func TestBuildCloakFingerprintArgs_Empty(t *testing.T) {
+ cfg := &config.RuntimeConfig{}
+ if got := bridgeruntime.CloakBrowserFlagArgs(cfg); len(got) != 0 {
+ t.Fatalf("expected no args, got %v", got)
+ }
+}
+
+func TestWriteText_FormatsResults(t *testing.T) {
+ results := []CheckResult{
+ {Name: "binary_exists", Status: StatusPass, Detail: "/opt/chrome", Duration: 52 * time.Millisecond},
+ {Name: "binary_starts", Status: StatusFail, Detail: "boom", Duration: 1500 * time.Millisecond, Err: errors.New("boom")},
+ {Name: "linux_fonts_present", Status: StatusSkip, Detail: "not linux", Duration: time.Microsecond},
+ }
+ var buf bytes.Buffer
+ WriteText(&buf, "cloak", "", results)
+ out := buf.String()
+ if !strings.Contains(out, "pinchtab doctor (provider=cloak)") {
+ t.Errorf("missing header in output:\n%s", out)
+ }
+ if !strings.Contains(out, "binary_exists") || !strings.Contains(out, "/opt/chrome") {
+ t.Errorf("missing pass row:\n%s", out)
+ }
+ if !strings.Contains(out, "1 passed, 1 failed, 1 skipped, 0 warnings.") {
+ t.Errorf("missing or wrong summary:\n%s", out)
+ }
+}
+
+func TestWriteJSON_Structure(t *testing.T) {
+ results := []CheckResult{
+ {Name: "binary_exists", Status: StatusPass, Detail: "/x", Duration: 5 * time.Millisecond},
+ {Name: "binary_starts", Status: StatusFail, Detail: "broken", Err: errors.New("broken")},
+ }
+ var buf bytes.Buffer
+ if err := WriteJSON(&buf, "cloak", "default", results); err != nil {
+ t.Fatal(err)
+ }
+ var report jsonReport
+ if err := json.Unmarshal(buf.Bytes(), &report); err != nil {
+ t.Fatalf("unmarshal: %v\nbody=%s", err, buf.String())
+ }
+ if report.Provider != "cloak" || report.Target != "default" {
+ t.Errorf("provider/target mismatch: %+v", report)
+ }
+ if len(report.Results) != 2 {
+ t.Fatalf("expected 2 results, got %d", len(report.Results))
+ }
+ if report.Results[1].ErrMsg != "broken" {
+ t.Errorf("error not propagated to JSON: %+v", report.Results[1])
+ }
+ if report.Summary.Passed != 1 || report.Summary.Failed != 1 {
+ t.Errorf("summary wrong: %+v", report.Summary)
+ }
+}
diff --git a/internal/doctor/version.go b/internal/doctor/version.go
new file mode 100644
index 00000000..77e2be9b
--- /dev/null
+++ b/internal/doctor/version.go
@@ -0,0 +1,73 @@
+package doctor
+
+import "strings"
+
+// compareSemver returns -1/0/1 comparing major.minor.patch of a and b; it is
+// lenient about "v" prefixes, build/prerelease suffixes, and non-numeric noise.
+func compareSemver(a, b string) int {
+ ap := splitDoctorVersion(a)
+ bp := splitDoctorVersion(b)
+ for i := 0; i < 3; i++ {
+ switch {
+ case ap[i] < bp[i]:
+ return -1
+ case ap[i] > bp[i]:
+ return 1
+ }
+ }
+ return 0
+}
+
+func splitDoctorVersion(v string) [3]int {
+ v = strings.TrimSpace(v)
+ v = strings.TrimPrefix(v, "v")
+ v = strings.TrimPrefix(v, "V")
+ if i := strings.IndexAny(v, "-+"); i >= 0 {
+ v = v[:i]
+ }
+ parts := [3]int{}
+ segs := strings.SplitN(v, ".", 3)
+ for i, s := range segs {
+ if i >= 3 {
+ break
+ }
+ n := 0
+ for _, c := range s {
+ if c >= '0' && c <= '9' {
+ n = n*10 + int(c-'0')
+ continue
+ }
+ break
+ }
+ parts[i] = n
+ }
+ return parts
+}
+
+// extractVersionToken returns the first dotted numeric token in s, or "".
+func extractVersionToken(s string) string {
+ fields := strings.Fields(s)
+ for _, f := range fields {
+ f = strings.Trim(f, "()[],;")
+ if hasDottedDigits(f) {
+ return f
+ }
+ }
+ return ""
+}
+
+func hasDottedDigits(s string) bool {
+ sawDigit := false
+ sawDot := false
+ for _, c := range s {
+ switch {
+ case c >= '0' && c <= '9':
+ sawDigit = true
+ case c == '.':
+ sawDot = true
+ default:
+ return false
+ }
+ }
+ return sawDigit && sawDot
+}
diff --git a/internal/handlers/banner_dismiss.go b/internal/handlers/banner_dismiss.go
index 842a1b81..e31639ea 100644
--- a/internal/handlers/banner_dismiss.go
+++ b/internal/handlers/banner_dismiss.go
@@ -18,9 +18,8 @@ import (
// Permissive labels are tried first because rejection paths often gate
// further interaction behind another modal.
// 2. Phase 2 — if no button matched, hard-remove DOM nodes whose id, class,
-// or aria-label contains "cookie"/"consent", plus role=dialog modals and
-// fixed/absolute "overlay" containers. Re-enables document scrolling that
-// banners commonly lock with overflow:hidden.
+// or aria-label contains "cookie"/"consent". Re-enables document scrolling
+// that banners commonly lock with overflow:hidden.
//
// The script is wrapped in try/catch and bounded to a short timeout from the
// caller so it can never wedge a navigation response.
@@ -57,8 +56,7 @@ const bannerDismissJS = `(() => {
// Phase 2: hard-remove obvious overlay containers.
const sel = '[id*="cookie" i], [class*="cookie" i], [id*="consent" i], [class*="consent" i],' +
- '[aria-label*="cookie" i], [aria-label*="consent" i],' +
- '[class*="overlay" i], [role="dialog"], [aria-modal="true"]';
+ '[aria-label*="cookie" i], [aria-label*="consent" i]';
const removed = [];
document.querySelectorAll(sel).forEach((el) => {
if (el === document.body || el === document.documentElement) return;
diff --git a/internal/handlers/banner_dismiss_test.go b/internal/handlers/banner_dismiss_test.go
index e60a2b0f..8cdd84bb 100644
--- a/internal/handlers/banner_dismiss_test.go
+++ b/internal/handlers/banner_dismiss_test.go
@@ -3,6 +3,7 @@ package handlers
import (
"context"
"net/http/httptest"
+ "strings"
"testing"
)
@@ -38,3 +39,28 @@ func TestDismissBannersDisabledIsNoop(t *testing.T) {
h.dismissBanners(context.Background(), "tab", false)
h.dismissBanners(context.Background(), "", true)
}
+
+func TestBannerDismissScriptDoesNotHardRemoveGenericDialogsOrOverlays(t *testing.T) {
+ for _, forbidden := range []string{
+ `[role="dialog"]`,
+ `[aria-modal="true"]`,
+ `[class*="overlay" i]`,
+ } {
+ if strings.Contains(bannerDismissJS, forbidden) {
+ t.Fatalf("banner dismiss script must not hard-remove generic selector %s", forbidden)
+ }
+ }
+}
+
+func TestBannerDismissScriptStillTargetsCookieConsentContainers(t *testing.T) {
+ for _, want := range []string{
+ `[id*="cookie" i]`,
+ `[class*="cookie" i]`,
+ `[id*="consent" i]`,
+ `[class*="consent" i]`,
+ } {
+ if !strings.Contains(bannerDismissJS, want) {
+ t.Fatalf("banner dismiss script missing cookie/consent selector %s", want)
+ }
+ }
+}
diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.go
index 66413589..50d48fb0 100644
--- a/internal/handlers/navigation.go
+++ b/internal/handlers/navigation.go
@@ -16,6 +16,7 @@ import (
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/engine"
"github.com/pinchtab/pinchtab/internal/httpx"
)
@@ -63,6 +64,7 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
WaitFor string `json:"waitFor"`
WaitSelector string `json:"waitSelector"`
DismissBanners bool `json:"dismissBanners"`
+ BrowserTarget string `json:"browserTarget,omitempty"`
}
if r.Method == http.MethodGet {
@@ -73,6 +75,7 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
req.WaitFor = q.Get("waitFor")
req.WaitSelector = q.Get("waitSelector")
req.DismissBanners = strings.EqualFold(q.Get("dismissBanners"), "true") || q.Get("dismissBanners") == "1"
+ req.BrowserTarget = q.Get("browserTarget")
if v := q.Get("waitTitle"); v != "" {
if n, err := strconv.ParseFloat(v, 64); err == nil {
req.WaitTitle = n
@@ -90,6 +93,29 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
}
}
+ requestedTarget, err := h.resolveNavigateBrowserTarget(req.BrowserTarget)
+ if err != nil {
+ httpx.Error(w, http.StatusBadRequest, err)
+ return
+ }
+ tabID := strings.TrimSpace(req.TabID)
+ if requestedTarget != "" && tabID != "" && h.Orchestrator != nil {
+ if inst, ok := h.Orchestrator.FindInstanceByTab(tabID); ok && inst != nil {
+ if inst.BrowserTarget != "" && inst.BrowserTarget != requestedTarget {
+ httpx.ErrorCode(w, http.StatusConflict, "browser_target_conflict",
+ fmt.Sprintf("tab %q is owned by instance with browserTarget %q; cannot navigate with browserTarget %q",
+ tabID, inst.BrowserTarget, requestedTarget),
+ false, map[string]any{
+ "tabId": tabID,
+ "instanceTarget": inst.BrowserTarget,
+ "requestedTarget": requestedTarget,
+ "instanceProvider": inst.BrowserProvider,
+ })
+ return
+ }
+ }
+ }
+
if err := validateNavigateURL(req.URL); err != nil {
httpx.Error(w, 400, err)
return
@@ -307,6 +333,21 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
httpx.JSON(w, 200, map[string]any{"tabId": resolvedTabID, "url": navURL, "title": title})
}
+func (h *Handlers) resolveNavigateBrowserTarget(raw string) (string, error) {
+ target := strings.TrimSpace(raw)
+ if target == "" {
+ return "", nil
+ }
+ if h != nil && h.Config != nil && len(h.Config.Targets) > 0 {
+ resolved, err := config.ResolveExplicitBrowserTarget(h.Config, target)
+ if err != nil {
+ return "", err
+ }
+ return resolved.Name, nil
+ }
+ return target, nil
+}
+
type navigateChromeOptions struct {
URL string
WaitFor string
diff --git a/internal/handlers/navigation_browsertarget_test.go b/internal/handlers/navigation_browsertarget_test.go
new file mode 100644
index 00000000..8154a40f
--- /dev/null
+++ b/internal/handlers/navigation_browsertarget_test.go
@@ -0,0 +1,154 @@
+package handlers
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+// fakeOrchestrator stubs bridge.OrchestratorService; only FindInstanceByTab
+// is wired, the rest are no-ops.
+type fakeOrchestrator struct {
+ tabs map[string]*bridge.Instance
+ lookup int
+}
+
+func (f *fakeOrchestrator) RegisterHandlers(mux *http.ServeMux) {}
+func (f *fakeOrchestrator) Launch(name, port string, headless bool, extensionPaths []string) (*bridge.Instance, error) {
+ return nil, nil
+}
+func (f *fakeOrchestrator) Stop(id string) error { return nil }
+func (f *fakeOrchestrator) StopProfile(name string) error { return nil }
+func (f *fakeOrchestrator) List() []bridge.Instance { return nil }
+func (f *fakeOrchestrator) Logs(id string) (string, error) { return "", nil }
+func (f *fakeOrchestrator) FirstRunningURL() string { return "" }
+func (f *fakeOrchestrator) AllTabs() []bridge.InstanceTab { return nil }
+func (f *fakeOrchestrator) FindInstanceByTab(tabID string) (*bridge.Instance, bool) {
+ f.lookup++
+ inst, ok := f.tabs[tabID]
+ if !ok {
+ return nil, false
+ }
+ return inst, true
+}
+func (f *fakeOrchestrator) ScreencastURL(instanceID, tabID string) string { return "" }
+func (f *fakeOrchestrator) Shutdown() {}
+func (f *fakeOrchestrator) ForceShutdown() {}
+
+func newOrchWithTab(tabID string, inst *bridge.Instance) *fakeOrchestrator {
+ return &fakeOrchestrator{tabs: map[string]*bridge.Instance{tabID: inst}}
+}
+
+func decodeErrorCode(body string) string {
+ var payload struct {
+ Code string `json:"code"`
+ }
+ _ = json.Unmarshal([]byte(body), &payload)
+ return payload.Code
+}
+
+func TestHandleNavigate_BrowserTargetMatchingTab_TrimsAndResolves(t *testing.T) {
+ orch := newOrchWithTab("tab1", &bridge.Instance{ID: "inst1", BrowserTarget: "chrome-default", BrowserProvider: "chrome"})
+ h := New(&mockBridge{}, &config.RuntimeConfig{
+ DefaultTarget: "chrome-default",
+ Targets: config.BrowserTargetsConfig{
+ "chrome-default": {Provider: config.BrowserProviderChrome},
+ "cloak-default": {Provider: config.BrowserProviderCloak, Binary: "/opt/cloakbrowser/chrome"},
+ },
+ }, nil, nil, orch)
+
+ body := []byte(`{"tabId":"tab1","url":"https://example.com","browserTarget":" chrome-default "}`)
+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))
+ w := httptest.NewRecorder()
+ h.HandleNavigate(w, req)
+
+ if w.Code == http.StatusConflict {
+ t.Fatalf("expected matching target NOT to 409, got 409 body=%s", w.Body.String())
+ }
+ if orch.lookup != 1 {
+ t.Fatalf("expected FindInstanceByTab to be called once, got %d", orch.lookup)
+ }
+}
+
+func TestHandleNavigate_BrowserTargetConflict_409(t *testing.T) {
+ orch := newOrchWithTab("tab1", &bridge.Instance{ID: "inst1", BrowserTarget: "chrome-default", BrowserProvider: "chrome"})
+ h := New(&mockBridge{}, &config.RuntimeConfig{
+ DefaultTarget: "chrome-default",
+ Targets: config.BrowserTargetsConfig{
+ "chrome-default": {Provider: config.BrowserProviderChrome},
+ "cloak-default": {Provider: config.BrowserProviderCloak, Binary: "/opt/cloakbrowser/chrome"},
+ },
+ }, nil, nil, orch)
+
+ body := []byte(`{"tabId":"tab1","url":"https://example.com","browserTarget":" cloak-default "}`)
+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))
+ w := httptest.NewRecorder()
+ h.HandleNavigate(w, req)
+
+ if w.Code != http.StatusConflict {
+ t.Fatalf("expected 409 conflict, got %d body=%s", w.Code, w.Body.String())
+ }
+ if code := decodeErrorCode(w.Body.String()); code != "browser_target_conflict" {
+ t.Fatalf("expected error code browser_target_conflict, got %q body=%s", code, w.Body.String())
+ }
+}
+
+func TestHandleNavigate_BrowserTargetUnknownTab_FallsThrough(t *testing.T) {
+ orch := &fakeOrchestrator{tabs: map[string]*bridge.Instance{}}
+ m := &mockBridge{failTab: true}
+ h := New(m, &config.RuntimeConfig{}, nil, nil, orch)
+
+ body := []byte(`{"tabId":"missing","url":"https://example.com","browserTarget":"cloak-default"}`)
+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))
+ w := httptest.NewRecorder()
+ h.HandleNavigate(w, req)
+
+ if w.Code == http.StatusConflict {
+ t.Fatalf("expected unknown tab to fall through (not 409), got 409 body=%s", w.Body.String())
+ }
+ if orch.lookup != 1 {
+ t.Fatalf("expected FindInstanceByTab to be consulted once, got %d", orch.lookup)
+ }
+ // Code shouldn't be browser_target_conflict regardless of downstream outcome.
+ if strings.Contains(w.Body.String(), "browser_target_conflict") {
+ t.Fatalf("unexpected browser_target_conflict in response body: %s", w.Body.String())
+ }
+}
+
+func TestHandleNavigate_BrowserTargetLegacyInstance_NoConflict(t *testing.T) {
+ // Legacy instance: BrowserTarget empty.
+ orch := newOrchWithTab("tab1", &bridge.Instance{ID: "inst1"})
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, orch)
+
+ body := []byte(`{"tabId":"tab1","url":"https://example.com","browserTarget":"cloak-default"}`)
+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))
+ w := httptest.NewRecorder()
+ h.HandleNavigate(w, req)
+
+ if w.Code == http.StatusConflict {
+ t.Fatalf("expected legacy instance to skip conflict check, got 409 body=%s", w.Body.String())
+ }
+}
+
+func TestHandleNavigate_BrowserTargetNoTabID_Accepted(t *testing.T) {
+ orch := &fakeOrchestrator{tabs: map[string]*bridge.Instance{}}
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, orch)
+
+ body := []byte(`{"url":"https://example.com","browserTarget":"cloak-default"}`)
+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))
+ w := httptest.NewRecorder()
+ h.HandleNavigate(w, req)
+
+ if w.Code == http.StatusConflict {
+ t.Fatalf("expected no-tabId + target to be accepted, got 409 body=%s", w.Body.String())
+ }
+ if orch.lookup != 0 {
+ t.Fatalf("expected FindInstanceByTab NOT to be called without tabId, got %d", orch.lookup)
+ }
+}
diff --git a/internal/handlers/navigation_policy.go b/internal/handlers/navigation_policy.go
index b4d53137..c3de5556 100644
--- a/internal/handlers/navigation_policy.go
+++ b/internal/handlers/navigation_policy.go
@@ -141,32 +141,30 @@ func validateNavigateTarget(raw string, allowExplicitInternal bool, trustedResol
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
- if _, err := netguard.ResolveAndValidatePublicIPs(ctx, host); err != nil {
- if errors.Is(err, netguard.ErrResolveHost) {
- return nil, fmt.Errorf("could not resolve navigation host")
- }
+ ips, err := resolveNavigateHostAddrs(ctx, host)
+ if err != nil {
+ return nil, fmt.Errorf("could not resolve navigation host")
+ }
+ if err := validateResolvedNavigatePublicIPs(ips); err != nil {
if errors.Is(err, netguard.ErrPrivateInternalIP) {
if allowExplicitInternal {
- return &validatedNavigateTarget{allowInternal: true}, nil
+ return &validatedNavigateTarget{trustedResolvedIP: ips}, nil
}
- if len(trustedResolveCIDRs) > 0 {
- ips, err2 := netguard.ResolveAndValidateIPsWithTrustedCIDRs(ctx, host, trustedResolveCIDRs)
- if err2 == nil {
- cidrs := make([]string, len(trustedResolveCIDRs))
- for i, c := range trustedResolveCIDRs {
- cidrs[i] = c.String()
- }
- addrs := make([]string, len(ips))
- for i, a := range ips {
- addrs[i] = a.String()
- }
- slog.Info("navigate: trusted resolve CIDR override",
- "host", host,
- "resolvedIPs", addrs,
- "trustedCIDRs", cidrs,
- )
- return &validatedNavigateTarget{trustedResolvedIP: ips}, nil
+ if len(trustedResolveCIDRs) > 0 && validateResolvedNavigateIPsWithTrustedCIDRs(ips, trustedResolveCIDRs) == nil {
+ cidrs := make([]string, len(trustedResolveCIDRs))
+ for i, c := range trustedResolveCIDRs {
+ cidrs[i] = c.String()
}
+ addrs := make([]string, len(ips))
+ for i, a := range ips {
+ addrs[i] = a.String()
+ }
+ slog.Info("navigate: trusted resolve CIDR override",
+ "host", host,
+ "resolvedIPs", addrs,
+ "trustedCIDRs", cidrs,
+ )
+ return &validatedNavigateTarget{trustedResolvedIP: ips}, nil
}
return nil, fmt.Errorf("navigation target resolves to blocked private/internal IP")
}
@@ -175,6 +173,72 @@ func validateNavigateTarget(raw string, allowExplicitInternal bool, trustedResol
return &validatedNavigateTarget{}, nil
}
+func validateResolvedNavigatePublicIPs(ips []netip.Addr) error {
+ _, err := netguard.ValidateResolvedPublicAddrs(ips)
+ return err
+}
+
+func validateResolvedNavigateIPsWithTrustedCIDRs(ips []netip.Addr, trusted []*net.IPNet) error {
+ if len(ips) == 0 {
+ return netguard.ErrResolveHost
+ }
+ for _, addr := range ips {
+ ip := net.ParseIP(addr.String())
+ if err := netguard.ValidatePublicIP(ip); err != nil {
+ if !ipInCIDRs(ip, trusted) {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+func ipInCIDRs(ip net.IP, cidrs []*net.IPNet) bool {
+ for _, cidr := range cidrs {
+ if cidr.Contains(ip) {
+ return true
+ }
+ }
+ return false
+}
+
+func resolveNavigateHostAddrs(ctx context.Context, host string) ([]netip.Addr, error) {
+ host = netguard.NormalizeHost(host)
+ if host == "" {
+ return nil, netguard.ErrResolveHost
+ }
+ if ip := net.ParseIP(host); ip != nil {
+ addr, ok := netip.AddrFromSlice(ip)
+ if !ok {
+ return nil, netguard.ErrResolveHost
+ }
+ return []netip.Addr{addr.Unmap()}, nil
+ }
+
+ ips, err := netguard.ResolveHostIPs(ctx, "ip", host)
+ if err != nil || len(ips) == 0 {
+ return nil, netguard.ErrResolveHost
+ }
+ seen := make(map[netip.Addr]struct{}, len(ips))
+ out := make([]netip.Addr, 0, len(ips))
+ for _, ip := range ips {
+ addr, ok := netip.AddrFromSlice(ip)
+ if !ok {
+ return nil, netguard.ErrResolveHost
+ }
+ addr = addr.Unmap()
+ if _, ok := seen[addr]; ok {
+ continue
+ }
+ seen[addr] = struct{}{}
+ out = append(out, addr)
+ }
+ if len(out) == 0 {
+ return nil, netguard.ErrResolveHost
+ }
+ return out, nil
+}
+
func extractNavigateHost(raw string) (string, bool) {
parsed, err := url.Parse(strings.TrimSpace(raw))
if err != nil {
diff --git a/internal/handlers/navigation_test.go b/internal/handlers/navigation_test.go
index b9aca214..924a3bc9 100644
--- a/internal/handlers/navigation_test.go
+++ b/internal/handlers/navigation_test.go
@@ -124,6 +124,46 @@ func TestValidateNavigateTarget_RejectsResolvedPrivateIP(t *testing.T) {
}
}
+func TestValidateNavigateTarget_AllowsDualStackPublicResolution(t *testing.T) {
+ stubNavigateHostResolution(t, func(context.Context, string, string) ([]net.IP, error) {
+ return []net.IP{
+ net.ParseIP("2606:2800:220:1:248:1893:25c8:1946"),
+ net.ParseIP("93.184.216.34"),
+ }, nil
+ })
+
+ if _, err := validateNavigateTarget("https://dual.example/app", false, nil); err != nil {
+ t.Fatalf("validateNavigateTarget should allow public dual-stack resolution: %v", err)
+ }
+}
+
+func TestValidateNavigateTarget_RejectsMixedPublicPrivateDualStackResolution(t *testing.T) {
+ tests := []struct {
+ name string
+ ips []net.IP
+ }{
+ {
+ name: "private-v6-first",
+ ips: []net.IP{net.ParseIP("fd00::10"), net.ParseIP("93.184.216.34")},
+ },
+ {
+ name: "public-v4-first",
+ ips: []net.IP{net.ParseIP("93.184.216.34"), net.ParseIP("fd00::10")},
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ stubNavigateHostResolution(t, func(context.Context, string, string) ([]net.IP, error) {
+ return tt.ips, nil
+ })
+
+ if _, err := validateNavigateTarget("https://mixed.example/app", false, nil); err == nil {
+ t.Fatal("validateNavigateTarget should reject mixed public/private DNS answers")
+ }
+ })
+ }
+}
+
func TestValidateNavigateTarget_AllowsResolvedPrivateIPWhenExplicitlyAllowlisted(t *testing.T) {
stubNavigateHostResolution(t, func(context.Context, string, string) ([]net.IP, error) {
return []net.IP{net.ParseIP("172.18.0.5")}, nil
@@ -133,8 +173,14 @@ func TestValidateNavigateTarget_AllowsResolvedPrivateIPWhenExplicitlyAllowlisted
if err != nil {
t.Fatalf("validateNavigateTarget should allow explicitly allowlisted private targets: %v", err)
}
- if target == nil || !target.allowInternal {
- t.Fatal("validateNavigateTarget should mark explicitly allowlisted private targets as allowed")
+ if target == nil {
+ t.Fatal("validateNavigateTarget returned nil target")
+ }
+ if target.allowInternal {
+ t.Fatal("allowlisted private targets should not disable redirect/internal-IP runtime guards")
+ }
+ if len(target.trustedResolvedIP) != 1 || target.trustedResolvedIP[0] != netip.MustParseAddr("172.18.0.5") {
+ t.Fatalf("trustedResolvedIP = %v, want [172.18.0.5]", target.trustedResolvedIP)
}
}
diff --git a/internal/mcp/handlers_navigation.go b/internal/mcp/handlers_navigation.go
index 3fa3473a..3d5633d6 100644
--- a/internal/mcp/handlers_navigation.go
+++ b/internal/mcp/handlers_navigation.go
@@ -26,6 +26,10 @@ func handleNavigate(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.
if tabID != "" {
payload["tabId"] = tabID
}
+ browserTarget := optString(r, "browserTarget")
+ if browserTarget != "" {
+ payload["browserTarget"] = browserTarget
+ }
body, code, err := c.Post(ctx, "/navigate", payload)
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
@@ -41,6 +45,11 @@ func handleNavigate(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.
q.Set("format", "compact")
if tabID != "" {
q.Set("tabId", tabID)
+ } else if returnedTabID := responseStringField(body, "tabId"); returnedTabID != "" {
+ q.Set("tabId", returnedTabID)
+ }
+ if browserTarget != "" {
+ q.Set("browserTarget", browserTarget)
}
snapBody, _, snapErr := c.Get(ctx, "/snapshot", q)
if snapErr == nil {
@@ -52,6 +61,15 @@ func handleNavigate(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.
}
}
+func responseStringField(body []byte, field string) string {
+ var payload map[string]any
+ if err := json.Unmarshal(body, &payload); err != nil {
+ return ""
+ }
+ value, _ := payload[field].(string)
+ return strings.TrimSpace(value)
+}
+
func handleSnapshot(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
q := url.Values{}
diff --git a/internal/mcp/handlers_navigation_test.go b/internal/mcp/handlers_navigation_test.go
index e5e48a42..29a92a63 100644
--- a/internal/mcp/handlers_navigation_test.go
+++ b/internal/mcp/handlers_navigation_test.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "net/url"
"strings"
"testing"
@@ -86,6 +87,79 @@ func TestHandleNavigateAnyScheme(t *testing.T) {
}
}
+func TestHandleNavigate_WithBrowserTarget(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ // When browserTarget is supplied, the forwarded payload includes it.
+ r := callTool(t, "pinchtab_navigate", map[string]any{
+ "url": "https://example.com",
+ "browserTarget": "chrome",
+ }, srv)
+
+ resp := resultJSON(t, r)
+ body, _ := resp["body"].(map[string]any)
+ if got, _ := body["browserTarget"].(string); got != "chrome" {
+ t.Errorf("browserTarget = %q, want chrome", got)
+ }
+
+ // When omitted/empty, the payload must not include the key.
+ r2 := callTool(t, "pinchtab_navigate", map[string]any{
+ "url": "https://example.com",
+ "browserTarget": "",
+ }, srv)
+
+ resp2 := resultJSON(t, r2)
+ body2, _ := resp2["body"].(map[string]any)
+ if _, ok := body2["browserTarget"]; ok {
+ t.Errorf("browserTarget should be omitted when empty, got %v", body2["browserTarget"])
+ }
+}
+
+func TestHandleNavigateSnapUsesReturnedTabAndBrowserTarget(t *testing.T) {
+ var navigateBody map[string]any
+ var snapshotQuery url.Values
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/navigate":
+ if err := json.NewDecoder(r.Body).Decode(&navigateBody); err != nil {
+ t.Errorf("decode navigate body: %v", err)
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "tabId": "tab-cloak",
+ "url": "https://example.com",
+ })
+ case "/snapshot":
+ snapshotQuery = r.URL.Query()
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "snapshot": true,
+ })
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_navigate", map[string]any{
+ "url": "https://example.com",
+ "browserTarget": "cloak",
+ "snap": true,
+ }, srv)
+ if r.IsError {
+ t.Fatalf("navigate returned error: %s", resultText(t, r))
+ }
+
+ if got, _ := navigateBody["browserTarget"].(string); got != "cloak" {
+ t.Fatalf("navigate browserTarget = %q, want cloak", got)
+ }
+ if got := snapshotQuery.Get("tabId"); got != "tab-cloak" {
+ t.Fatalf("snapshot tabId = %q, want tab-cloak; query=%v", got, snapshotQuery)
+ }
+ if got := snapshotQuery.Get("browserTarget"); got != "cloak" {
+ t.Fatalf("snapshot browserTarget = %q, want cloak; query=%v", got, snapshotQuery)
+ }
+}
+
func TestHandleSnapshot(t *testing.T) {
srv := mockPinchTab()
defer srv.Close()
diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go
index 23bf6e71..c188791b 100644
--- a/internal/mcp/tools.go
+++ b/internal/mcp/tools.go
@@ -11,6 +11,10 @@ func allTools() []mcp.Tool {
mcp.WithString("url", mcp.Required(), mcp.Description("The URL to navigate to")),
mcp.WithString("tabId", mcp.Description("Target tab ID (optional, uses current tab if empty)")),
mcp.WithBoolean("snap", mcp.Description("Return interactive compact snapshot after navigation (saves a round-trip)")),
+ mcp.WithString("browserTarget",
+ mcp.Description("Named browser target to use (e.g. 'chrome', 'cloak'). "+
+ "If a tabId is also supplied and the tab's instance was launched "+
+ "with a different target, the call returns 409 conflict.")),
),
mcp.NewTool("pinchtab_snapshot",
mcp.WithDescription("Get an accessibility tree snapshot of the current page. Use this sparingly: prefer pinchtab_find + action selectors for faster loops."),
diff --git a/internal/netguard/netguard.go b/internal/netguard/netguard.go
index 511fdb87..00c6808b 100644
--- a/internal/netguard/netguard.go
+++ b/internal/netguard/netguard.go
@@ -81,11 +81,11 @@ func ResolveAndValidatePublicIPs(ctx context.Context, host string) ([]netip.Addr
}
if ip := net.ParseIP(host); ip != nil {
- addr, err := publicAddr(ip)
- if err != nil {
- return nil, err
+ addr, ok := netip.AddrFromSlice(ip)
+ if !ok {
+ return nil, ErrPrivateInternalIP
}
- return []netip.Addr{addr}, nil
+ return ValidateResolvedPublicAddrs([]netip.Addr{addr})
}
ips, err := ResolveHostIPs(ctx, "ip", host)
@@ -93,11 +93,29 @@ func ResolveAndValidatePublicIPs(ctx context.Context, host string) ([]netip.Addr
return nil, ErrResolveHost
}
+ addrs := make([]netip.Addr, 0, len(ips))
+ for _, ip := range ips {
+ addr, ok := netip.AddrFromSlice(ip)
+ if !ok {
+ return nil, ErrPrivateInternalIP
+ }
+ addrs = append(addrs, addr)
+ }
+ return ValidateResolvedPublicAddrs(addrs)
+}
+
+func ValidateResolvedPublicAddrs(ips []netip.Addr) ([]netip.Addr, error) {
+ if len(ips) == 0 {
+ return nil, ErrResolveHost
+ }
seen := make(map[netip.Addr]struct{}, len(ips))
out := make([]netip.Addr, 0, len(ips))
- for _, ip := range ips {
- addr, err := publicAddr(ip)
- if err != nil {
+ for _, addr := range ips {
+ if !addr.IsValid() {
+ return nil, ErrPrivateInternalIP
+ }
+ addr = addr.Unmap()
+ if err := ValidatePublicIP(net.IP(addr.AsSlice())); err != nil {
return nil, err
}
if _, ok := seen[addr]; ok {
@@ -182,11 +200,3 @@ func ipInCIDRs(ip net.IP, cidrs []*net.IPNet) bool {
}
return false
}
-
-func publicAddr(ip net.IP) (netip.Addr, error) {
- if err := ValidatePublicIP(ip); err != nil {
- return netip.Addr{}, err
- }
- addr, _ := netip.AddrFromSlice(ip)
- return addr.Unmap(), nil
-}
diff --git a/internal/netguard/netguard_test.go b/internal/netguard/netguard_test.go
index 9b6c0ab5..ddda7e5a 100644
--- a/internal/netguard/netguard_test.go
+++ b/internal/netguard/netguard_test.go
@@ -72,6 +72,8 @@ func TestResolveAndValidatePublicIPs(t *testing.T) {
return []net.IP{net.ParseIP("93.184.216.34"), net.ParseIP("2606:2800:220:1:248:1893:25c8:1946")}, nil
case "mixed.example":
return []net.IP{net.ParseIP("93.184.216.34"), net.ParseIP("10.0.0.8")}, nil
+ case "mixed-private-first.example":
+ return []net.IP{net.ParseIP("10.0.0.8"), net.ParseIP("93.184.216.34")}, nil
case "dupe.example":
return []net.IP{net.ParseIP("93.184.216.34"), net.ParseIP("93.184.216.34")}, nil
default:
@@ -99,6 +101,10 @@ func TestResolveAndValidatePublicIPs(t *testing.T) {
t.Fatalf("ResolveAndValidatePublicIPs(mixed.example) error = %v, want private/internal sentinel", err)
}
+ if _, err := ResolveAndValidatePublicIPs(context.Background(), "mixed-private-first.example"); !errors.Is(err, ErrPrivateInternalIP) {
+ t.Fatalf("ResolveAndValidatePublicIPs(mixed-private-first.example) error = %v, want private/internal sentinel", err)
+ }
+
if _, err := ResolveAndValidatePublicIPs(context.Background(), "missing.example"); !errors.Is(err, ErrResolveHost) {
t.Fatalf("ResolveAndValidatePublicIPs(missing.example) error = %v, want resolve sentinel", err)
}
diff --git a/internal/orchestrator/find_instance_by_tab_test.go b/internal/orchestrator/find_instance_by_tab_test.go
new file mode 100644
index 00000000..2b78a1cd
--- /dev/null
+++ b/internal/orchestrator/find_instance_by_tab_test.go
@@ -0,0 +1,83 @@
+package orchestrator
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+)
+
+func TestFindInstanceByTab_KnownTabReturnsInstance(t *testing.T) {
+ alwaysAlive(t)
+ o := NewOrchestrator(t.TempDir())
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/tabs" {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"tabs":[{"id":"tab-1","url":"about:blank"},{"id":"tab-2","url":"https://example.com"}]}`))
+ return
+ }
+ w.WriteHeader(404)
+ }))
+ t.Cleanup(srv.Close)
+ o.client = srv.Client()
+
+ inst := &InstanceInternal{
+ Instance: bridge.Instance{
+ ID: "inst_a",
+ Status: "running",
+ URL: srv.URL,
+ BrowserTarget: "chrome-default",
+ BrowserProvider: "chrome",
+ },
+ URL: srv.URL,
+ cmd: &mockCmd{pid: 1, isAlive: true},
+ }
+ o.instances["inst_a"] = inst
+
+ got, ok := o.FindInstanceByTab("tab-2")
+ if !ok {
+ t.Fatal("expected FindInstanceByTab to return ok for known tab")
+ }
+ if got == nil || got.ID != "inst_a" {
+ t.Fatalf("expected instance inst_a, got %+v", got)
+ }
+ if got.BrowserTarget != "chrome-default" {
+ t.Fatalf("expected BrowserTarget=chrome-default, got %q", got.BrowserTarget)
+ }
+}
+
+func TestFindInstanceByTab_UnknownTabReturnsFalse(t *testing.T) {
+ alwaysAlive(t)
+ o := NewOrchestrator(t.TempDir())
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/tabs" {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"tabs":[{"id":"tab-1","url":"about:blank"}]}`))
+ return
+ }
+ w.WriteHeader(404)
+ }))
+ t.Cleanup(srv.Close)
+ o.client = srv.Client()
+
+ inst := &InstanceInternal{
+ Instance: bridge.Instance{ID: "inst_a", Status: "running", URL: srv.URL},
+ URL: srv.URL,
+ cmd: &mockCmd{pid: 1, isAlive: true},
+ }
+ o.instances["inst_a"] = inst
+
+ if got, ok := o.FindInstanceByTab("nope"); ok || got != nil {
+ t.Fatalf("expected (nil,false) for unknown tab, got (%+v,%v)", got, ok)
+ }
+}
+
+func TestFindInstanceByTab_EmptyTabID(t *testing.T) {
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{})
+ if got, ok := o.FindInstanceByTab(""); ok || got != nil {
+ t.Fatalf("expected (nil,false) for empty tabID, got (%+v,%v)", got, ok)
+ }
+}
diff --git a/internal/orchestrator/handlers_instances.go b/internal/orchestrator/handlers_instances.go
index 07e5df79..e643d8f1 100644
--- a/internal/orchestrator/handlers_instances.go
+++ b/internal/orchestrator/handlers_instances.go
@@ -2,6 +2,7 @@ package orchestrator
import (
"encoding/json"
+ "errors"
"fmt"
"net/http"
"net/url"
@@ -15,11 +16,13 @@ import (
)
type startInstanceRequest struct {
- ProfileID string `json:"profileId,omitempty"`
- Mode string `json:"mode,omitempty"`
- Port string `json:"port,omitempty"`
- ExtensionPaths []string `json:"extensionPaths,omitempty"`
- SecurityPolicy *bridge.SecurityPolicy `json:"securityPolicy,omitempty"`
+ ProfileID string `json:"profileId,omitempty"`
+ Mode string `json:"mode,omitempty"`
+ Port string `json:"port,omitempty"`
+ ExtensionPaths []string `json:"extensionPaths,omitempty"`
+ SecurityPolicy *bridge.SecurityPolicy `json:"securityPolicy,omitempty"`
+ BrowserTarget string `json:"browserTarget,omitempty"`
+ FallbackTargets []string `json:"fallbackTargets,omitempty"`
}
func (o *Orchestrator) handleGetInstance(w http.ResponseWriter, r *http.Request) {
@@ -266,13 +269,14 @@ func (o *Orchestrator) startInstanceWithRequest(w http.ResponseWriter, r *http.R
headless := req.Mode != "headed"
- inst, err := o.LaunchWithOptions(profileName, req.Port, headless, LaunchOptions{
+ opts := LaunchOptions{
ExtensionPaths: req.ExtensionPaths,
SecurityPolicy: req.SecurityPolicy,
- })
+ }
+
+ inst, err := o.LaunchWithTargetSelection(profileName, req.Port, headless, req.BrowserTarget, req.FallbackTargets, opts)
if err != nil {
- statusCode := classifyLaunchError(err)
- httpx.Error(w, statusCode, err)
+ writeLaunchError(w, err)
return
}
@@ -280,6 +284,30 @@ func (o *Orchestrator) startInstanceWithRequest(w http.ResponseWriter, r *http.R
httpx.JSON(w, 201, inst)
}
+// writeLaunchError maps launch / fallback errors to 400 (unknown target), 502 (exhaustion), or the legacy classifier.
+func writeLaunchError(w http.ResponseWriter, err error) {
+ var unknown *UnknownBrowserTargetError
+ if errors.As(err, &unknown) {
+ httpx.Error(w, http.StatusBadRequest, err)
+ return
+ }
+ var exhausted *FallbackExhaustedError
+ if errors.As(err, &exhausted) {
+ attempts := make([]map[string]string, 0, len(exhausted.Attempts))
+ for _, a := range exhausted.Attempts {
+ attempts = append(attempts, map[string]string{
+ "target": a.Target,
+ "reason": string(a.Reason),
+ })
+ }
+ httpx.ErrorCode(w, http.StatusBadGateway, "browser_target_unavailable", err.Error(), true, map[string]any{
+ "attempts": attempts,
+ })
+ return
+ }
+ httpx.Error(w, classifyLaunchError(err), err)
+}
+
func validateStartInstanceSecurityPolicy(policy *bridge.SecurityPolicy) error {
if policy == nil {
return nil
@@ -337,8 +365,10 @@ func (o *Orchestrator) handleInstanceTabs(w http.ResponseWriter, r *http.Request
func (o *Orchestrator) handleAttachInstance(w http.ResponseWriter, r *http.Request) {
var req struct {
- CdpURL string `json:"cdpUrl"`
- Name string `json:"name,omitempty"`
+ CdpURL string `json:"cdpUrl"`
+ Name string `json:"name,omitempty"`
+ Provider string `json:"provider,omitempty"`
+ BrowserTarget string `json:"browserTarget,omitempty"`
}
if err := httpx.DecodeJSONBody(w, r, 0, &req); err != nil {
@@ -350,6 +380,14 @@ func (o *Orchestrator) handleAttachInstance(w http.ResponseWriter, r *http.Reque
httpx.Error(w, 400, fmt.Errorf("cdpUrl is required"))
return
}
+ attachOpts, err := o.resolveAttachOptions(AttachOptions{
+ BrowserTarget: req.BrowserTarget,
+ BrowserProvider: req.Provider,
+ }, config.BrowserProviderChrome)
+ if err != nil {
+ httpx.Error(w, 400, err)
+ return
+ }
// Validate attach is enabled and URL is allowed
if err := o.validateAttachURL(req.CdpURL); err != nil {
@@ -363,21 +401,22 @@ func (o *Orchestrator) handleAttachInstance(w http.ResponseWriter, r *http.Reque
name = fmt.Sprintf("attached-%d", time.Now().UnixNano())
}
- inst, err := o.Attach(name, req.CdpURL)
+ inst, err := o.AttachWithOptions(name, req.CdpURL, attachOpts)
if err != nil {
httpx.Error(w, classifyLaunchError(err), err)
return
}
- authn.AuditLog(r, "instance.attached", "instanceId", inst.ID, "instanceName", inst.ProfileName, "attachType", "cdp")
+ authn.AuditLog(r, "instance.attached", "instanceId", inst.ID, "instanceName", inst.ProfileName, "attachType", "cdp-bridge")
httpx.JSON(w, 201, inst)
}
func (o *Orchestrator) handleAttachBridge(w http.ResponseWriter, r *http.Request) {
var req struct {
- BaseURL string `json:"baseUrl"`
- Name string `json:"name,omitempty"`
- Token string `json:"token,omitempty"`
+ BaseURL string `json:"baseUrl"`
+ Name string `json:"name,omitempty"`
+ Token string `json:"token,omitempty"`
+ BrowserTarget string `json:"browserTarget,omitempty"`
}
if err := httpx.DecodeJSONBody(w, r, 0, &req); err != nil {
@@ -388,6 +427,11 @@ func (o *Orchestrator) handleAttachBridge(w http.ResponseWriter, r *http.Request
httpx.Error(w, 400, fmt.Errorf("baseUrl is required"))
return
}
+ attachOpts, err := o.resolveAttachOptions(AttachOptions{BrowserTarget: req.BrowserTarget}, "")
+ if err != nil {
+ httpx.Error(w, 400, err)
+ return
+ }
if err := o.validateAttachURL(req.BaseURL); err != nil {
httpx.Error(w, 403, err)
return
@@ -402,7 +446,7 @@ func (o *Orchestrator) handleAttachBridge(w http.ResponseWriter, r *http.Request
name = fmt.Sprintf("bridge-%d", time.Now().UnixNano())
}
- inst, created, err := o.AttachBridge(name, req.BaseURL, req.Token)
+ inst, created, err := o.AttachBridgeWithOptions(name, req.BaseURL, req.Token, attachOpts)
if err != nil {
httpx.Error(w, classifyLaunchError(err), err)
return
@@ -470,14 +514,15 @@ func (o *Orchestrator) validateAttachURL(rawURL string) error {
}
if parsed.Scheme == "http" || parsed.Scheme == "https" {
- if parsed.Path != "" && parsed.Path != "/" {
- return fmt.Errorf("bridge baseUrl must not include a path")
+ // CDP attach allows /json/version; attach-bridge requires bare origin.
+ if parsed.Path != "" && parsed.Path != "/" && parsed.Path != "/json/version" {
+ return fmt.Errorf("HTTP attach URL must be the bare origin or end with /json/version")
}
if parsed.User != nil {
- return fmt.Errorf("bridge baseUrl must not include userinfo")
+ return fmt.Errorf("attach URL must not include userinfo")
}
if parsed.RawQuery != "" || parsed.Fragment != "" {
- return fmt.Errorf("bridge baseUrl must not include query or fragment")
+ return fmt.Errorf("attach URL must not include query or fragment")
}
}
diff --git a/internal/orchestrator/handlers_instances_test.go b/internal/orchestrator/handlers_instances_test.go
index 900f63fe..03df8f06 100644
--- a/internal/orchestrator/handlers_instances_test.go
+++ b/internal/orchestrator/handlers_instances_test.go
@@ -2,6 +2,7 @@ package orchestrator
import (
"encoding/json"
+ "fmt"
"net/http"
"net/http/httptest"
"os"
@@ -184,3 +185,556 @@ func TestHandleStartInstance_RejectsInvalidSecurityPolicyOverride(t *testing.T)
t.Fatalf("body = %q, want securityPolicy validation message", w.Body.String())
}
}
+
+func setupTargetsOrchestrator(t *testing.T) *Orchestrator {
+ t.Helper()
+ old := processAliveFunc
+ processAliveFunc = func(pid int) bool { return pid > 0 }
+ t.Cleanup(func() { processAliveFunc = old })
+ stubPortAvailability(t, func(int) bool { return true })
+
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ DefaultTarget: "chrome-local",
+ Targets: config.BrowserTargetsConfig{
+ "chrome-local": {Provider: config.BrowserProviderChrome},
+ "cloak-1": {Provider: config.BrowserProviderCloak},
+ },
+ })
+ return o
+}
+
+func TestHandleStartInstance_LegacyConfigEmptyBody_NoTargetFields(t *testing.T) {
+ old := processAliveFunc
+ processAliveFunc = func(pid int) bool { return pid > 0 }
+ defer func() { processAliveFunc = old }()
+ stubPortAvailability(t, func(int) bool { return true })
+
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+
+ req := httptest.NewRequest(http.MethodPost, "/instances/start", strings.NewReader(``))
+ req.ContentLength = 0
+ w := httptest.NewRecorder()
+
+ o.handleStartInstance(w, req)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, want %d body=%s", w.Code, http.StatusCreated, w.Body.String())
+ }
+ body := w.Body.String()
+ if strings.Contains(body, `"browserTarget"`) || strings.Contains(body, `"browserProvider"`) {
+ t.Fatalf("legacy config must not emit target/provider keys; body=%s", body)
+ }
+}
+
+func TestHandleStartInstance_TargetsConfigValid_EchoesValues(t *testing.T) {
+ o := setupTargetsOrchestrator(t)
+
+ req := httptest.NewRequest(http.MethodPost, "/instances/start", strings.NewReader(`{"browserTarget":"cloak-1"}`))
+ w := httptest.NewRecorder()
+
+ o.handleStartInstance(w, req)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, want %d body=%s", w.Code, http.StatusCreated, w.Body.String())
+ }
+ var inst bridge.Instance
+ if err := json.NewDecoder(w.Body).Decode(&inst); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if inst.BrowserTarget != "cloak-1" {
+ t.Fatalf("BrowserTarget = %q, want cloak-1", inst.BrowserTarget)
+ }
+ if inst.BrowserProvider != config.BrowserProviderCloak {
+ t.Fatalf("BrowserProvider = %q, want cloak", inst.BrowserProvider)
+ }
+}
+
+func TestHandleStartInstance_TargetsConfigBadTarget_Rejects400(t *testing.T) {
+ o := setupTargetsOrchestrator(t)
+
+ req := httptest.NewRequest(http.MethodPost, "/instances/start", strings.NewReader(`{"browserTarget":"ghost"}`))
+ w := httptest.NewRecorder()
+
+ o.handleStartInstance(w, req)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400 body=%s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "not found") {
+ t.Fatalf("body = %q, want 'not found'", w.Body.String())
+ }
+}
+
+func TestHandleLaunchByName_LegacyConfigEmptyBody_NoTargetFields(t *testing.T) {
+ old := processAliveFunc
+ processAliveFunc = func(pid int) bool { return pid > 0 }
+ defer func() { processAliveFunc = old }()
+ stubPortAvailability(t, func(int) bool { return true })
+
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+
+ req := httptest.NewRequest(http.MethodPost, "/instances/launch", strings.NewReader(``))
+ req.ContentLength = 0
+ w := httptest.NewRecorder()
+
+ o.handleLaunchByName(w, req)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, want %d body=%s", w.Code, http.StatusCreated, w.Body.String())
+ }
+ body := w.Body.String()
+ if strings.Contains(body, `"browserTarget"`) || strings.Contains(body, `"browserProvider"`) {
+ t.Fatalf("legacy config must not emit target/provider keys; body=%s", body)
+ }
+}
+
+func TestHandleLaunchByName_TargetsConfigValid_EchoesValues(t *testing.T) {
+ o := setupTargetsOrchestrator(t)
+
+ req := httptest.NewRequest(http.MethodPost, "/instances/launch", strings.NewReader(`{"browserTarget":"chrome-local"}`))
+ w := httptest.NewRecorder()
+
+ o.handleLaunchByName(w, req)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, want %d body=%s", w.Code, http.StatusCreated, w.Body.String())
+ }
+ var inst bridge.Instance
+ if err := json.NewDecoder(w.Body).Decode(&inst); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if inst.BrowserTarget != "chrome-local" {
+ t.Fatalf("BrowserTarget = %q, want chrome-local", inst.BrowserTarget)
+ }
+ if inst.BrowserProvider != config.BrowserProviderChrome {
+ t.Fatalf("BrowserProvider = %q, want chrome", inst.BrowserProvider)
+ }
+}
+
+func TestHandleLaunchByName_TargetsConfigBadTarget_Rejects400(t *testing.T) {
+ o := setupTargetsOrchestrator(t)
+
+ req := httptest.NewRequest(http.MethodPost, "/instances/launch", strings.NewReader(`{"browserTarget":"ghost"}`))
+ w := httptest.NewRecorder()
+
+ o.handleLaunchByName(w, req)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400 body=%s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "not found") {
+ t.Fatalf("body = %q, want 'not found'", w.Body.String())
+ }
+}
+
+func TestHandleAttachInstanceRejectsUnknownProvider(t *testing.T) {
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ AttachEnabled: true,
+ AttachAllowHosts: []string{"127.0.0.1"},
+ AttachAllowSchemes: []string{"ws"},
+ })
+
+ req := httptest.NewRequest(http.MethodPost, "/instances/attach", strings.NewReader(`{
+ "cdpUrl":"ws://127.0.0.1:9222/devtools/browser/abc",
+ "provider":"cloack"
+ }`))
+ w := httptest.NewRecorder()
+
+ o.handleAttachInstance(w, req)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400 body=%s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "invalid browser provider") {
+ t.Fatalf("body = %q, want invalid provider message", w.Body.String())
+ }
+}
+
+func TestHandleAttachInstanceUsesDefaultBrowserTargetWhenOmitted(t *testing.T) {
+ stubAttachBridgeHealthy(t)
+ runner := &mockRunner{portAvail: true}
+ o := setupAttachTargetsOrchestrator(t, runner)
+ o.runtimeCfg.DefaultTarget = "cloak-1"
+
+ req := httptest.NewRequest(http.MethodPost, "/instances/attach", strings.NewReader(`{
+ "name":"attached-cloak",
+ "cdpUrl":"ws://127.0.0.1:9222/devtools/browser/abc"
+ }`))
+ w := httptest.NewRecorder()
+
+ o.handleAttachInstance(w, req)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, want 201 body=%s", w.Code, w.Body.String())
+ }
+ var inst bridge.Instance
+ if err := json.NewDecoder(w.Body).Decode(&inst); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if inst.BrowserTarget != "cloak-1" {
+ t.Fatalf("BrowserTarget = %q, want cloak-1", inst.BrowserTarget)
+ }
+ if inst.BrowserProvider != config.BrowserProviderCloak {
+ t.Fatalf("BrowserProvider = %q, want cloak", inst.BrowserProvider)
+ }
+
+ target, status, err := o.FirstRunningURLForRequest(httptest.NewRequest(http.MethodGet, "/text", nil))
+ if err != nil {
+ t.Fatalf("FirstRunningURLForRequest error status=%d err=%v", status, err)
+ }
+ if target != inst.URL {
+ t.Fatalf("target URL = %q, want attached URL %q", target, inst.URL)
+ }
+}
+
+func TestHandleAttachInstanceExplicitBrowserTargetRoutes(t *testing.T) {
+ stubAttachBridgeHealthy(t)
+ runner := &mockRunner{portAvail: true}
+ o := setupAttachTargetsOrchestrator(t, runner)
+
+ req := httptest.NewRequest(http.MethodPost, "/instances/attach", strings.NewReader(`{
+ "name":"attached-cloak",
+ "cdpUrl":"ws://127.0.0.1:9222/devtools/browser/abc",
+ "browserTarget":"cloak-1"
+ }`))
+ w := httptest.NewRecorder()
+
+ o.handleAttachInstance(w, req)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, want 201 body=%s", w.Code, w.Body.String())
+ }
+ var inst bridge.Instance
+ if err := json.NewDecoder(w.Body).Decode(&inst); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if inst.BrowserTarget != "cloak-1" {
+ t.Fatalf("BrowserTarget = %q, want cloak-1", inst.BrowserTarget)
+ }
+ if inst.BrowserProvider != config.BrowserProviderCloak {
+ t.Fatalf("BrowserProvider = %q, want cloak", inst.BrowserProvider)
+ }
+ if !strings.Contains(strings.Join(runner.args, " "), "--browser-provider cloak") {
+ t.Fatalf("runner args = %v, want cloak provider", runner.args)
+ }
+
+ target, status, err := o.FirstRunningURLForRequest(httptest.NewRequest(http.MethodGet, "/text?browserTarget=cloak-1", nil))
+ if err != nil {
+ t.Fatalf("FirstRunningURLForRequest error status=%d err=%v", status, err)
+ }
+ if target != inst.URL {
+ t.Fatalf("target URL = %q, want attached URL %q", target, inst.URL)
+ }
+}
+
+func TestHandleAttachInstanceRejectsUnknownBrowserTarget(t *testing.T) {
+ runner := &mockRunner{portAvail: true}
+ o := setupAttachTargetsOrchestrator(t, runner)
+
+ req := httptest.NewRequest(http.MethodPost, "/instances/attach", strings.NewReader(`{
+ "name":"attached-ghost",
+ "cdpUrl":"ws://127.0.0.1:9222/devtools/browser/abc",
+ "browserTarget":"ghost"
+ }`))
+ w := httptest.NewRecorder()
+
+ o.handleAttachInstance(w, req)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400 body=%s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "not found") {
+ t.Fatalf("body = %q, want unknown-target message", w.Body.String())
+ }
+ if runner.runCalled {
+ t.Fatal("unknown browserTarget should be rejected before starting child bridge")
+ }
+}
+
+func TestHandleAttachInstanceRejectsProviderTargetConflict(t *testing.T) {
+ runner := &mockRunner{portAvail: true}
+ o := setupAttachTargetsOrchestrator(t, runner)
+
+ req := httptest.NewRequest(http.MethodPost, "/instances/attach", strings.NewReader(`{
+ "name":"attached-conflict",
+ "cdpUrl":"ws://127.0.0.1:9222/devtools/browser/abc",
+ "browserTarget":"cloak-1",
+ "provider":"chrome"
+ }`))
+ w := httptest.NewRecorder()
+
+ o.handleAttachInstance(w, req)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400 body=%s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "conflicts with browserTarget") {
+ t.Fatalf("body = %q, want provider conflict message", w.Body.String())
+ }
+ if runner.runCalled {
+ t.Fatal("provider conflict should be rejected before starting child bridge")
+ }
+}
+
+func TestHandleAttachBridgeUsesDefaultBrowserTarget(t *testing.T) {
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/health" {
+ t.Fatalf("path = %q, want /health", r.URL.Path)
+ }
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer backend.Close()
+
+ o := setupAttachTargetsOrchestrator(t, &mockRunner{portAvail: true})
+ o.client = backend.Client()
+ o.runtimeCfg.DefaultTarget = "cloak-1"
+ o.runtimeCfg.AttachAllowHosts = []string{"*"}
+ o.runtimeCfg.AttachAllowSchemes = []string{"http"}
+
+ req := httptest.NewRequest(http.MethodPost, "/instances/attach-bridge", strings.NewReader(fmt.Sprintf(`{
+ "name":"attached-bridge",
+ "baseUrl":%q
+ }`, backend.URL)))
+ w := httptest.NewRecorder()
+
+ o.handleAttachBridge(w, req)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, want 201 body=%s", w.Code, w.Body.String())
+ }
+ var inst bridge.Instance
+ if err := json.NewDecoder(w.Body).Decode(&inst); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if inst.BrowserTarget != "cloak-1" {
+ t.Fatalf("BrowserTarget = %q, want cloak-1", inst.BrowserTarget)
+ }
+ if inst.BrowserProvider != config.BrowserProviderCloak {
+ t.Fatalf("BrowserProvider = %q, want cloak", inst.BrowserProvider)
+ }
+
+ target, status, err := o.FirstRunningURLForRequest(httptest.NewRequest(http.MethodGet, "/tabs", nil))
+ if err != nil {
+ t.Fatalf("FirstRunningURLForRequest error status=%d err=%v", status, err)
+ }
+ if target != backend.URL {
+ t.Fatalf("target URL = %q, want bridge URL %q", target, backend.URL)
+ }
+}
+
+func setupAttachTargetsOrchestrator(t *testing.T, runner *mockRunner) *Orchestrator {
+ t.Helper()
+ old := processAliveFunc
+ processAliveFunc = func(pid int) bool { return pid > 0 }
+ t.Cleanup(func() { processAliveFunc = old })
+
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ AttachEnabled: true,
+ AttachAllowHosts: []string{"127.0.0.1"},
+ AttachAllowSchemes: []string{"ws"},
+ DefaultTarget: "chrome-local",
+ Targets: config.BrowserTargetsConfig{
+ "chrome-local": {Provider: config.BrowserProviderChrome},
+ "cloak-1": {Provider: config.BrowserProviderCloak},
+ },
+ })
+ return o
+}
+
+func setupFallbackOrchestrator(t *testing.T) *Orchestrator {
+ t.Helper()
+ old := processAliveFunc
+ processAliveFunc = func(pid int) bool { return pid > 0 }
+ t.Cleanup(func() { processAliveFunc = old })
+ stubPortAvailability(t, func(int) bool { return true })
+
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ DefaultTarget: "chrome-local",
+ Targets: config.BrowserTargetsConfig{
+ "chrome-local": {Provider: config.BrowserProviderChrome},
+ "cloak-1": {Provider: config.BrowserProviderCloak},
+ "backup": {Provider: config.BrowserProviderChrome},
+ },
+ FallbackOrder: []string{"cloak-1"},
+ })
+ return o
+}
+
+func TestHandleStartInstance_RequestFallbackTargets_Wins(t *testing.T) {
+ fastPolling(t)
+ o := setupFallbackOrchestrator(t)
+ fl := fakeLauncherForOrch(t, o, []scriptedOutcome{
+ {target: "chrome-local", failReason: ReasonBinaryMissing},
+ {target: "backup", succeed: true},
+ })
+
+ body := `{"browserTarget":"chrome-local","fallbackTargets":["backup"]}`
+ req := httptest.NewRequest(http.MethodPost, "/instances/start", strings.NewReader(body))
+ w := httptest.NewRecorder()
+
+ o.handleStartInstance(w, req)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, want %d body=%s", w.Code, http.StatusCreated, w.Body.String())
+ }
+ if len(fl.calls) != 2 {
+ t.Fatalf("expected 2 launch calls (primary + request fallback), got %d", len(fl.calls))
+ }
+ if fl.calls[1].BrowserTarget != "backup" {
+ t.Fatalf("second call BrowserTarget = %q, want backup (request must win over cfg.FallbackOrder)", fl.calls[1].BrowserTarget)
+ }
+
+ var inst bridge.Instance
+ if err := json.NewDecoder(w.Body).Decode(&inst); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if inst.BrowserTarget != "backup" {
+ t.Fatalf("BrowserTarget = %q, want backup", inst.BrowserTarget)
+ }
+ if inst.FallbackFrom != "chrome-local" {
+ t.Fatalf("FallbackFrom = %q, want chrome-local", inst.FallbackFrom)
+ }
+}
+
+func TestHandleStartInstance_ConfigFallbackOrder_UsedWhenRequestEmpty(t *testing.T) {
+ fastPolling(t)
+ o := setupFallbackOrchestrator(t)
+ fl := fakeLauncherForOrch(t, o, []scriptedOutcome{
+ {target: "chrome-local", failReason: ReasonBinaryMissing},
+ {target: "cloak-1", succeed: true},
+ })
+
+ body := `{"browserTarget":"chrome-local"}`
+ req := httptest.NewRequest(http.MethodPost, "/instances/start", strings.NewReader(body))
+ w := httptest.NewRecorder()
+
+ o.handleStartInstance(w, req)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, want %d body=%s", w.Code, http.StatusCreated, w.Body.String())
+ }
+ if len(fl.calls) != 2 {
+ t.Fatalf("expected 2 launch calls (primary + cfg fallback), got %d", len(fl.calls))
+ }
+ if fl.calls[1].BrowserTarget != "cloak-1" {
+ t.Fatalf("second call BrowserTarget = %q, want cloak-1 (from cfg.FallbackOrder)", fl.calls[1].BrowserTarget)
+ }
+}
+
+func TestHandleStartInstance_LegacyConfig_NoFallback(t *testing.T) {
+ old := processAliveFunc
+ processAliveFunc = func(pid int) bool { return pid > 0 }
+ defer func() { processAliveFunc = old }()
+ stubPortAvailability(t, func(int) bool { return true })
+
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.fallbackLauncher = fakeLauncherFor(nil)
+
+ req := httptest.NewRequest(http.MethodPost, "/instances/start", strings.NewReader(``))
+ req.ContentLength = 0
+ w := httptest.NewRecorder()
+
+ o.handleStartInstance(w, req)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, want %d body=%s", w.Code, http.StatusCreated, w.Body.String())
+ }
+}
+
+func TestHandleStartInstance_Exhaustion_502(t *testing.T) {
+ fastPolling(t)
+ o := setupFallbackOrchestrator(t)
+ _ = fakeLauncherForOrch(t, o, []scriptedOutcome{
+ {target: "chrome-local", failReason: ReasonBinaryMissing},
+ {target: "backup", failReason: ReasonStartupTimeout},
+ })
+
+ body := `{"browserTarget":"chrome-local","fallbackTargets":["backup"]}`
+ req := httptest.NewRequest(http.MethodPost, "/instances/start", strings.NewReader(body))
+ w := httptest.NewRecorder()
+
+ o.handleStartInstance(w, req)
+
+ if w.Code != http.StatusBadGateway {
+ t.Fatalf("status = %d, want 502 body=%s", w.Code, w.Body.String())
+ }
+ var payload map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if payload["code"] != "browser_target_unavailable" {
+ t.Fatalf("code = %v, want browser_target_unavailable; body=%s", payload["code"], w.Body.String())
+ }
+ details, ok := payload["details"].(map[string]any)
+ if !ok {
+ t.Fatalf("details missing; body=%s", w.Body.String())
+ }
+ attempts, ok := details["attempts"].([]any)
+ if !ok {
+ t.Fatalf("attempts missing in details; body=%s", w.Body.String())
+ }
+ if len(attempts) != 2 {
+ t.Fatalf("attempts = %d, want 2", len(attempts))
+ }
+ got := make(map[string]string, len(attempts))
+ for _, raw := range attempts {
+ entry := raw.(map[string]any)
+ got[entry["target"].(string)] = entry["reason"].(string)
+ }
+ if got["chrome-local"] != string(ReasonBinaryMissing) {
+ t.Fatalf("chrome-local reason = %q, want %q", got["chrome-local"], ReasonBinaryMissing)
+ }
+ if got["backup"] != string(ReasonStartupTimeout) {
+ t.Fatalf("backup reason = %q, want %q", got["backup"], ReasonStartupTimeout)
+ }
+}
+
+func TestHandleLaunchByName_RequestFallbackTargets_Wins(t *testing.T) {
+ fastPolling(t)
+ o := setupFallbackOrchestrator(t)
+ fl := fakeLauncherForOrch(t, o, []scriptedOutcome{
+ {target: "chrome-local", failReason: ReasonBinaryMissing},
+ {target: "backup", succeed: true},
+ })
+
+ body := `{"browserTarget":"chrome-local","fallbackTargets":["backup"]}`
+ req := httptest.NewRequest(http.MethodPost, "/instances/launch", strings.NewReader(body))
+ w := httptest.NewRecorder()
+
+ o.handleLaunchByName(w, req)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, want %d body=%s", w.Code, http.StatusCreated, w.Body.String())
+ }
+ if len(fl.calls) != 2 {
+ t.Fatalf("expected 2 launch calls, got %d", len(fl.calls))
+ }
+ if fl.calls[1].BrowserTarget != "backup" {
+ t.Fatalf("second call BrowserTarget = %q, want backup", fl.calls[1].BrowserTarget)
+ }
+}
+
+func TestHandleLaunchByName_Exhaustion_502(t *testing.T) {
+ fastPolling(t)
+ o := setupFallbackOrchestrator(t)
+ _ = fakeLauncherForOrch(t, o, []scriptedOutcome{
+ {target: "chrome-local", failReason: ReasonBinaryMissing},
+ {target: "cloak-1", failReason: ReasonStartupTimeout},
+ })
+
+ req := httptest.NewRequest(http.MethodPost, "/instances/launch", strings.NewReader(`{"browserTarget":"chrome-local"}`))
+ w := httptest.NewRecorder()
+
+ o.handleLaunchByName(w, req)
+
+ if w.Code != http.StatusBadGateway {
+ t.Fatalf("status = %d, want 502 body=%s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "browser_target_unavailable") {
+ t.Fatalf("body missing browser_target_unavailable code: %s", w.Body.String())
+ }
+}
diff --git a/internal/orchestrator/handlers_profiles.go b/internal/orchestrator/handlers_profiles.go
index 0ee0954a..c2f641b5 100644
--- a/internal/orchestrator/handlers_profiles.go
+++ b/internal/orchestrator/handlers_profiles.go
@@ -31,9 +31,11 @@ func (o *Orchestrator) handleStartByID(w http.ResponseWriter, r *http.Request) {
}
var req struct {
- Port string `json:"port,omitempty"`
- Headless bool `json:"headless"`
- SecurityPolicy *bridge.SecurityPolicy `json:"securityPolicy,omitempty"`
+ Port string `json:"port,omitempty"`
+ Headless bool `json:"headless"`
+ SecurityPolicy *bridge.SecurityPolicy `json:"securityPolicy,omitempty"`
+ BrowserTarget string `json:"browserTarget,omitempty"`
+ FallbackTargets []string `json:"fallbackTargets,omitempty"`
}
if r.ContentLength > 0 {
if err := httpx.DecodeJSONBody(w, r, 0, &req); err != nil {
@@ -46,12 +48,11 @@ func (o *Orchestrator) handleStartByID(w http.ResponseWriter, r *http.Request) {
return
}
- inst, err := o.LaunchWithOptions(name, req.Port, req.Headless, LaunchOptions{
+ inst, err := o.LaunchWithTargetSelection(name, req.Port, req.Headless, req.BrowserTarget, req.FallbackTargets, LaunchOptions{
SecurityPolicy: req.SecurityPolicy,
})
if err != nil {
- statusCode := classifyLaunchError(err)
- httpx.Error(w, statusCode, err)
+ writeLaunchError(w, err)
return
}
authn.AuditLog(r, "instance.started", "profileId", id, "profileName", name, "instanceId", inst.ID)
diff --git a/internal/orchestrator/handlers_profiles_test.go b/internal/orchestrator/handlers_profiles_test.go
new file mode 100644
index 00000000..547c51f9
--- /dev/null
+++ b/internal/orchestrator/handlers_profiles_test.go
@@ -0,0 +1,88 @@
+package orchestrator
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/profiles"
+)
+
+func TestHandleStartByID_TargetsConfigDefault_EchoesValues(t *testing.T) {
+ old := processAliveFunc
+ processAliveFunc = func(pid int) bool { return pid > 0 }
+ t.Cleanup(func() { processAliveFunc = old })
+ stubPortAvailability(t, func(int) bool { return true })
+
+ baseDir := t.TempDir()
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(baseDir, runner)
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ DefaultTarget: "cloak-1",
+ Targets: config.BrowserTargetsConfig{
+ "chrome-local": {Provider: config.BrowserProviderChrome},
+ "cloak-1": {Provider: config.BrowserProviderCloak},
+ },
+ })
+ pm := profiles.NewProfileManager(baseDir)
+ if err := pm.CreateWithMeta("work", profiles.ProfileMeta{}); err != nil {
+ t.Fatalf("CreateWithMeta: %v", err)
+ }
+ o.profiles = pm
+
+ req := httptest.NewRequest(http.MethodPost, "/profiles/work/start", strings.NewReader(`{}`))
+ req.SetPathValue("id", "work")
+ w := httptest.NewRecorder()
+
+ o.handleStartByID(w, req)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, want %d body=%s", w.Code, http.StatusCreated, w.Body.String())
+ }
+ var inst bridge.Instance
+ if err := json.NewDecoder(w.Body).Decode(&inst); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if inst.ProfileName != "work" {
+ t.Fatalf("ProfileName = %q, want work", inst.ProfileName)
+ }
+ if inst.BrowserTarget != "cloak-1" {
+ t.Fatalf("BrowserTarget = %q, want cloak-1", inst.BrowserTarget)
+ }
+ if inst.BrowserProvider != config.BrowserProviderCloak {
+ t.Fatalf("BrowserProvider = %q, want cloak", inst.BrowserProvider)
+ }
+}
+
+func TestHandleStartByID_TargetsConfigBadTarget_Rejects400(t *testing.T) {
+ baseDir := t.TempDir()
+ o := NewOrchestratorWithRunner(baseDir, &mockRunner{portAvail: true})
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ DefaultTarget: "chrome-local",
+ Targets: config.BrowserTargetsConfig{
+ "chrome-local": {Provider: config.BrowserProviderChrome},
+ },
+ })
+ pm := profiles.NewProfileManager(baseDir)
+ if err := pm.CreateWithMeta("work", profiles.ProfileMeta{}); err != nil {
+ t.Fatalf("CreateWithMeta: %v", err)
+ }
+ o.profiles = pm
+
+ req := httptest.NewRequest(http.MethodPost, "/profiles/work/start", strings.NewReader(`{"browserTarget":"ghost"}`))
+ req.SetPathValue("id", "work")
+ w := httptest.NewRecorder()
+
+ o.handleStartByID(w, req)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400 body=%s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "not found") {
+ t.Fatalf("body = %q, want 'not found'", w.Body.String())
+ }
+}
diff --git a/internal/orchestrator/health.go b/internal/orchestrator/health.go
index 7656e755..b0ef7e5c 100644
--- a/internal/orchestrator/health.go
+++ b/internal/orchestrator/health.go
@@ -3,6 +3,7 @@ package orchestrator
import (
"bytes"
"encoding/json"
+ "errors"
"fmt"
"io"
"log/slog"
@@ -105,16 +106,18 @@ func (o *Orchestrator) monitor(inst *InstanceInternal) {
if tail := tailLogLine(inst.logBuf.String()); tail != "" {
inst.Error += " | " + tail
}
+ inst.lastFailureReason = ClassifyLaunchFailure(errors.New(inst.Error))
eventType = "instance.error"
- slog.Error("instance exited before ready", "id", inst.ID)
+ slog.Error("instance exited before ready", "id", inst.ID, "reason", string(inst.lastFailureReason))
} else {
inst.Status = "error"
inst.Error = fmt.Errorf("health check timeout after %s (%s)", instanceStartupTimeout, lastProbe).Error()
if tail := tailLogLine(inst.logBuf.String()); tail != "" {
inst.Error += " | " + tail
}
+ inst.lastFailureReason = ClassifyLaunchFailure(errors.New(inst.Error))
eventType = "instance.error"
- slog.Error("instance failed to start", "id", inst.ID)
+ slog.Error("instance failed to start", "id", inst.ID, "reason", string(inst.lastFailureReason))
}
}
instCopy := inst.Instance
diff --git a/internal/orchestrator/health_test.go b/internal/orchestrator/health_test.go
index ad1460d4..1ddc49af 100644
--- a/internal/orchestrator/health_test.go
+++ b/internal/orchestrator/health_test.go
@@ -1,6 +1,7 @@
package orchestrator
import (
+ "errors"
"io"
"net/http"
"net/http/httptest"
@@ -15,6 +16,53 @@ import (
"github.com/pinchtab/pinchtab/internal/config"
)
+type exitingMockCmd struct {
+ waitErr error
+}
+
+func (m *exitingMockCmd) Wait() error { return m.waitErr }
+func (m *exitingMockCmd) PID() int { return 4242 }
+func (m *exitingMockCmd) Cancel() {}
+
+func TestMonitor_SetsLastFailureReasonOnProcessExit(t *testing.T) {
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+
+ // Stub the orchestrator HTTP client so the health probe never accidentally
+ // connects to a real service on the test port (e.g. a developer's running
+ // PinchTab on :9999). The test needs the monitor to land in the
+ // "exited early without ever becoming healthy" branch.
+ o.client = &http.Client{
+ Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
+ return nil, errors.New("stub: connection refused")
+ }),
+ }
+
+ inst := &InstanceInternal{
+ Instance: bridge.Instance{
+ ID: "inst_test0001",
+ Port: "9999",
+ Status: "starting",
+ },
+ URL: "http://127.0.0.1:9999",
+ cmd: &exitingMockCmd{waitErr: errors.New("signal: killed")},
+ logBuf: newRingBuffer(1024),
+ }
+ o.mu.Lock()
+ o.instances[inst.ID] = inst
+ o.mu.Unlock()
+
+ o.monitor(inst)
+
+ o.mu.RLock()
+ defer o.mu.RUnlock()
+ if inst.lastFailureReason != ReasonProcessExited {
+ t.Fatalf("lastFailureReason = %q, want %q", inst.lastFailureReason, ReasonProcessExited)
+ }
+ if !strings.Contains(inst.Error, "process exited before health check") {
+ t.Errorf("expected process-exit error message, got %q", inst.Error)
+ }
+}
+
type roundTripFunc func(*http.Request) (*http.Response, error)
func (fn roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
diff --git a/internal/orchestrator/launch_failure.go b/internal/orchestrator/launch_failure.go
new file mode 100644
index 00000000..8beac385
--- /dev/null
+++ b/internal/orchestrator/launch_failure.go
@@ -0,0 +1,86 @@
+package orchestrator
+
+import (
+ "context"
+ "errors"
+ "io/fs"
+ "os/exec"
+ "strings"
+)
+
+// LaunchFailureReason categorizes why a browser instance failed to launch.
+type LaunchFailureReason string
+
+const (
+ ReasonStartupTimeout LaunchFailureReason = "startup_timeout"
+ ReasonProcessExited LaunchFailureReason = "process_exited"
+ ReasonBinaryMissing LaunchFailureReason = "binary_missing"
+ ReasonCDPConnectFail LaunchFailureReason = "cdp_connect_fail"
+ ReasonHealthCheckTimeout LaunchFailureReason = "health_check_timeout"
+ ReasonUnknown LaunchFailureReason = "unknown"
+)
+
+// ClassifyLaunchFailure maps a launch error to a LaunchFailureReason; nil input returns ReasonUnknown.
+func ClassifyLaunchFailure(err error) LaunchFailureReason {
+ if err == nil {
+ return ReasonUnknown
+ }
+
+ // Typed checks first so they win over generic string matches.
+ var execErr *exec.Error
+ if errors.As(err, &execErr) {
+ return ReasonBinaryMissing
+ }
+ var pathErr *fs.PathError
+ if errors.As(err, &pathErr) {
+ return ReasonBinaryMissing
+ }
+ if errors.Is(err, fs.ErrNotExist) {
+ return ReasonBinaryMissing
+ }
+
+ msg := err.Error()
+
+ if strings.Contains(msg, "binary not found") ||
+ strings.Contains(msg, "chrome/chromium not found") {
+ return ReasonBinaryMissing
+ }
+
+ if errors.Is(err, context.DeadlineExceeded) {
+ return ReasonStartupTimeout
+ }
+ if strings.Contains(msg, "chrome startup timeout") {
+ return ReasonStartupTimeout
+ }
+
+ if strings.Contains(msg, "health check timeout") {
+ return ReasonHealthCheckTimeout
+ }
+
+ if strings.Contains(msg, "process exited") {
+ return ReasonProcessExited
+ }
+
+ if strings.Contains(msg, "failed to connect to chrome") ||
+ strings.Contains(msg, "failed to connect/inject") ||
+ strings.Contains(msg, "chrome devtools not ready") {
+ return ReasonCDPConnectFail
+ }
+
+ return ReasonUnknown
+}
+
+// recoverableFallbackReasons trigger fallback retry; anything else (incl. ReasonUnknown) bails out.
+var recoverableFallbackReasons = map[LaunchFailureReason]struct{}{
+ ReasonStartupTimeout: {},
+ ReasonProcessExited: {},
+ ReasonBinaryMissing: {},
+ ReasonCDPConnectFail: {},
+ ReasonHealthCheckTimeout: {},
+}
+
+// IsRecoverable reports whether the reason should trigger the next fallback candidate.
+func IsRecoverable(reason LaunchFailureReason) bool {
+ _, ok := recoverableFallbackReasons[reason]
+ return ok
+}
diff --git a/internal/orchestrator/launch_failure_test.go b/internal/orchestrator/launch_failure_test.go
new file mode 100644
index 00000000..15a3ae74
--- /dev/null
+++ b/internal/orchestrator/launch_failure_test.go
@@ -0,0 +1,126 @@
+package orchestrator
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io/fs"
+ "os/exec"
+ "testing"
+)
+
+func TestClassifyLaunchFailure(t *testing.T) {
+ tests := []struct {
+ name string
+ err error
+ want LaunchFailureReason
+ }{
+ {
+ name: "nil returns unknown",
+ err: nil,
+ want: ReasonUnknown,
+ },
+ {
+ name: "wrapped DeadlineExceeded → startup_timeout",
+ err: fmt.Errorf("chrome startup timeout after 20s: %w", context.DeadlineExceeded),
+ want: ReasonStartupTimeout,
+ },
+ {
+ name: "bare DeadlineExceeded → startup_timeout",
+ err: context.DeadlineExceeded,
+ want: ReasonStartupTimeout,
+ },
+ {
+ name: "exec.Error → binary_missing",
+ err: &exec.Error{Name: "chrome", Err: exec.ErrNotFound},
+ want: ReasonBinaryMissing,
+ },
+ {
+ name: "fs.PathError on binary → binary_missing",
+ err: &fs.PathError{Op: "stat", Path: "/no/such/chrome", Err: fs.ErrNotExist},
+ want: ReasonBinaryMissing,
+ },
+ {
+ name: "fs.ErrNotExist wrapped → binary_missing",
+ err: fmt.Errorf("locating binary: %w", fs.ErrNotExist),
+ want: ReasonBinaryMissing,
+ },
+ {
+ name: "missingBrowserBinaryError message (chrome) → binary_missing",
+ err: errors.New("chrome/chromium not found: please install chrome or chromium, or set 'binary' in config.json"),
+ want: ReasonBinaryMissing,
+ },
+ {
+ name: "missingBrowserBinaryError message (cloak) → binary_missing",
+ err: errors.New("cloakbrowser binary not found: set browser.binary ..."),
+ want: ReasonBinaryMissing,
+ },
+ {
+ name: "process exited before health check → process_exited",
+ err: errors.New("process exited before health check: signal: killed"),
+ want: ReasonProcessExited,
+ },
+ {
+ name: "health check timeout → health_check_timeout",
+ err: errors.New("health check timeout after 45s (127.0.0.1:9876 -> connection refused)"),
+ want: ReasonHealthCheckTimeout,
+ },
+ {
+ name: "failed to connect to chrome → cdp_connect_fail",
+ err: errors.New("failed to connect to chrome: websocket dial: connection refused"),
+ want: ReasonCDPConnectFail,
+ },
+ {
+ name: "remote connect/inject → cdp_connect_fail",
+ err: errors.New("failed to connect/inject via remote: handshake failed"),
+ want: ReasonCDPConnectFail,
+ },
+ {
+ name: "devtools not ready → cdp_connect_fail",
+ err: errors.New("chrome devtools not ready on port 9222: timeout"),
+ want: ReasonCDPConnectFail,
+ },
+ {
+ name: "generic error → unknown",
+ err: errors.New("something else entirely went wrong"),
+ want: ReasonUnknown,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := ClassifyLaunchFailure(tc.err)
+ if got != tc.want {
+ t.Errorf("ClassifyLaunchFailure(%v) = %q, want %q", tc.err, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestClassifyLaunchFailure_AllReasonsCovered(t *testing.T) {
+ reasons := map[LaunchFailureReason]bool{
+ ReasonStartupTimeout: false,
+ ReasonProcessExited: false,
+ ReasonBinaryMissing: false,
+ ReasonCDPConnectFail: false,
+ ReasonHealthCheckTimeout: false,
+ ReasonUnknown: false,
+ }
+ samples := []error{
+ nil,
+ context.DeadlineExceeded,
+ &exec.Error{Name: "chrome", Err: exec.ErrNotFound},
+ errors.New("process exited before health check"),
+ errors.New("health check timeout after 45s"),
+ errors.New("failed to connect to chrome"),
+ errors.New("something else"),
+ }
+ for _, s := range samples {
+ reasons[ClassifyLaunchFailure(s)] = true
+ }
+ for r, hit := range reasons {
+ if !hit {
+ t.Errorf("reason %q not produced by any sample input", r)
+ }
+ }
+}
diff --git a/internal/orchestrator/launch_target_config_test.go b/internal/orchestrator/launch_target_config_test.go
new file mode 100644
index 00000000..c9c6d1c6
--- /dev/null
+++ b/internal/orchestrator/launch_target_config_test.go
@@ -0,0 +1,172 @@
+package orchestrator
+
+import (
+ "encoding/json"
+ "os"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+// fakeOrch avoids the binary-install side effects of NewOrchestrator.
+func fakeOrch(cfg *config.RuntimeConfig) *Orchestrator {
+ return &Orchestrator{runtimeCfg: cfg}
+}
+
+func runtimeCfgWithTargets() *config.RuntimeConfig {
+ return &config.RuntimeConfig{
+ Port: "9867",
+ BrowserProvider: config.BrowserProviderChrome,
+ ChromeBinary: "/global/chrome",
+ ChromeExtraFlags: "--global-flag",
+ Cloak: config.CloakBrowserRuntimeConfig{
+ FingerprintSeed: "global-seed",
+ Platform: "linux",
+ },
+ Targets: config.BrowserTargetsConfig{
+ "chrome": config.BrowserTargetConfig{
+ Provider: config.BrowserProviderChrome,
+ Binary: "/global/chrome",
+ },
+ "cloak": config.BrowserTargetConfig{
+ Provider: config.BrowserProviderCloak,
+ Binary: "/opt/cloak/cloakbrowser",
+ ExtraFlags: "--target-flag",
+ Cloak: config.CloakBrowserConfig{
+ FingerprintSeed: "target-seed",
+ Timezone: "Europe/London",
+ },
+ },
+ },
+ DefaultTarget: "chrome",
+ }
+}
+
+func TestBuildChildFileConfig_TargetSelectedLaunchPromotesTargetBlock(t *testing.T) {
+ cfg := runtimeCfgWithTargets()
+ o := fakeOrch(cfg)
+
+ resolved, err := config.ResolveExplicitBrowserTarget(cfg, "cloak")
+ if err != nil {
+ t.Fatalf("resolve target: %v", err)
+ }
+ effective := resolved.Config
+ fc := o.buildChildFileConfig(effective, "9999", 12345, "/tmp/profile", "/tmp/state", true, nil, nil)
+
+ if fc.Browser.Provider != config.BrowserProviderCloak {
+ t.Errorf("Browser.Provider = %q, want cloak", fc.Browser.Provider)
+ }
+ if fc.Browser.ChromeBinary != "/opt/cloak/cloakbrowser" {
+ t.Errorf("Browser.ChromeBinary = %q, want /opt/cloak/cloakbrowser", fc.Browser.ChromeBinary)
+ }
+ if fc.Browser.ChromeExtraFlags != "--target-flag" {
+ t.Errorf("Browser.ChromeExtraFlags = %q, want --target-flag", fc.Browser.ChromeExtraFlags)
+ }
+ if fc.Browser.Cloak.FingerprintSeed != "target-seed" {
+ t.Errorf("Cloak.FingerprintSeed = %q, want target-seed", fc.Browser.Cloak.FingerprintSeed)
+ }
+ if fc.Browser.Cloak.Timezone != "Europe/London" {
+ t.Errorf("Cloak.Timezone = %q, want Europe/London", fc.Browser.Cloak.Timezone)
+ }
+ if fc.Browser.Cloak.Platform != "linux" {
+ t.Errorf("Cloak.Platform = %q, want preserved linux", fc.Browser.Cloak.Platform)
+ }
+ if cfg.BrowserProvider != config.BrowserProviderChrome ||
+ cfg.ChromeBinary != "/global/chrome" {
+ t.Errorf("runtime cfg mutated by override: %+v", cfg)
+ }
+}
+
+func TestBuildChildFileConfig_NoTargetSelected_UsesGlobalFields(t *testing.T) {
+ cfg := runtimeCfgWithTargets()
+ o := fakeOrch(cfg)
+
+ fc := o.buildChildFileConfig(cfg, "9999", 12345, "/tmp/profile", "/tmp/state", true, nil, nil)
+ if fc.Browser.Provider != config.BrowserProviderChrome {
+ t.Errorf("Browser.Provider = %q, want chrome (global)", fc.Browser.Provider)
+ }
+ if fc.Browser.ChromeBinary != "/global/chrome" {
+ t.Errorf("Browser.ChromeBinary = %q, want /global/chrome", fc.Browser.ChromeBinary)
+ }
+ if fc.Browser.ChromeExtraFlags != "--global-flag" {
+ t.Errorf("Browser.ChromeExtraFlags = %q, want --global-flag", fc.Browser.ChromeExtraFlags)
+ }
+}
+
+func TestBuildChildFileConfig_LegacyConfigByteStable(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ Port: "9867",
+ BrowserProvider: config.BrowserProviderChrome,
+ ChromeBinary: "/usr/bin/chrome",
+ ChromeExtraFlags: "--flag",
+ }
+ o := fakeOrch(cfg)
+
+ prev := o.buildChildFileConfig(o.runtimeCfg, "9999", 12345, "/tmp/profile", "/tmp/state", true, nil, nil)
+ prevBytes, err := json.MarshalIndent(prev, "", " ")
+ if err != nil {
+ t.Fatalf("marshal prev: %v", err)
+ }
+
+ got := o.buildChildFileConfig(cfg, "9999", 12345, "/tmp/profile", "/tmp/state", true, nil, nil)
+ gotBytes, err := json.MarshalIndent(got, "", " ")
+ if err != nil {
+ t.Fatalf("marshal got: %v", err)
+ }
+
+ if string(prevBytes) != string(gotBytes) {
+ t.Fatalf("legacy config child bytes differ.\nprev:\n%s\ngot:\n%s", prevBytes, gotBytes)
+ }
+}
+
+func TestWriteAttachChildConfigPreservesRuntimeModeAndEngine(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ Port: "9867",
+ StateDir: t.TempDir(),
+ BrowserProvider: config.BrowserProviderChrome,
+ Headless: true,
+ HeadlessSet: true,
+ Engine: "lite",
+ AttachEnabled: true,
+ AttachAllowHosts: []string{"*"},
+ AttachAllowSchemes: []string{"http", "ws"},
+ AttachForwardProxyAuth: true,
+ }
+ o := fakeOrch(cfg)
+
+ stateDir := t.TempDir()
+ configPath, err := o.writeAttachChildConfig("9999", config.BrowserProviderCloak, stateDir)
+ if err != nil {
+ t.Fatalf("writeAttachChildConfig: %v", err)
+ }
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("read attach child config: %v", err)
+ }
+ var fc config.FileConfig
+ if err := json.Unmarshal(data, &fc); err != nil {
+ t.Fatalf("unmarshal attach child config: %v", err)
+ }
+
+ if fc.Server.Engine != "lite" {
+ t.Errorf("Server.Engine = %q, want lite", fc.Server.Engine)
+ }
+ if fc.InstanceDefaults.Mode != "headless" {
+ t.Errorf("InstanceDefaults.Mode = %q, want headless", fc.InstanceDefaults.Mode)
+ }
+ if fc.Browser.Provider != config.BrowserProviderCloak {
+ t.Errorf("Browser.Provider = %q, want cloak", fc.Browser.Provider)
+ }
+ if fc.Security.Attach.Enabled == nil || *fc.Security.Attach.Enabled {
+ t.Errorf("Security.Attach.Enabled = %v, want false", fc.Security.Attach.Enabled)
+ }
+ if len(fc.Security.Attach.AllowHosts) != 0 {
+ t.Errorf("Security.Attach.AllowHosts = %v, want empty", fc.Security.Attach.AllowHosts)
+ }
+ if len(fc.Security.Attach.AllowSchemes) != 0 {
+ t.Errorf("Security.Attach.AllowSchemes = %v, want empty", fc.Security.Attach.AllowSchemes)
+ }
+ if fc.Security.Attach.ForwardProxyAuth == nil || *fc.Security.Attach.ForwardProxyAuth {
+ t.Errorf("Security.Attach.ForwardProxyAuth = %v, want false", fc.Security.Attach.ForwardProxyAuth)
+ }
+}
diff --git a/internal/orchestrator/launch_target_selection.go b/internal/orchestrator/launch_target_selection.go
new file mode 100644
index 00000000..6984e51b
--- /dev/null
+++ b/internal/orchestrator/launch_target_selection.go
@@ -0,0 +1,59 @@
+package orchestrator
+
+import (
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+// ResolveRequestedBrowserTarget resolves a public browserTarget value against
+// the current runtime config and wraps failures for HTTP handlers.
+func (o *Orchestrator) ResolveRequestedBrowserTarget(requested string) (targetName, provider string, err error) {
+ var resolved *config.ResolvedBrowserTarget
+ if strings.TrimSpace(requested) == "" {
+ resolved, err = config.ResolveDefaultBrowserTarget(o.runtimeCfg)
+ } else {
+ resolved, err = config.ResolveExplicitBrowserTarget(o.runtimeCfg, requested)
+ }
+ if err != nil {
+ return "", "", &UnknownBrowserTargetError{Target: requested, Err: err}
+ }
+ if resolved == nil || resolved.Legacy {
+ return "", "", nil
+ }
+ return resolved.Name, resolved.Provider, nil
+}
+
+// LaunchWithTargetSelection applies browserTarget/defaultTarget/fallbackOrder
+// consistently across orchestration entry points.
+func (o *Orchestrator) LaunchWithTargetSelection(
+ name, port string,
+ headless bool,
+ requestedTarget string,
+ fallbackTargets []string,
+ opts LaunchOptions,
+) (*bridge.Instance, error) {
+ resolvedTarget, resolvedProvider, err := o.ResolveRequestedBrowserTarget(requestedTarget)
+ if err != nil {
+ return nil, err
+ }
+
+ opts.RequestedBrowserTarget = requestedTarget
+ opts.BrowserTarget = resolvedTarget
+ opts.BrowserProvider = resolvedProvider
+
+ var fallbacks []string
+ if len(fallbackTargets) > 0 {
+ fallbacks = fallbackTargets
+ } else if resolvedTarget != "" && o.runtimeCfg != nil {
+ fallbacks = o.runtimeCfg.FallbackOrder
+ }
+
+ if resolvedTarget == "" || len(fallbacks) == 0 {
+ return o.LaunchWithOptions(name, port, headless, opts)
+ }
+
+ candidates := append([]string{resolvedTarget}, fallbacks...)
+ return o.LaunchWithFallback(name, port, headless, candidates, opts)
+}
diff --git a/internal/orchestrator/launch_with_fallback.go b/internal/orchestrator/launch_with_fallback.go
new file mode 100644
index 00000000..67e0986d
--- /dev/null
+++ b/internal/orchestrator/launch_with_fallback.go
@@ -0,0 +1,442 @@
+package orchestrator
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+// ErrUnknownBrowserTarget disambiguates 400 (unknown target) from 502 (exhaustion) for handlers.
+var ErrUnknownBrowserTarget = errors.New("unknown browser target")
+
+// UnknownBrowserTargetError satisfies errors.Is(ErrUnknownBrowserTarget).
+type UnknownBrowserTargetError struct {
+ Target string
+ Err error
+}
+
+func (e *UnknownBrowserTargetError) Error() string {
+ return fmt.Sprintf("launch with fallback: resolve target %q: %v", e.Target, e.Err)
+}
+
+func (e *UnknownBrowserTargetError) Unwrap() error { return e.Err }
+
+func (e *UnknownBrowserTargetError) Is(target error) bool {
+ return target == ErrUnknownBrowserTarget
+}
+
+type FallbackAttempt struct {
+ Target string `json:"target"`
+ Reason LaunchFailureReason `json:"reason"`
+}
+
+// FallbackExhaustedError maps to HTTP 502 browser_target_unavailable.
+type FallbackExhaustedError struct {
+ Attempts []FallbackAttempt
+ Cause error `json:"-"`
+}
+
+func (e *FallbackExhaustedError) Error() string {
+ parts := make([]string, 0, len(e.Attempts))
+ for _, a := range e.Attempts {
+ parts = append(parts, fmt.Sprintf("%s:%s", a.Target, string(a.Reason)))
+ }
+ msg := fmt.Sprintf("all browser targets failed: [%s]", strings.Join(parts, ", "))
+ if e.Cause != nil {
+ msg += ": " + e.Cause.Error()
+ }
+ return msg
+}
+
+func (e *FallbackExhaustedError) Unwrap() error { return e.Cause }
+
+// launchWithFallbackTimeout covers the monitor's instanceStartupTimeout plus a margin.
+const launchWithFallbackTimeout = 60 * time.Second
+
+var launchOutcomePollInterval = 50 * time.Millisecond
+
+// ResolvedLaunchTarget is the target/provider pair the planner passes into a
+// launch attempt.
+type ResolvedLaunchTarget struct {
+ Name string
+ Provider string
+}
+
+// LaunchOutcome is the terminal state observed for a launched attempt.
+type LaunchOutcome struct {
+ Status string
+ Reason LaunchFailureReason
+}
+
+// PlannedLaunch is the planner result before orchestrator-specific instance
+// storage metadata has been applied.
+type PlannedLaunch struct {
+ Instance *bridge.Instance
+ FallbackFrom string
+ FallbackReason LaunchFailureReason
+}
+
+// Launcher is the dependency boundary for fallback planning. Implementations
+// provide target resolution, launch execution, outcome polling, and teardown.
+type Launcher interface {
+ ResolveTarget(candidate string) (ResolvedLaunchTarget, error)
+ Launch(name, port string, headless bool, opts LaunchOptions) (*bridge.Instance, error)
+ WaitForLaunchOutcome(instanceID string, timeout time.Duration) (LaunchOutcome, error)
+ TearDownFailedAttempt(instanceID string)
+}
+
+// LaunchPlanner contains fallback policy without depending on Orchestrator
+// internals. It is intentionally small so policy tests can use a fake Launcher.
+type LaunchPlanner struct {
+ Launcher Launcher
+ Timeout time.Duration
+}
+
+type fallbackAttempt struct {
+ target string
+ reason LaunchFailureReason
+}
+
+func (a fallbackAttempt) String() string {
+ return fmt.Sprintf("%s:%s", a.target, string(a.reason))
+}
+
+// LaunchWithFallback tries candidates in order, tearing down recoverable failures before moving on.
+// Returns *UnknownBrowserTargetError for invalid names, *FallbackExhaustedError when all candidates fail.
+func (p LaunchPlanner) LaunchWithFallback(
+ name, port string, headless bool,
+ primaryAndFallbacks []string,
+ opts LaunchOptions,
+) (*PlannedLaunch, error) {
+ if p.Launcher == nil {
+ return nil, fmt.Errorf("launch with fallback: launcher is required")
+ }
+ timeout := p.Timeout
+ if timeout <= 0 {
+ timeout = launchWithFallbackTimeout
+ }
+ candidates := dedupCandidates(primaryAndFallbacks)
+ if len(candidates) == 0 {
+ return nil, fmt.Errorf("launch with fallback: at least one browser target candidate is required")
+ }
+
+ var (
+ attempts []fallbackAttempt
+ firstFailTarget string
+ firstFailReason LaunchFailureReason
+ )
+
+ for i, candidate := range candidates {
+ resolved, err := p.Launcher.ResolveTarget(candidate)
+ if err != nil {
+ return nil, &UnknownBrowserTargetError{Target: candidate, Err: err}
+ }
+
+ attemptOpts := opts
+ attemptOpts.BrowserTarget = resolved.Name
+ attemptOpts.BrowserProvider = resolved.Provider
+
+ inst, launchErr := p.Launcher.Launch(name, port, headless, attemptOpts)
+ if launchErr != nil {
+ reason := ClassifyLaunchFailure(launchErr)
+ attempts = append(attempts, fallbackAttempt{target: candidate, reason: reason})
+ if i == 0 {
+ firstFailTarget = candidate
+ firstFailReason = reason
+ }
+ if !IsRecoverable(reason) {
+ return nil, fallbackExhaustedError(attempts, fmt.Errorf(
+ "launch with fallback: candidate %q failed non-recoverably (%s): %w",
+ candidate, string(reason), launchErr,
+ ))
+ }
+ continue
+ }
+ if inst == nil {
+ reason := ReasonUnknown
+ attempts = append(attempts, fallbackAttempt{target: candidate, reason: reason})
+ return nil, fallbackExhaustedError(attempts, fmt.Errorf(
+ "launch with fallback: candidate %q returned nil instance",
+ candidate,
+ ))
+ }
+
+ outcome, waitErr := p.Launcher.WaitForLaunchOutcome(inst.ID, timeout)
+ if waitErr != nil {
+ reason := ClassifyLaunchFailure(waitErr)
+ attempts = append(attempts, fallbackAttempt{target: candidate, reason: reason})
+ p.Launcher.TearDownFailedAttempt(inst.ID)
+ return nil, fallbackExhaustedError(attempts, fmt.Errorf(
+ "launch with fallback: wait for %q: %w", candidate, waitErr,
+ ))
+ }
+
+ if outcome.Status == "running" {
+ result := &PlannedLaunch{Instance: inst}
+ if i > 0 {
+ result.FallbackFrom = firstFailTarget
+ result.FallbackReason = firstFailReason
+ }
+ return result, nil
+ }
+
+ attempts = append(attempts, fallbackAttempt{target: candidate, reason: outcome.Reason})
+ if i == 0 {
+ firstFailTarget = candidate
+ firstFailReason = outcome.Reason
+ }
+
+ if !IsRecoverable(outcome.Reason) {
+ p.Launcher.TearDownFailedAttempt(inst.ID)
+ return nil, fallbackExhaustedError(attempts, fmt.Errorf(
+ "launch with fallback: candidate %q failed non-recoverably (%s)",
+ candidate, string(outcome.Reason),
+ ))
+ }
+
+ p.Launcher.TearDownFailedAttempt(inst.ID)
+ }
+
+ return nil, fallbackExhaustedError(attempts, nil)
+}
+
+// LaunchWithFallback tries candidates in order, tearing down recoverable failures before moving on.
+// Returns *UnknownBrowserTargetError for invalid names, *FallbackExhaustedError when all candidates fail.
+func (o *Orchestrator) LaunchWithFallback(
+ name, port string, headless bool,
+ primaryAndFallbacks []string,
+ opts LaunchOptions,
+) (*bridge.Instance, error) {
+ planner := LaunchPlanner{
+ Launcher: o.fallbackLaunchPlannerLauncher(),
+ Timeout: launchWithFallbackTimeout,
+ }
+ planned, err := planner.LaunchWithFallback(name, port, headless, primaryAndFallbacks, opts)
+ if err != nil {
+ return nil, err
+ }
+ return o.snapshotWithFallbackMetadata(planned), nil
+}
+
+func (o *Orchestrator) fallbackLaunchPlannerLauncher() Launcher {
+ if o != nil && o.fallbackLauncher != nil {
+ return o.fallbackLauncher
+ }
+ return orchestratorFallbackLauncher{orch: o}
+}
+
+type orchestratorFallbackLauncher struct {
+ orch *Orchestrator
+}
+
+func (l orchestratorFallbackLauncher) ResolveTarget(candidate string) (ResolvedLaunchTarget, error) {
+ resolved, err := config.ResolveExplicitBrowserTarget(l.orch.runtimeCfg, candidate)
+ if err != nil {
+ return ResolvedLaunchTarget{}, err
+ }
+ return ResolvedLaunchTarget{Name: resolved.Name, Provider: resolved.Provider}, nil
+}
+
+func (l orchestratorFallbackLauncher) Launch(name, port string, headless bool, opts LaunchOptions) (*bridge.Instance, error) {
+ return l.orch.LaunchWithOptions(name, port, headless, opts)
+}
+
+func (l orchestratorFallbackLauncher) WaitForLaunchOutcome(instanceID string, timeout time.Duration) (LaunchOutcome, error) {
+ status, reason, err := l.orch.waitForLaunchOutcome(instanceID, timeout)
+ return LaunchOutcome{Status: status, Reason: reason}, err
+}
+
+func (l orchestratorFallbackLauncher) TearDownFailedAttempt(instanceID string) {
+ l.orch.tearDownFailedAttempt(instanceID)
+}
+
+func (o *Orchestrator) snapshotWithFallbackMetadata(planned *PlannedLaunch) *bridge.Instance {
+ if planned == nil || planned.Instance == nil {
+ return nil
+ }
+ if planned.FallbackFrom == "" {
+ return planned.Instance
+ }
+
+ reason := string(planned.FallbackReason)
+ o.mu.Lock()
+ if internal, ok := o.instances[planned.Instance.ID]; ok {
+ internal.FallbackFrom = planned.FallbackFrom
+ internal.FallbackReason = reason
+ snapshot := internal.Instance
+ o.mu.Unlock()
+ o.syncInstanceToManager(&snapshot)
+ return &snapshot
+ }
+ o.mu.Unlock()
+
+ snapshot := *planned.Instance
+ snapshot.FallbackFrom = planned.FallbackFrom
+ snapshot.FallbackReason = reason
+ return &snapshot
+}
+
+func fallbackExhaustedError(attempts []fallbackAttempt, cause error) *FallbackExhaustedError {
+ exhausted := &FallbackExhaustedError{
+ Attempts: make([]FallbackAttempt, 0, len(attempts)),
+ Cause: cause,
+ }
+ for _, a := range attempts {
+ exhausted.Attempts = append(exhausted.Attempts, FallbackAttempt{Target: a.target, Reason: a.reason})
+ }
+ return exhausted
+}
+
+// waitForLaunchOutcome polls until the instance reaches running/error or the timeout fires.
+func (o *Orchestrator) waitForLaunchOutcome(instanceID string, timeout time.Duration) (string, LaunchFailureReason, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), timeout)
+ defer cancel()
+
+ ticker := time.NewTicker(launchOutcomePollInterval)
+ defer ticker.Stop()
+
+ for {
+ o.mu.RLock()
+ inst, ok := o.instances[instanceID]
+ var status string
+ var reason LaunchFailureReason
+ if ok {
+ status = inst.Status
+ reason = inst.lastFailureReason
+ }
+ o.mu.RUnlock()
+
+ if !ok {
+ return "", ReasonUnknown, fmt.Errorf("instance %q disappeared from orchestrator map", instanceID)
+ }
+
+ switch status {
+ case "running":
+ return "running", ReasonUnknown, nil
+ case "error":
+ return "error", reason, nil
+ }
+
+ select {
+ case <-ctx.Done():
+ return "", ReasonUnknown, ctx.Err()
+ case <-ticker.C:
+ }
+ }
+}
+
+// tearDownFailedAttempt logs but does not propagate errors so teardown never blocks fallback.
+func (o *Orchestrator) tearDownFailedAttempt(instanceID string) {
+ inst := o.detachFailedAttempt(instanceID)
+ if inst == nil {
+ return
+ }
+ go o.stopDetachedFailedAttempt(instanceID, inst)
+}
+
+func (o *Orchestrator) detachFailedAttempt(instanceID string) *InstanceInternal {
+ o.mu.Lock()
+ inst, ok := o.instances[instanceID]
+ if !ok {
+ o.mu.Unlock()
+ return nil
+ }
+ inst.Status = "stopping"
+ delete(o.instances, instanceID)
+ o.mu.Unlock()
+
+ o.removeInstanceFromManager(instanceID)
+ o.releaseInstancePorts(instanceID, inst)
+ return inst
+}
+
+func (o *Orchestrator) stopDetachedFailedAttempt(instanceID string, inst *InstanceInternal) {
+ if inst == nil {
+ return
+ }
+ defer func() {
+ o.cleanupDetachedFailedAttemptProfile(inst.ProfileName)
+ }()
+
+ if inst.cmd == nil {
+ if inst.AttachType == "bridge" {
+ o.requestDetachedShutdown(inst)
+ }
+ return
+ }
+
+ o.requestDetachedShutdown(inst)
+ pid := inst.cmd.PID()
+ if pid > 0 {
+ if waitForProcessExit(pid, 5*time.Second) {
+ return
+ }
+
+ if err := killProcessGroup(pid, sigTERM); err != nil {
+ slog.Warn("failed to send SIGTERM to failed fallback attempt", "id", instanceID, "pid", pid, "err", err)
+ }
+ if waitForProcessExit(pid, 3*time.Second) {
+ return
+ }
+
+ if err := killProcessGroup(pid, sigKILL); err != nil {
+ slog.Warn("failed to send SIGKILL to failed fallback attempt", "id", instanceID, "pid", pid, "err", err)
+ }
+ }
+
+ inst.cmd.Cancel()
+ if pid > 0 && !waitForProcessExit(pid, 2*time.Second) {
+ slog.Warn("failed fallback attempt still running after teardown", "id", instanceID, "pid", pid)
+ }
+}
+
+func (o *Orchestrator) requestDetachedShutdown(inst *InstanceInternal) {
+ reqCtx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
+ defer cancel()
+ targetURL, targetErr := o.instancePathURL(inst, "/shutdown", "")
+ if targetErr != nil {
+ return
+ }
+ req, _ := http.NewRequestWithContext(reqCtx, http.MethodPost, targetURL.String(), nil)
+ o.applyInstanceAuth(req, inst)
+ if resp, err := o.client.Do(req); err == nil {
+ _ = resp.Body.Close()
+ }
+}
+
+func (o *Orchestrator) cleanupDetachedFailedAttemptProfile(profileName string) {
+ o.mu.RLock()
+ for _, inst := range o.instances {
+ if inst != nil && inst.ProfileName == profileName && instanceIsActive(inst) {
+ o.mu.RUnlock()
+ return
+ }
+ }
+ o.mu.RUnlock()
+ o.cleanupStoppedProfile(profileName)
+}
+
+// dedupCandidates trims whitespace, drops empty/duplicate entries, preserves order.
+func dedupCandidates(in []string) []string {
+ out := make([]string, 0, len(in))
+ seen := make(map[string]struct{}, len(in))
+ for _, raw := range in {
+ name := strings.TrimSpace(raw)
+ if name == "" {
+ continue
+ }
+ if _, dup := seen[name]; dup {
+ continue
+ }
+ seen[name] = struct{}{}
+ out = append(out, name)
+ }
+ return out
+}
diff --git a/internal/orchestrator/launch_with_fallback_test.go b/internal/orchestrator/launch_with_fallback_test.go
new file mode 100644
index 00000000..c8421365
--- /dev/null
+++ b/internal/orchestrator/launch_with_fallback_test.go
@@ -0,0 +1,492 @@
+package orchestrator
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type scriptedOutcome struct {
+ target string
+ succeed bool
+ failReason LaunchFailureReason
+ errOnLaunch error
+}
+
+type fakeLauncher struct {
+ mu sync.Mutex
+ plan []scriptedOutcome
+ calls []LaunchOptions
+ createdIDs []string
+ tornDown []string
+ idCounter int
+ orch *Orchestrator
+ outcomes map[string]scriptedOutcome
+}
+
+func (fl *fakeLauncher) ResolveTarget(candidate string) (ResolvedLaunchTarget, error) {
+ if strings.Contains(candidate, "cloak") {
+ return ResolvedLaunchTarget{Name: candidate, Provider: config.BrowserProviderCloak}, nil
+ }
+ switch candidate {
+ case "chrome", "chrome-local", "backup":
+ return ResolvedLaunchTarget{Name: candidate, Provider: config.BrowserProviderChrome}, nil
+ default:
+ return ResolvedLaunchTarget{}, fmt.Errorf("unknown target %q", candidate)
+ }
+}
+
+func (fl *fakeLauncher) Launch(name, port string, headless bool, opts LaunchOptions) (*bridge.Instance, error) {
+ fl.mu.Lock()
+ defer fl.mu.Unlock()
+ if len(fl.calls) >= len(fl.plan) {
+ return nil, fmt.Errorf("fakeLauncher: unexpected extra call (call #%d, plan has %d entries)", len(fl.calls)+1, len(fl.plan))
+ }
+ step := fl.plan[len(fl.calls)]
+ fl.calls = append(fl.calls, opts)
+
+ if step.errOnLaunch != nil {
+ return nil, step.errOnLaunch
+ }
+
+ fl.idCounter++
+ id := fmt.Sprintf("inst_fake_%02d", fl.idCounter)
+ fl.createdIDs = append(fl.createdIDs, id)
+ if fl.outcomes == nil {
+ fl.outcomes = make(map[string]scriptedOutcome)
+ }
+ fl.outcomes[id] = step
+
+ instance := bridge.Instance{
+ ID: id,
+ ProfileName: name,
+ Port: port,
+ Headless: headless,
+ Mode: bridge.ModeFromHeadless(headless),
+ Status: "starting",
+ StartTime: time.Now(),
+ BrowserTarget: opts.BrowserTarget,
+ BrowserProvider: opts.BrowserProvider,
+ }
+ if fl.orch != nil {
+ internal := &InstanceInternal{
+ Instance: instance,
+ resolvedBrowserTarget: opts.BrowserTarget,
+ browserProvider: opts.BrowserProvider,
+ }
+ fl.orch.mu.Lock()
+ fl.orch.instances[id] = internal
+ fl.orch.mu.Unlock()
+ }
+
+ snapshot := instance
+ return &snapshot, nil
+}
+
+func (fl *fakeLauncher) WaitForLaunchOutcome(instanceID string, timeout time.Duration) (LaunchOutcome, error) {
+ fl.mu.Lock()
+ step, ok := fl.outcomes[instanceID]
+ fl.mu.Unlock()
+ if !ok {
+ return LaunchOutcome{}, fmt.Errorf("unknown instance %q", instanceID)
+ }
+
+ if step.succeed {
+ if fl.orch != nil {
+ fl.orch.mu.Lock()
+ if internal, ok := fl.orch.instances[instanceID]; ok {
+ internal.Status = "running"
+ }
+ fl.orch.mu.Unlock()
+ }
+ return LaunchOutcome{Status: "running"}, nil
+ }
+
+ if fl.orch != nil {
+ fl.orch.mu.Lock()
+ if internal, ok := fl.orch.instances[instanceID]; ok {
+ internal.Status = "error"
+ internal.lastFailureReason = step.failReason
+ internal.Error = fmt.Sprintf("scripted failure: %s", string(step.failReason))
+ }
+ fl.orch.mu.Unlock()
+ }
+ return LaunchOutcome{Status: "error", Reason: step.failReason}, nil
+}
+
+func (fl *fakeLauncher) TearDownFailedAttempt(instanceID string) {
+ fl.mu.Lock()
+ fl.tornDown = append(fl.tornDown, instanceID)
+ fl.mu.Unlock()
+ if fl.orch != nil {
+ fl.orch.mu.Lock()
+ delete(fl.orch.instances, instanceID)
+ fl.orch.mu.Unlock()
+ }
+}
+
+func fakeLauncherFor(plan []scriptedOutcome) *fakeLauncher {
+ return &fakeLauncher{plan: plan, outcomes: make(map[string]scriptedOutcome)}
+}
+
+func fakeLauncherForOrch(t *testing.T, o *Orchestrator, plan []scriptedOutcome) *fakeLauncher {
+ t.Helper()
+ fl := fakeLauncherFor(plan)
+ fl.orch = o
+ o.fallbackLauncher = fl
+ return fl
+}
+
+func launchWithFallbackForTest(fl *fakeLauncher, candidates []string) (*PlannedLaunch, error) {
+ return LaunchPlanner{
+ Launcher: fl,
+ Timeout: time.Second,
+ }.LaunchWithFallback("prof", "9000", true, candidates, LaunchOptions{})
+}
+
+func fastPolling(t *testing.T) {
+ t.Helper()
+ prev := launchOutcomePollInterval
+ launchOutcomePollInterval = time.Millisecond
+ t.Cleanup(func() { launchOutcomePollInterval = prev })
+}
+
+func newFallbackTestOrch(t *testing.T) *Orchestrator {
+ t.Helper()
+ return &Orchestrator{
+ instances: make(map[string]*InstanceInternal),
+ portAllocator: NewPortAllocator(9000, 9100),
+ runtimeCfg: &config.RuntimeConfig{
+ BrowserProvider: config.BrowserProviderChrome,
+ Targets: config.BrowserTargetsConfig{
+ "chrome": config.BrowserTargetConfig{Provider: config.BrowserProviderChrome},
+ "cloak": config.BrowserTargetConfig{Provider: config.BrowserProviderCloak},
+ "backup": config.BrowserTargetConfig{Provider: config.BrowserProviderChrome},
+ },
+ DefaultTarget: "chrome",
+ },
+ }
+}
+
+func TestLaunchWithFallback_FirstCandidateSucceeds(t *testing.T) {
+ fastPolling(t)
+ fl := fakeLauncherFor([]scriptedOutcome{
+ {target: "chrome", succeed: true},
+ })
+
+ planned, err := launchWithFallbackForTest(fl, []string{"chrome"})
+ if err != nil {
+ t.Fatalf("LaunchWithFallback returned error: %v", err)
+ }
+ inst := planned.Instance
+ if inst == nil {
+ t.Fatal("expected non-nil instance")
+ }
+ if inst.FallbackFrom != "" || inst.FallbackReason != "" {
+ t.Errorf("expected no fallback metadata, got from=%q reason=%q", inst.FallbackFrom, inst.FallbackReason)
+ }
+ if inst.BrowserTarget != "chrome" {
+ t.Errorf("BrowserTarget = %q, want chrome", inst.BrowserTarget)
+ }
+ if len(fl.calls) != 1 {
+ t.Errorf("expected 1 launch call, got %d", len(fl.calls))
+ }
+}
+
+func TestLaunchWithFallback_FirstFailsSecondSucceeds(t *testing.T) {
+ fastPolling(t)
+ fl := fakeLauncherFor([]scriptedOutcome{
+ {target: "chrome", failReason: ReasonBinaryMissing},
+ {target: "cloak", succeed: true},
+ })
+
+ planned, err := launchWithFallbackForTest(fl, []string{"chrome", "cloak"})
+ if err != nil {
+ t.Fatalf("LaunchWithFallback returned error: %v", err)
+ }
+ inst := planned.Instance
+ if planned.FallbackFrom != "chrome" {
+ t.Errorf("FallbackFrom = %q, want chrome", planned.FallbackFrom)
+ }
+ if planned.FallbackReason != ReasonBinaryMissing {
+ t.Errorf("FallbackReason = %q, want %q", planned.FallbackReason, ReasonBinaryMissing)
+ }
+ if inst.BrowserTarget != "cloak" {
+ t.Errorf("BrowserTarget = %q, want cloak", inst.BrowserTarget)
+ }
+ if len(fl.calls) != 2 {
+ t.Errorf("expected 2 launch calls, got %d", len(fl.calls))
+ }
+
+}
+
+func TestLaunchWithFallback_StoresFallbackMetadataOnCanonicalInstance(t *testing.T) {
+ fastPolling(t)
+ o := newFallbackTestOrch(t)
+ _ = fakeLauncherForOrch(t, o, []scriptedOutcome{
+ {target: "chrome", failReason: ReasonBinaryMissing},
+ {target: "cloak", succeed: true},
+ })
+
+ inst, err := o.LaunchWithFallback("prof", "9000", true, []string{"chrome", "cloak"}, LaunchOptions{})
+ if err != nil {
+ t.Fatalf("LaunchWithFallback returned error: %v", err)
+ }
+ if inst.FallbackFrom != "chrome" || inst.FallbackReason != string(ReasonBinaryMissing) {
+ t.Fatalf("returned fallback metadata = from %q reason %q, want chrome/%s", inst.FallbackFrom, inst.FallbackReason, ReasonBinaryMissing)
+ }
+
+ o.mu.RLock()
+ stored, ok := o.instances[inst.ID]
+ o.mu.RUnlock()
+ if !ok {
+ t.Fatalf("running instance %q missing from orchestrator map", inst.ID)
+ }
+ if stored.FallbackFrom != inst.FallbackFrom || stored.FallbackReason != inst.FallbackReason {
+ t.Errorf("stored fallback metadata diverged from returned snapshot: stored=%+v returned=%+v", stored.Instance, inst)
+ }
+}
+
+func TestLaunchUsesConfiguredFallbackOrder(t *testing.T) {
+ fastPolling(t)
+ o := newFallbackTestOrch(t)
+ o.runtimeCfg.FallbackOrder = []string{"cloak"}
+ fl := fakeLauncherForOrch(t, o, []scriptedOutcome{
+ {target: "chrome", failReason: ReasonBinaryMissing},
+ {target: "cloak", succeed: true},
+ })
+
+ inst, err := o.Launch("prof", "9000", true, nil)
+ if err != nil {
+ t.Fatalf("Launch returned error: %v", err)
+ }
+ if inst.BrowserTarget != "cloak" {
+ t.Fatalf("BrowserTarget = %q, want cloak fallback", inst.BrowserTarget)
+ }
+ if inst.FallbackFrom != "chrome" {
+ t.Fatalf("FallbackFrom = %q, want chrome", inst.FallbackFrom)
+ }
+ if len(fl.calls) != 2 {
+ t.Fatalf("launch calls = %d, want 2", len(fl.calls))
+ }
+ if fl.calls[0].BrowserTarget != "chrome" || fl.calls[1].BrowserTarget != "cloak" {
+ t.Fatalf("launch target order = [%q, %q], want [chrome, cloak]", fl.calls[0].BrowserTarget, fl.calls[1].BrowserTarget)
+ }
+}
+
+func TestLaunchWithFallback_AllFail_Exhaustion(t *testing.T) {
+ fastPolling(t)
+ fl := fakeLauncherFor([]scriptedOutcome{
+ {target: "chrome", failReason: ReasonStartupTimeout},
+ {target: "cloak", failReason: ReasonBinaryMissing},
+ {target: "backup", failReason: ReasonHealthCheckTimeout},
+ })
+
+ _, err := launchWithFallbackForTest(fl, []string{"chrome", "cloak", "backup"})
+ if err == nil {
+ t.Fatal("expected error on exhaustion")
+ }
+ msg := err.Error()
+ if !strings.Contains(msg, "all browser targets failed") {
+ t.Errorf("error missing exhaustion prefix: %q", msg)
+ }
+ for _, want := range []string{
+ "chrome:" + string(ReasonStartupTimeout),
+ "cloak:" + string(ReasonBinaryMissing),
+ "backup:" + string(ReasonHealthCheckTimeout),
+ } {
+ if !strings.Contains(msg, want) {
+ t.Errorf("error missing attempt %q: %q", want, msg)
+ }
+ }
+
+ if len(fl.tornDown) != 3 {
+ t.Errorf("expected all failed attempts to be torn down, got %d teardowns", len(fl.tornDown))
+ }
+}
+
+func TestLaunchWithFallback_NonRecoverableAbortsImmediately(t *testing.T) {
+ fastPolling(t)
+ fl := fakeLauncherFor([]scriptedOutcome{
+ {target: "chrome", failReason: ReasonUnknown},
+ // Omitting a second entry triggers "unexpected extra call" if the loop continues.
+ })
+
+ _, err := launchWithFallbackForTest(fl, []string{"chrome", "cloak"})
+ if err == nil {
+ t.Fatal("expected non-recoverable failure to surface as error")
+ }
+ if !strings.Contains(err.Error(), "non-recoverably") {
+ t.Errorf("error should flag non-recoverable: %q", err.Error())
+ }
+ var exhausted *FallbackExhaustedError
+ if !errors.As(err, &exhausted) {
+ t.Fatalf("non-recoverable failure should still return FallbackExhaustedError, got %T", err)
+ }
+ if len(exhausted.Attempts) != 1 || exhausted.Attempts[0].Target != "chrome" {
+ t.Fatalf("attempt metadata lost: %+v", exhausted.Attempts)
+ }
+ if len(fl.calls) != 1 {
+ t.Errorf("expected exactly 1 launch attempt, got %d", len(fl.calls))
+ }
+}
+
+func TestLaunchWithFallback_TearsDownFailedAttempt(t *testing.T) {
+ fastPolling(t)
+ fl := fakeLauncherFor([]scriptedOutcome{
+ {target: "chrome", failReason: ReasonProcessExited},
+ {target: "cloak", succeed: true},
+ })
+
+ _, err := launchWithFallbackForTest(fl, []string{"chrome", "cloak"})
+ if err != nil {
+ t.Fatalf("LaunchWithFallback returned error: %v", err)
+ }
+
+ if len(fl.createdIDs) != 2 {
+ t.Fatalf("expected 2 instances created, got %d", len(fl.createdIDs))
+ }
+ if len(fl.tornDown) != 1 || fl.tornDown[0] != fl.createdIDs[0] {
+ t.Errorf("failed attempt teardown = %v, want [%s]", fl.tornDown, fl.createdIDs[0])
+ }
+ if fl.tornDown[0] == fl.createdIDs[1] {
+ t.Errorf("running instance %q was torn down", fl.createdIDs[1])
+ }
+}
+
+func TestTearDownFailedAttempt_DetachesBeforeAsyncStop(t *testing.T) {
+ oldAlive := processAliveFunc
+ processAliveFunc = func(pid int) bool { return true }
+ t.Cleanup(func() { processAliveFunc = oldAlive })
+
+ o := newFallbackTestOrch(t)
+ failed := &InstanceInternal{
+ Instance: bridge.Instance{
+ ID: "failed",
+ ProfileName: "prof",
+ Port: "9001",
+ Status: "error",
+ },
+ }
+ activeSameProfile := &InstanceInternal{
+ Instance: bridge.Instance{
+ ID: "active",
+ ProfileName: "prof",
+ Port: "9002",
+ Status: "running",
+ },
+ cmd: &mockCmd{pid: 99, isAlive: true},
+ }
+ o.instances[failed.ID] = failed
+ o.instances[activeSameProfile.ID] = activeSameProfile
+
+ o.tearDownFailedAttempt(failed.ID)
+
+ o.mu.RLock()
+ _, failedPresent := o.instances[failed.ID]
+ _, activePresent := o.instances[activeSameProfile.ID]
+ o.mu.RUnlock()
+ if failedPresent {
+ t.Fatal("failed attempt remained in orchestrator map")
+ }
+ if !activePresent {
+ t.Fatal("active same-profile instance was removed")
+ }
+}
+
+func TestLaunchWithFallback_UnknownCandidateIsHardError(t *testing.T) {
+ fastPolling(t)
+ fl := fakeLauncherFor([]scriptedOutcome{})
+
+ _, err := launchWithFallbackForTest(fl, []string{"does-not-exist", "chrome"})
+ if err == nil {
+ t.Fatal("expected hard error for unknown candidate")
+ }
+ if !strings.Contains(err.Error(), "does-not-exist") {
+ t.Errorf("error should reference the offending name: %q", err.Error())
+ }
+ if len(fl.calls) != 0 {
+ t.Errorf("expected zero launch attempts on unknown candidate, got %d", len(fl.calls))
+ }
+}
+
+func TestLaunchWithFallback_EmptyCandidateList(t *testing.T) {
+ fastPolling(t)
+ fl := fakeLauncherFor(nil)
+
+ _, err := launchWithFallbackForTest(fl, nil)
+ if err == nil {
+ t.Fatal("expected validation error on empty candidate list")
+ }
+ if !strings.Contains(err.Error(), "at least one") {
+ t.Errorf("unexpected error: %q", err.Error())
+ }
+
+ _, err = launchWithFallbackForTest(fl, []string{"", " "})
+ if err == nil {
+ t.Fatal("expected validation error on whitespace candidates")
+ }
+}
+
+func TestLaunchWithFallback_DedupesCandidates(t *testing.T) {
+ fastPolling(t)
+ fl := fakeLauncherFor([]scriptedOutcome{
+ {target: "chrome", succeed: true},
+ })
+
+ if _, err := launchWithFallbackForTest(fl, []string{"chrome", "chrome", " chrome "}); err != nil {
+ t.Fatalf("LaunchWithFallback returned error: %v", err)
+ }
+ if len(fl.calls) != 1 {
+ t.Errorf("expected dedup to reduce to 1 attempt, got %d", len(fl.calls))
+ }
+}
+
+func TestIsRecoverable(t *testing.T) {
+ recoverable := []LaunchFailureReason{
+ ReasonStartupTimeout,
+ ReasonProcessExited,
+ ReasonBinaryMissing,
+ ReasonCDPConnectFail,
+ ReasonHealthCheckTimeout,
+ }
+ for _, r := range recoverable {
+ if !IsRecoverable(r) {
+ t.Errorf("expected %q to be recoverable", string(r))
+ }
+ }
+ if IsRecoverable(ReasonUnknown) {
+ t.Errorf("ReasonUnknown must not be recoverable")
+ }
+ if IsRecoverable(LaunchFailureReason("not_a_reason")) {
+ t.Errorf("arbitrary string must not be recoverable")
+ }
+}
+
+func TestDedupCandidates(t *testing.T) {
+ got := dedupCandidates([]string{"a", " a", "b", "", "c", "b"})
+ want := []string{"a", "b", "c"}
+ if !equalStrings(got, want) {
+ t.Errorf("dedupCandidates = %v, want %v", got, want)
+ }
+}
+
+func equalStrings(a, b []string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for i := range a {
+ if a[i] != b[i] {
+ return false
+ }
+ }
+ return true
+}
+
+var _ = errors.New
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index ffbd63ec..ddd686ec 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -59,12 +59,16 @@ type Orchestrator struct {
// tabsCache stores per-instance snapshots of /tabs results to absorb
// repeated dashboard visibility queries. Routing never reads it.
- tabsCache *TabsCache
- portAllocator *PortAllocator
- idMgr *ids.Manager
- eventHandlers []EventHandler
- instanceMgr *instance.Manager
- runtimeCfg *config.RuntimeConfig
+ tabsCache *TabsCache
+ portAllocator *PortAllocator
+ idMgr *ids.Manager
+ eventHandlers []EventHandler
+ instanceMgr *instance.Manager
+ runtimeCfg *config.RuntimeConfig
+ fallbackLauncher Launcher
+
+ // attachHealthCheckTimeout overrides the default health-check timeout in tests.
+ attachHealthCheckTimeout time.Duration
}
// OnEvent adds an event handler for instance lifecycle events.
@@ -103,11 +107,31 @@ type InstanceInternal struct {
logBuf *ringBuffer
requestedSecurityPolicy *bridge.SecurityPolicy
+
+ requestedBrowserTarget string
+ resolvedBrowserTarget string
+ browserProvider string
+ effectiveBinary string
+
+ lastFailureReason LaunchFailureReason
}
type LaunchOptions struct {
ExtensionPaths []string
SecurityPolicy *bridge.SecurityPolicy
+
+ RequestedBrowserTarget string
+ BrowserTarget string
+ BrowserProvider string
+}
+
+type AttachOptions struct {
+ BrowserTarget string
+ BrowserProvider string
+}
+
+var waitForChildBridgeHealthyFunc = func(o *Orchestrator, inst *InstanceInternal, timeout time.Duration) error {
+ return o.waitForChildBridgeHealthy(inst, timeout)
}
// generateInternalToken returns a random hex string used as the shared
@@ -349,9 +373,10 @@ func installStableBinary(src, dst string) error {
}
func (o *Orchestrator) Launch(name, port string, headless bool, extensionPaths []string) (*bridge.Instance, error) {
- return o.LaunchWithOptions(name, port, headless, LaunchOptions{
+ opts := LaunchOptions{
ExtensionPaths: extensionPaths,
- })
+ }
+ return o.LaunchWithTargetSelection(name, port, headless, "", nil, opts)
}
func (o *Orchestrator) LaunchWithOptions(name, port string, headless bool, opts LaunchOptions) (*bridge.Instance, error) {
@@ -447,7 +472,17 @@ func (o *Orchestrator) LaunchWithOptions(name, port string, headless bool, opts
requestedPolicy := cloneSecurityPolicy(opts.SecurityPolicy)
effectivePolicy := effectiveSecurityPolicy(o.runtimeCfg, requestedPolicy)
- childConfigPath, err := o.writeChildConfig(port, cdpPort, profilePath, instanceStateDir, headless, opts.ExtensionPaths, effectivePolicy)
+ // Target-aware launch only applies in orchestrator mode; direct-bridge path reads the global RuntimeConfig.
+ effectiveCfg := o.runtimeCfg
+ if strings.TrimSpace(opts.BrowserTarget) != "" {
+ resolved, err := config.ResolveExplicitBrowserTarget(o.runtimeCfg, opts.BrowserTarget)
+ if err != nil {
+ return nil, err
+ }
+ effectiveCfg = resolved.Config
+ }
+
+ childConfigPath, err := o.writeChildConfig(effectiveCfg, port, cdpPort, profilePath, instanceStateDir, headless, opts.ExtensionPaths, effectivePolicy)
if err != nil {
return nil, fmt.Errorf("write child config: %w", err)
}
@@ -471,16 +506,18 @@ func (o *Orchestrator) LaunchWithOptions(name, port string, headless bool, opts
inst := &InstanceInternal{
Instance: bridge.Instance{
- ID: instanceID,
- ProfileID: profileID,
- ProfileName: name,
- Port: port,
- URL: o.childInstanceBaseURL(port),
- Mode: bridge.ModeFromHeadless(headless),
- Headless: headless,
- Status: "starting",
- StartTime: time.Now(),
- SecurityPolicy: effectivePolicy,
+ ID: instanceID,
+ ProfileID: profileID,
+ ProfileName: name,
+ Port: port,
+ URL: o.childInstanceBaseURL(port),
+ Mode: bridge.ModeFromHeadless(headless),
+ Headless: headless,
+ Status: "starting",
+ StartTime: time.Now(),
+ SecurityPolicy: effectivePolicy,
+ BrowserTarget: opts.BrowserTarget,
+ BrowserProvider: opts.BrowserProvider,
},
URL: o.childInstanceBaseURL(port),
cdpPort: cdpPort,
@@ -488,6 +525,10 @@ func (o *Orchestrator) LaunchWithOptions(name, port string, headless bool, opts
logBuf: logBuf,
requestedSecurityPolicy: requestedPolicy,
+ requestedBrowserTarget: opts.RequestedBrowserTarget,
+ resolvedBrowserTarget: opts.BrowserTarget,
+ browserProvider: opts.BrowserProvider,
+ effectiveBinary: effectiveBinaryFromCfg(effectiveCfg),
}
o.mu.Lock()
@@ -522,8 +563,12 @@ func portConflictError(port string, inspection PortInspection) error {
return fmt.Errorf("instance port %s is already in use on this machine", port)
}
-func (o *Orchestrator) writeChildConfig(port string, cdpPort int, profilePath, instanceStateDir string, headless bool, extensionPaths []string, securityPolicy *bridge.SecurityPolicy) (string, error) {
- fc := config.FileConfigFromRuntime(o.runtimeCfg)
+// buildChildFileConfig builds the per-child FileConfig; nil effectiveCfg falls back to o.runtimeCfg.
+func (o *Orchestrator) buildChildFileConfig(effectiveCfg *config.RuntimeConfig, port string, cdpPort int, profilePath, instanceStateDir string, headless bool, extensionPaths []string, securityPolicy *bridge.SecurityPolicy) config.FileConfig {
+ if effectiveCfg == nil {
+ effectiveCfg = o.runtimeCfg
+ }
+ fc := config.FileConfigFromRuntime(effectiveCfg)
fc.Server.Port = port
fc.Server.StateDir = instanceStateDir
activityEnabled := false
@@ -557,6 +602,11 @@ func (o *Orchestrator) writeChildConfig(port string, cdpPort int, profilePath, i
}
fc.Browser.ExtensionPaths = unique
}
+ return fc
+}
+
+func (o *Orchestrator) writeChildConfig(effectiveCfg *config.RuntimeConfig, port string, cdpPort int, profilePath, instanceStateDir string, headless bool, extensionPaths []string, securityPolicy *bridge.SecurityPolicy) (string, error) {
+ fc := o.buildChildFileConfig(effectiveCfg, port, cdpPort, profilePath, instanceStateDir, headless, extensionPaths, securityPolicy)
configPath := filepath.Join(instanceStateDir, "config.json")
data, err := json.MarshalIndent(fc, "", " ")
@@ -572,6 +622,34 @@ func (o *Orchestrator) writeChildConfig(port string, cdpPort int, profilePath, i
return configPath, nil
}
+// writeAttachChildConfig writes a minimal child config for a CDP-attach bridge; RemoteCDPURL is passed via CLI flags.
+func (o *Orchestrator) writeAttachChildConfig(port, provider, stateDir string) (string, error) {
+ fc := config.FileConfigFromRuntime(o.runtimeCfg)
+ fc.Server.Port = port
+ fc.Server.StateDir = stateDir
+ activityEnabled := false
+ fc.Observability.Activity.Enabled = &activityEnabled
+ fc.Browser.Provider = provider
+ attachDisabled := false
+ fc.Security.Attach = config.AttachConfig{
+ Enabled: &attachDisabled,
+ ForwardProxyAuth: &attachDisabled,
+ }
+
+ configPath := filepath.Join(stateDir, "config.json")
+ data, err := json.MarshalIndent(fc, "", " ")
+ if err != nil {
+ return "", err
+ }
+ if err := os.WriteFile(configPath, data, 0600); err != nil {
+ return "", err
+ }
+ if err := os.Chmod(configPath, 0600); err != nil {
+ return "", err
+ }
+ return configPath, nil
+}
+
func effectiveSecurityPolicy(cfg *config.RuntimeConfig, requested *bridge.SecurityPolicy) *bridge.SecurityPolicy {
var merged []string
if cfg != nil {
@@ -617,6 +695,13 @@ func mergeAllowedDomains(base []string, extras []string) []string {
return out
}
+func effectiveBinaryFromCfg(cfg *config.RuntimeConfig) string {
+ if cfg == nil {
+ return ""
+ }
+ return cfg.ChromeBinary
+}
+
func intPtr(v int) *int {
if v <= 0 {
return nil
@@ -642,6 +727,12 @@ func (o *Orchestrator) attachExternalInstance(name string, inst bridge.Instance,
existing.Status = "running"
existing.Error = ""
existing.StartTime = time.Now()
+ if inst.BrowserTarget != "" {
+ existing.BrowserTarget = inst.BrowserTarget
+ }
+ if inst.BrowserProvider != "" {
+ existing.BrowserProvider = inst.BrowserProvider
+ }
result := existing.Instance
o.mu.Unlock()
@@ -675,48 +766,221 @@ func (o *Orchestrator) attachExternalInstance(name string, inst bridge.Instance,
return &internal.Instance, true, nil
}
-// Attach connects to an externally managed Chrome instance via CDP URL.
-// Unlike Launch, this does not start a Chrome process - it only registers
-// the external instance for tracking and proxying.
+// Attach wraps an externally-managed browser via a child bridge; the external process is never killed on Stop.
func (o *Orchestrator) Attach(name, cdpURL string) (*bridge.Instance, error) {
- inst, _, err := o.attachExternalInstance(name, bridge.Instance{
- Attached: true,
- AttachType: "cdp",
- CdpURL: cdpURL,
- URL: cdpURL,
- Mode: bridge.ModeFromHeadless(false),
- }, "")
+ return o.AttachWithProvider(name, cdpURL, "")
+}
+
+// AttachWithProvider is Attach with an explicit provider ("" defaults to chrome).
+func (o *Orchestrator) AttachWithProvider(name, cdpURL, provider string) (*bridge.Instance, error) {
+ return o.AttachWithOptions(name, cdpURL, AttachOptions{BrowserProvider: provider})
+}
+
+// AttachWithOptions wraps an externally-managed browser and records its resolved browser target.
+func (o *Orchestrator) AttachWithOptions(name, cdpURL string, opts AttachOptions) (*bridge.Instance, error) {
+ if err := profiles.ValidateProfileName(name); err != nil {
+ return nil, err
+ }
+ if strings.TrimSpace(cdpURL) == "" {
+ return nil, fmt.Errorf("cdpUrl is required")
+ }
+ if err := o.validateAttachURL(cdpURL); err != nil {
+ return nil, err
+ }
+ resolved, err := o.resolveAttachOptions(opts, config.BrowserProviderChrome)
if err != nil {
return nil, err
}
- slog.Info("attached to external Chrome", "id", inst.ID, "name", name, "cdpUrl", internalurls.RedactForLog(cdpURL))
+ bridgePort, err := o.portAllocator.AllocatePort()
+ if err != nil {
+ return nil, fmt.Errorf("failed to allocate bridge port: %w", err)
+ }
+ released := false
+ defer func() {
+ if !released {
+ o.portAllocator.ReleasePort(bridgePort)
+ }
+ }()
+ portStr := strconv.Itoa(bridgePort)
- // Emit event
- o.emitEvent("instance.attached", inst)
- return inst, nil
+ profileID := o.idMgr.ProfileID(name)
+ instanceID := o.idMgr.InstanceID(profileID, name)
+
+ o.mu.Lock()
+ for _, existing := range o.instances {
+ if existing.ProfileName == name && instanceIsActive(existing) {
+ o.mu.Unlock()
+ return nil, fmt.Errorf("instance with name %q already exists", name)
+ }
+ }
+ o.mu.Unlock()
+
+ // RemoteCDPURL/RemoteBrowserName are passed via CLI flags rather than persisted.
+ stateDir := filepath.Join(o.baseDir, "attach", instanceID)
+ if err := os.MkdirAll(stateDir, 0700); err != nil {
+ return nil, fmt.Errorf("create attach state dir: %w", err)
+ }
+ if err := os.Chmod(stateDir, 0700); err != nil {
+ return nil, fmt.Errorf("set attach state dir permissions: %w", err)
+ }
+ childConfigPath, err := o.writeAttachChildConfig(portStr, resolved.BrowserProvider, stateDir)
+ if err != nil {
+ return nil, fmt.Errorf("write attach child config: %w", err)
+ }
+
+ envOverrides := map[string]string{
+ "PINCHTAB_PORT": portStr,
+ "PINCHTAB_CONFIG": childConfigPath,
+ }
+ if o.internalToken != "" {
+ envOverrides["PINCHTAB_INTERNAL_TOKEN"] = o.internalToken
+ }
+ env := mergeEnvWithOverrides(filterEnvWithPrefixes(os.Environ(), "PINCHTAB_"), envOverrides)
+
+ logBuf := newRingBuffer(256 * 1024)
+ args := []string{
+ "bridge",
+ "--cdp-attach", cdpURL,
+ "--browser-provider", resolved.BrowserProvider,
+ "--remote-browser-name", name,
+ }
+ slog.Info("starting CDP attach bridge child",
+ "id", instanceID, "name", name, "port", portStr, "provider", resolved.BrowserProvider, "browserTarget", resolved.BrowserTarget,
+ "cdpUrl", internalurls.RedactForLog(cdpURL),
+ )
+ cmd, err := o.runner.Run(context.Background(), o.binary, args, env, logBuf, logBuf)
+ if err != nil {
+ return nil, fmt.Errorf("failed to start CDP attach bridge: %w", err)
+ }
+
+ baseURL := o.childInstanceBaseURL(portStr)
+ internal := &InstanceInternal{
+ Instance: bridge.Instance{
+ ID: instanceID,
+ ProfileID: profileID,
+ ProfileName: name,
+ Port: portStr,
+ URL: baseURL,
+ Mode: bridge.ModeFromHeadless(false),
+ Headless: false,
+ Status: "starting",
+ StartTime: time.Now(),
+ Attached: true,
+ AttachType: "cdp-bridge",
+ CdpURL: cdpURL,
+ BrowserTarget: resolved.BrowserTarget,
+ BrowserProvider: resolved.BrowserProvider,
+ },
+ URL: baseURL,
+ cmd: cmd,
+ logBuf: logBuf,
+
+ requestedBrowserTarget: strings.TrimSpace(opts.BrowserTarget),
+ resolvedBrowserTarget: resolved.BrowserTarget,
+ browserProvider: resolved.BrowserProvider,
+ }
+
+ o.mu.Lock()
+ o.instances[instanceID] = internal
+ o.mu.Unlock()
+ released = true
+
+ go o.monitor(internal)
+
+ healthTimeout := o.attachHealthCheckTimeout
+ if healthTimeout <= 0 {
+ healthTimeout = 15 * time.Second
+ }
+ if err := waitForChildBridgeHealthyFunc(o, internal, healthTimeout); err != nil {
+ tail := tailChildLog(logBuf, 20)
+ slog.Warn("CDP attach bridge did not become healthy in time; tearing down child bridge", "id", instanceID, "err", err, "childLogTail", tail)
+ if stopErr := o.Stop(instanceID); stopErr != nil {
+ slog.Warn("failed to tear down unhealthy CDP attach bridge", "id", instanceID, "err", stopErr)
+ }
+ if tail != "" {
+ return nil, fmt.Errorf("CDP attach bridge did not become healthy: %w; child log tail:\n%s", err, tail)
+ }
+ return nil, fmt.Errorf("CDP attach bridge did not become healthy: %w", err)
+ }
+
+ result := internal.Instance
+ slog.Info("attached external browser via CDP bridge",
+ "id", result.ID, "name", name, "provider", resolved.BrowserProvider, "browserTarget", resolved.BrowserTarget,
+ "url", internalurls.RedactForLog(result.URL),
+ "cdpUrl", internalurls.RedactForLog(cdpURL),
+ )
+ o.emitEvent("instance.attached", &result)
+ return &result, nil
+}
+
+// waitForChildBridgeHealthy polls the child /health until OK or the deadline elapses.
+func (o *Orchestrator) waitForChildBridgeHealthy(inst *InstanceInternal, timeout time.Duration) error {
+ deadline := time.Now().Add(timeout)
+ healthURL := strings.TrimRight(inst.URL, "/") + "/health"
+ for time.Now().Before(deadline) {
+ req, _ := http.NewRequest(http.MethodGet, healthURL, nil)
+ o.applyInstanceAuth(req, inst)
+ resp, err := o.client.Do(req)
+ if err == nil {
+ _ = resp.Body.Close()
+ if resp.StatusCode == http.StatusOK {
+ o.mu.Lock()
+ inst.Status = "running"
+ o.mu.Unlock()
+ return nil
+ }
+ }
+ time.Sleep(250 * time.Millisecond)
+ }
+ return fmt.Errorf("child bridge health check timed out after %v", timeout)
}
// AttachBridge registers an already-running bridge server as an attached instance.
// If a bridge with the same name is already attached, it is updated in place (upsert)
// provided the caller presents the current bridge token.
func (o *Orchestrator) AttachBridge(name, baseURL, token string) (*bridge.Instance, bool, error) {
+ return o.AttachBridgeWithOptions(name, baseURL, token, AttachOptions{})
+}
+
+// AttachBridgeWithOptions registers an already-running bridge server with target metadata.
+func (o *Orchestrator) AttachBridgeWithOptions(name, baseURL, token string, opts AttachOptions) (*bridge.Instance, bool, error) {
+ if err := o.validateAttachURL(baseURL); err != nil {
+ return nil, false, err
+ }
+ preserveExistingTarget := strings.TrimSpace(opts.BrowserTarget) == "" &&
+ strings.TrimSpace(opts.BrowserProvider) == "" &&
+ o.hasActiveAttachedBridge(name)
+ resolved, err := o.resolveAttachOptions(opts, "")
+ if err != nil {
+ return nil, false, err
+ }
+ if preserveExistingTarget {
+ resolved.BrowserTarget = ""
+ resolved.BrowserProvider = ""
+ }
+
normalizedBaseURL := strings.TrimRight(baseURL, "/")
if parsed, err := url.Parse(normalizedBaseURL); err == nil && parsed.Scheme != "" && parsed.Host != "" {
normalizedBaseURL = parsed.Scheme + "://" + parsed.Host
}
inst, created, err := o.attachExternalInstance(name, bridge.Instance{
- Attached: true,
- AttachType: "bridge",
- URL: normalizedBaseURL,
- Mode: bridge.ModeFromHeadless(false),
+ Attached: true,
+ AttachType: "bridge",
+ URL: normalizedBaseURL,
+ Mode: bridge.ModeFromHeadless(false),
+ BrowserTarget: resolved.BrowserTarget,
+ BrowserProvider: resolved.BrowserProvider,
}, token)
if err != nil {
return nil, false, err
}
- slog.Info("attached to external bridge", "id", inst.ID, "name", name, "url", internalurls.RedactForLog(inst.URL))
+ slog.Info("attached to external bridge",
+ "id", inst.ID, "name", name, "browserTarget", inst.BrowserTarget, "provider", inst.BrowserProvider,
+ "url", internalurls.RedactForLog(inst.URL),
+ )
o.emitEvent("instance.attached", inst)
if created {
o.mu.RLock()
@@ -729,6 +993,72 @@ func (o *Orchestrator) AttachBridge(name, baseURL, token string) (*bridge.Instan
return inst, created, nil
}
+func (o *Orchestrator) hasActiveAttachedBridge(name string) bool {
+ o.mu.RLock()
+ defer o.mu.RUnlock()
+ for _, existing := range o.instances {
+ if existing.ProfileName == name && instanceIsActive(existing) && existing.Attached && existing.AttachType == "bridge" {
+ return true
+ }
+ }
+ return false
+}
+
+func (o *Orchestrator) resolveAttachOptions(opts AttachOptions, defaultProvider string) (AttachOptions, error) {
+ requestedTarget := strings.TrimSpace(opts.BrowserTarget)
+ requestedProvider := strings.TrimSpace(opts.BrowserProvider)
+
+ explicitProvider := requestedProvider != ""
+ parsedProvider := ""
+ if explicitProvider {
+ provider, err := config.ParseBrowserProvider(requestedProvider)
+ if err != nil {
+ return AttachOptions{}, err
+ }
+ parsedProvider = provider
+ }
+
+ if o.runtimeCfg == nil || len(o.runtimeCfg.Targets) == 0 {
+ if parsedProvider == "" && defaultProvider != "" {
+ provider, err := config.ParseBrowserProvider(defaultProvider)
+ if err != nil {
+ return AttachOptions{}, err
+ }
+ parsedProvider = provider
+ }
+ if requestedTarget != "" {
+ return AttachOptions{}, fmt.Errorf("no browser targets configured; cannot resolve %q", requestedTarget)
+ }
+ return AttachOptions{BrowserProvider: parsedProvider}, nil
+ }
+
+ var resolved *config.ResolvedBrowserTarget
+ var err error
+ if strings.TrimSpace(requestedTarget) == "" {
+ resolved, err = config.ResolveDefaultBrowserTarget(o.runtimeCfg)
+ } else {
+ resolved, err = config.ResolveExplicitBrowserTarget(o.runtimeCfg, requestedTarget)
+ }
+ if err != nil {
+ return AttachOptions{}, err
+ }
+ target, targetProvider := "", ""
+ if resolved != nil && !resolved.Legacy {
+ target = resolved.Name
+ targetProvider = resolved.Provider
+ }
+ if explicitProvider && targetProvider != "" && parsedProvider != targetProvider {
+ return AttachOptions{}, fmt.Errorf("browser provider %q conflicts with browserTarget %q provider %q", parsedProvider, target, targetProvider)
+ }
+ if targetProvider == "" {
+ targetProvider = parsedProvider
+ }
+ if targetProvider == "" {
+ targetProvider = config.BrowserProviderChrome
+ }
+ return AttachOptions{BrowserTarget: target, BrowserProvider: targetProvider}, nil
+}
+
func (o *Orchestrator) Stop(id string) error {
o.mu.Lock()
inst, ok := o.instances[id]
@@ -842,6 +1172,21 @@ func (o *Orchestrator) markStopped(id string) {
return
}
+ profileName := inst.ProfileName
+ delete(o.instances, id)
+ o.mu.Unlock()
+
+ o.releaseInstancePorts(id, inst)
+ o.removeInstanceFromManager(id)
+
+ slog.Info("instance stopped and removed", "id", id, "profile", profileName)
+ o.cleanupStoppedProfile(profileName)
+}
+
+func (o *Orchestrator) releaseInstancePorts(id string, inst *InstanceInternal) {
+ if o == nil || o.portAllocator == nil || inst == nil {
+ return
+ }
portStr := inst.Port
if portInt, err := strconv.Atoi(portStr); err == nil {
o.portAllocator.ReleasePort(portInt)
@@ -851,18 +1196,16 @@ func (o *Orchestrator) markStopped(id string) {
o.portAllocator.ReleasePort(inst.cdpPort)
slog.Debug("released chrome debug port", "id", id, "port", inst.cdpPort)
}
+}
- profileName := inst.ProfileName
- delete(o.instances, id)
- o.mu.Unlock()
-
- if o.instanceMgr != nil {
+func (o *Orchestrator) removeInstanceFromManager(id string) {
+ if o != nil && o.instanceMgr != nil {
o.instanceMgr.Locator.InvalidateInstance(id)
o.instanceMgr.Repo.Remove(id)
}
+}
- slog.Info("instance stopped and removed", "id", id, "profile", profileName)
-
+func (o *Orchestrator) cleanupStoppedProfile(profileName string) {
// Kill any orphaned Chrome processes using this profile's directory.
// Chrome spawns helpers (GPU, renderer) in their own process groups,
// so killing the bridge process group doesn't reach them.
@@ -929,6 +1272,20 @@ func (o *Orchestrator) Logs(id string) (string, error) {
}
func (o *Orchestrator) FirstRunningURL() string {
+ return o.firstRunningURL(nil)
+}
+
+func (o *Orchestrator) FirstRunningURLForBrowserTarget(target string) string {
+ target = strings.TrimSpace(target)
+ if target == "" {
+ return o.FirstRunningURL()
+ }
+ return o.firstRunningURL(func(inst *InstanceInternal) bool {
+ return inst != nil && inst.BrowserTarget == target
+ })
+}
+
+func (o *Orchestrator) firstRunningURL(match func(*InstanceInternal) bool) string {
o.mu.RLock()
defer o.mu.RUnlock()
// Collect running instances and sort by start time for determinism.
@@ -943,6 +1300,9 @@ func (o *Orchestrator) FirstRunningURL() string {
if inst.URL == "" {
continue
}
+ if match != nil && !match(inst) {
+ continue
+ }
candidates = append(candidates, candidate{start: inst.StartTime, url: inst.URL})
}
}
@@ -958,6 +1318,32 @@ func (o *Orchestrator) FirstRunningURL() string {
return candidates[0].url
}
+func (o *Orchestrator) FirstRunningURLForRequest(r *http.Request) (string, int, error) {
+ requested := ExtractRequestedBrowserTarget(r)
+ if requested == "" {
+ resolved, err := config.ResolveDefaultBrowserTarget(o.runtimeCfg)
+ if err != nil {
+ return "", http.StatusBadRequest, err
+ }
+ if resolved != nil && !resolved.Legacy {
+ if resolved.Name == "" {
+ return "", http.StatusBadRequest, fmt.Errorf("no default browser target configured and none requested")
+ }
+ return o.FirstRunningURLForBrowserTarget(resolved.Name), 0, nil
+ }
+ return o.FirstRunningURL(), 0, nil
+ }
+ resolved, err := config.ResolveExplicitBrowserTarget(o.runtimeCfg, requested)
+ if err != nil {
+ return "", http.StatusBadRequest, err
+ }
+ target := resolved.Name
+ if url := o.FirstRunningURLForBrowserTarget(target); url != "" {
+ return url, 0, nil
+ }
+ return "", http.StatusConflict, fmt.Errorf("no running instance for browserTarget %q", target)
+}
+
// instanceTabsCached returns the tab list for inst using the per-instance
// cache. fresh=true forces a bypass and refresh. Returned tabs are
// InstanceTab-shaped (with InstanceID set) so callers can hand them
@@ -1013,6 +1399,36 @@ func (o *Orchestrator) allTabs(fresh bool) []bridge.InstanceTab {
return all
}
+// FindInstanceByTab returns the running instance owning tabID, or (nil,false).
+func (o *Orchestrator) FindInstanceByTab(tabID string) (*bridge.Instance, bool) {
+ if tabID == "" {
+ return nil, false
+ }
+
+ o.mu.RLock()
+ instances := make([]*InstanceInternal, 0, len(o.instances))
+ for _, inst := range o.instances {
+ if inst.Status == "running" && instanceIsActive(inst) {
+ instances = append(instances, inst)
+ }
+ }
+ o.mu.RUnlock()
+
+ for _, inst := range instances {
+ tabs, err := o.instanceTabsCached(inst, false)
+ if err != nil {
+ continue
+ }
+ for _, tab := range tabs {
+ if tab.ID == tabID {
+ copyInst := inst.Instance
+ return &copyInst, true
+ }
+ }
+ }
+ return nil, false
+}
+
func (o *Orchestrator) AllMetrics() []types.InstanceMetrics {
o.mu.RLock()
instances := make([]*InstanceInternal, 0)
diff --git a/internal/orchestrator/orchestrator_test.go b/internal/orchestrator/orchestrator_test.go
index 635722bd..984132f6 100644
--- a/internal/orchestrator/orchestrator_test.go
+++ b/internal/orchestrator/orchestrator_test.go
@@ -3,6 +3,7 @@ package orchestrator
import (
"bytes"
"encoding/json"
+ "fmt"
"net/http"
"net/http/httptest"
"net/url"
@@ -11,6 +12,7 @@ import (
"strconv"
"strings"
"testing"
+ "time"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/config"
@@ -36,6 +38,14 @@ func stubPortAvailability(t *testing.T, fn func(int) bool) {
})
}
+func allowAttachForTest(o *Orchestrator, schemes, hosts []string) {
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ AttachEnabled: true,
+ AttachAllowSchemes: schemes,
+ AttachAllowHosts: hosts,
+ })
+}
+
func TestOrchestrator_Launch_Lifecycle(t *testing.T) {
old := processAliveFunc
processAliveFunc = func(pid int) bool { return pid > 0 }
@@ -425,9 +435,24 @@ func findSubstring(s, substr string) bool {
return false
}
+func stubAttachBridgeHealthy(t *testing.T) {
+ t.Helper()
+ old := waitForChildBridgeHealthyFunc
+ waitForChildBridgeHealthyFunc = func(o *Orchestrator, inst *InstanceInternal, timeout time.Duration) error {
+ o.mu.Lock()
+ inst.Status = "running"
+ o.mu.Unlock()
+ return nil
+ }
+ t.Cleanup(func() { waitForChildBridgeHealthyFunc = old })
+}
+
func TestOrchestrator_Attach(t *testing.T) {
+ stubAttachBridgeHealthy(t)
runner := &mockRunner{portAvail: true}
o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ allowAttachForTest(o, []string{"ws"}, []string{"localhost"})
+ o.attachHealthCheckTimeout = 50 * time.Millisecond
cdpURL := "ws://localhost:9222/devtools/browser/abc123"
inst, err := o.Attach("my-external-chrome", cdpURL)
@@ -441,8 +466,14 @@ func TestOrchestrator_Attach(t *testing.T) {
if inst.CdpURL != cdpURL {
t.Errorf("expected CdpURL %q, got %q", cdpURL, inst.CdpURL)
}
- if inst.Status != "running" {
- t.Errorf("expected status running, got %s", inst.Status)
+ if inst.AttachType != "cdp-bridge" {
+ t.Errorf("expected AttachType cdp-bridge, got %q", inst.AttachType)
+ }
+ if !strings.HasPrefix(inst.URL, "http://") {
+ t.Errorf("expected http:// bridge URL, got %q", inst.URL)
+ }
+ if inst.URL == cdpURL {
+ t.Errorf("URL must not be the raw cdpUrl")
}
if inst.ProfileName != "my-external-chrome" {
t.Errorf("expected ProfileName %q, got %q", "my-external-chrome", inst.ProfileName)
@@ -458,24 +489,242 @@ func TestOrchestrator_Attach(t *testing.T) {
}
}
+func TestOrchestrator_Attach_SpawnsChildBridgeWithCDPFlags(t *testing.T) {
+ stubAttachBridgeHealthy(t)
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ allowAttachForTest(o, []string{"ws"}, []string{"127.0.0.1"})
+ o.attachHealthCheckTimeout = 30 * time.Millisecond
+
+ cdpURL := "ws://127.0.0.1:9222/devtools/browser/abc"
+ if _, err := o.AttachWithProvider("ext-cloak", cdpURL, "cloak"); err != nil {
+ t.Fatalf("AttachWithProvider failed: %v", err)
+ }
+ if !runner.runCalled {
+ t.Fatal("expected runner.Run to be called for child bridge")
+ }
+ args := strings.Join(runner.args, " ")
+ if !strings.Contains(args, "bridge") {
+ t.Fatalf("expected child args to contain 'bridge': %v", runner.args)
+ }
+ if !strings.Contains(args, "--cdp-attach "+cdpURL) {
+ t.Fatalf("expected --cdp-attach flag with cdp url: %v", runner.args)
+ }
+ if !strings.Contains(args, "--browser-provider cloak") {
+ t.Fatalf("expected --browser-provider cloak: %v", runner.args)
+ }
+ if !strings.Contains(args, "--remote-browser-name ext-cloak") {
+ t.Fatalf("expected --remote-browser-name flag: %v", runner.args)
+ }
+}
+
+func TestOrchestrator_AttachWithProviderRejectsUnknownProvider(t *testing.T) {
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ allowAttachForTest(o, []string{"ws"}, []string{"127.0.0.1"})
+
+ _, err := o.AttachWithProvider("ext-cloak", "ws://127.0.0.1:9222/devtools/browser/abc", "cloack")
+ if err == nil {
+ t.Fatal("expected invalid browser provider error")
+ }
+ if !strings.Contains(err.Error(), "invalid browser provider") {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if runner.runCalled {
+ t.Fatal("invalid provider should be rejected before starting child bridge")
+ }
+}
+
+func TestOrchestrator_Attach_PreservesCdpURLMetadata(t *testing.T) {
+ stubAttachBridgeHealthy(t)
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ allowAttachForTest(o, []string{"ws"}, []string{"127.0.0.1"})
+ o.attachHealthCheckTimeout = 30 * time.Millisecond
+
+ cdpURL := "ws://127.0.0.1:9222/devtools/browser/xyz"
+ inst, err := o.Attach("ext", cdpURL)
+ if err != nil {
+ t.Fatalf("Attach failed: %v", err)
+ }
+ if inst.CdpURL != cdpURL {
+ t.Fatalf("CdpURL not preserved: got %q want %q", inst.CdpURL, cdpURL)
+ }
+ if inst.URL == cdpURL {
+ t.Fatal("instance URL must be the HTTP bridge URL, not the raw cdpUrl")
+ }
+ if !strings.HasPrefix(inst.URL, "http://") {
+ t.Fatalf("expected http:// bridge URL, got %q", inst.URL)
+ }
+}
+
func TestOrchestrator_Attach_DuplicateName(t *testing.T) {
+ stubAttachBridgeHealthy(t)
+ old := processAliveFunc
+ processAliveFunc = func(pid int) bool { return pid > 0 }
+ defer func() { processAliveFunc = old }()
+
runner := &mockRunner{portAvail: true}
o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ allowAttachForTest(o, []string{"ws"}, []string{"localhost"})
+ o.attachHealthCheckTimeout = 50 * time.Millisecond
- _, err := o.Attach("chrome1", "ws://localhost:9222/a")
+ _, err := o.Attach("chrome1", "ws://localhost:9222/devtools/browser/a")
if err != nil {
t.Fatalf("First attach failed: %v", err)
}
- _, err = o.Attach("chrome1", "ws://localhost:9222/b")
+ _, err = o.Attach("chrome1", "ws://localhost:9222/devtools/browser/b")
if err == nil {
t.Error("expected error when attaching duplicate name")
}
}
+func TestOrchestrator_Attach_HealthFailureTearsDownChild(t *testing.T) {
+ oldHealth := waitForChildBridgeHealthyFunc
+ waitForChildBridgeHealthyFunc = func(o *Orchestrator, inst *InstanceInternal, timeout time.Duration) error {
+ return fmt.Errorf("boom")
+ }
+ defer func() { waitForChildBridgeHealthyFunc = oldHealth }()
+
+ oldAlive := processAliveFunc
+ processAliveFunc = func(pid int) bool { return false }
+ defer func() { processAliveFunc = oldAlive }()
+
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ allowAttachForTest(o, []string{"ws"}, []string{"localhost"})
+ o.attachHealthCheckTimeout = 30 * time.Millisecond
+
+ _, err := o.Attach("unhealthy", "ws://localhost:9222/devtools/browser/a")
+ if err == nil {
+ t.Fatal("expected attach to fail when child bridge health fails")
+ }
+ if !strings.Contains(err.Error(), "did not become healthy") {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got := o.List(); len(got) != 0 {
+ t.Fatalf("unhealthy attach child was not removed: %+v", got)
+ }
+}
+
+func TestOrchestrator_FirstRunningURLForRequest_UsesBrowserTarget(t *testing.T) {
+ oldAlive := processAliveFunc
+ processAliveFunc = func(pid int) bool { return true }
+ defer func() { processAliveFunc = oldAlive }()
+
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ DefaultTarget: "chrome",
+ Targets: config.BrowserTargetsConfig{
+ "chrome": {Provider: config.BrowserProviderChrome},
+ "cloak": {Provider: config.BrowserProviderCloak},
+ },
+ })
+ now := time.Now()
+ o.instances["chrome"] = &InstanceInternal{
+ Instance: bridge.Instance{ID: "chrome", URL: "http://chrome.local", Status: "running", BrowserTarget: "chrome", StartTime: now},
+ URL: "http://chrome.local",
+ cmd: &mockCmd{pid: 111, isAlive: true},
+ }
+ o.instances["cloak"] = &InstanceInternal{
+ Instance: bridge.Instance{ID: "cloak", URL: "http://cloak.local", Status: "running", BrowserTarget: "cloak", StartTime: now.Add(time.Second)},
+ URL: "http://cloak.local",
+ cmd: &mockCmd{pid: 222, isAlive: true},
+ }
+
+ body := []byte(`{"url":"about:blank","browserTarget":"cloak"}`)
+ req := httptest.NewRequest(http.MethodPost, "/navigate", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ req.ContentLength = int64(len(body))
+
+ url, status, err := o.FirstRunningURLForRequest(req)
+ if err != nil {
+ t.Fatalf("FirstRunningURLForRequest error status=%d err=%v", status, err)
+ }
+ if url != "http://cloak.local" {
+ t.Fatalf("url = %q, want cloak target URL", url)
+ }
+}
+
+func TestOrchestrator_FirstRunningURLForRequest_UsesDefaultTargetWhenOmitted(t *testing.T) {
+ oldAlive := processAliveFunc
+ processAliveFunc = func(pid int) bool { return true }
+ defer func() { processAliveFunc = oldAlive }()
+
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ DefaultTarget: "cloak",
+ Targets: config.BrowserTargetsConfig{
+ "chrome": {Provider: config.BrowserProviderChrome},
+ "cloak": {Provider: config.BrowserProviderCloak},
+ },
+ })
+ now := time.Now()
+ o.instances["chrome"] = &InstanceInternal{
+ Instance: bridge.Instance{ID: "chrome", URL: "http://chrome.local", Status: "running", BrowserTarget: "chrome", StartTime: now},
+ URL: "http://chrome.local",
+ cmd: &mockCmd{pid: 111, isAlive: true},
+ }
+ o.instances["cloak"] = &InstanceInternal{
+ Instance: bridge.Instance{ID: "cloak", URL: "http://cloak.local", Status: "running", BrowserTarget: "cloak", StartTime: now.Add(time.Second)},
+ URL: "http://cloak.local",
+ cmd: &mockCmd{pid: 222, isAlive: true},
+ }
+
+ req := httptest.NewRequest(http.MethodGet, "/text", nil)
+ url, status, err := o.FirstRunningURLForRequest(req)
+ if err != nil {
+ t.Fatalf("FirstRunningURLForRequest error status=%d err=%v", status, err)
+ }
+ if url != "http://cloak.local" {
+ t.Fatalf("url = %q, want default target URL", url)
+ }
+}
+
+func TestOrchestrator_FirstRunningURLForRequest_RejectsUnknownBrowserTarget(t *testing.T) {
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ DefaultTarget: "chrome",
+ Targets: config.BrowserTargetsConfig{
+ "chrome": {Provider: config.BrowserProviderChrome},
+ },
+ })
+ req := httptest.NewRequest(http.MethodGet, "/navigate?browserTarget=ghost", nil)
+
+ _, status, err := o.FirstRunningURLForRequest(req)
+ if err == nil {
+ t.Fatal("expected unknown browserTarget error")
+ }
+ if status != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400", status)
+ }
+}
+
+func TestOrchestrator_FirstRunningURLForRequest_RequestedTargetNotRunningConflicts(t *testing.T) {
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ DefaultTarget: "chrome",
+ Targets: config.BrowserTargetsConfig{
+ "chrome": {Provider: config.BrowserProviderChrome},
+ "cloak": {Provider: config.BrowserProviderCloak},
+ },
+ })
+ req := httptest.NewRequest(http.MethodGet, "/navigate?browserTarget=cloak", nil)
+
+ _, status, err := o.FirstRunningURLForRequest(req)
+ if err == nil {
+ t.Fatal("expected no-running browserTarget error")
+ }
+ if status != http.StatusConflict {
+ t.Fatalf("status = %d, want 409", status)
+ }
+}
+
func TestOrchestrator_AttachBridge(t *testing.T) {
runner := &mockRunner{portAvail: true}
o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ allowAttachForTest(o, []string{"http"}, []string{"10.0.0.8"})
inst, created, err := o.AttachBridge("bridge1", "http://10.0.0.8:9868", "bridge-token")
if err != nil {
@@ -501,6 +750,7 @@ func TestOrchestrator_AttachBridge(t *testing.T) {
func TestOrchestrator_AttachBridge_UpsertsExistingBridge(t *testing.T) {
runner := &mockRunner{portAvail: true}
o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ allowAttachForTest(o, []string{"http"}, []string{"10.0.0.8", "10.0.0.9"})
first, _, err := o.AttachBridge("bridge1", "http://10.0.0.8:9868", "bridge-token-1")
if err != nil {
@@ -540,9 +790,91 @@ func TestOrchestrator_AttachBridge_UpsertsExistingBridge(t *testing.T) {
}
}
+func TestOrchestrator_AttachBridgeWithOptions_UpsertUpdatesBrowserTarget(t *testing.T) {
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ AttachEnabled: true,
+ AttachAllowSchemes: []string{"http"},
+ AttachAllowHosts: []string{"10.0.0.8", "10.0.0.9"},
+ DefaultTarget: "chrome",
+ Targets: config.BrowserTargetsConfig{
+ "chrome": {Provider: config.BrowserProviderChrome},
+ "cloak": {Provider: config.BrowserProviderCloak},
+ },
+ })
+
+ first, _, err := o.AttachBridgeWithOptions("bridge1", "http://10.0.0.8:9868", "bridge-token", AttachOptions{BrowserTarget: "chrome"})
+ if err != nil {
+ t.Fatalf("first AttachBridgeWithOptions failed: %v", err)
+ }
+ if first.BrowserTarget != "chrome" || first.BrowserProvider != config.BrowserProviderChrome {
+ t.Fatalf("first target/provider = %q/%q, want chrome/chrome", first.BrowserTarget, first.BrowserProvider)
+ }
+
+ second, created, err := o.AttachBridgeWithOptions("bridge1", "http://10.0.0.9:9868", "bridge-token", AttachOptions{BrowserTarget: "cloak"})
+ if err != nil {
+ t.Fatalf("second AttachBridgeWithOptions failed: %v", err)
+ }
+ if created {
+ t.Fatal("expected upsert, not create")
+ }
+ if second.ID != first.ID {
+ t.Fatalf("ID = %q, want %q", second.ID, first.ID)
+ }
+ if second.BrowserTarget != "cloak" || second.BrowserProvider != config.BrowserProviderCloak {
+ t.Fatalf("second target/provider = %q/%q, want cloak/cloak", second.BrowserTarget, second.BrowserProvider)
+ }
+
+ list := o.List()
+ if len(list) != 1 {
+ t.Fatalf("expected 1 instance in list, got %d", len(list))
+ }
+ if list[0].BrowserTarget != "cloak" || list[0].BrowserProvider != config.BrowserProviderCloak {
+ t.Fatalf("listed target/provider = %q/%q, want cloak/cloak", list[0].BrowserTarget, list[0].BrowserProvider)
+ }
+}
+
+func TestOrchestrator_AttachBridge_UpsertWithoutTargetPreservesExistingBrowserTarget(t *testing.T) {
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ AttachEnabled: true,
+ AttachAllowSchemes: []string{"http"},
+ AttachAllowHosts: []string{"10.0.0.8", "10.0.0.9"},
+ DefaultTarget: "chrome",
+ Targets: config.BrowserTargetsConfig{
+ "chrome": {Provider: config.BrowserProviderChrome},
+ "cloak": {Provider: config.BrowserProviderCloak},
+ },
+ })
+
+ first, _, err := o.AttachBridgeWithOptions("bridge1", "http://10.0.0.8:9868", "bridge-token", AttachOptions{BrowserTarget: "cloak"})
+ if err != nil {
+ t.Fatalf("first AttachBridgeWithOptions failed: %v", err)
+ }
+ second, created, err := o.AttachBridge("bridge1", "http://10.0.0.9:9868", "bridge-token")
+ if err != nil {
+ t.Fatalf("second AttachBridge failed: %v", err)
+ }
+ if created {
+ t.Fatal("expected upsert, not create")
+ }
+ if second.ID != first.ID {
+ t.Fatalf("ID = %q, want %q", second.ID, first.ID)
+ }
+ if second.BrowserTarget != "cloak" {
+ t.Fatalf("BrowserTarget = %q, want preserved cloak", second.BrowserTarget)
+ }
+ if second.BrowserProvider != config.BrowserProviderCloak {
+ t.Fatalf("BrowserProvider = %q, want preserved cloak", second.BrowserProvider)
+ }
+}
+
func TestOrchestrator_AttachBridge_RejectsTokenMismatch(t *testing.T) {
runner := &mockRunner{portAvail: true}
o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ allowAttachForTest(o, []string{"http"}, []string{"10.0.0.8", "10.0.0.9"})
_, _, err := o.AttachBridge("bridge1", "http://10.0.0.8:9868", "bridge-token-1")
if err != nil {
@@ -632,7 +964,7 @@ func TestValidateAttachURL_RejectsBridgeBaseURLWithPath(t *testing.T) {
if err == nil {
t.Fatal("expected error for attach bridge URL with path")
}
- if !strings.Contains(err.Error(), "must not include a path") {
+ if !strings.Contains(err.Error(), "bare origin or end with /json/version") {
t.Fatalf("unexpected error: %v", err)
}
}
@@ -649,7 +981,7 @@ func TestValidateAttachURL_RejectsBridgeBaseURLWithUserinfo(t *testing.T) {
if err == nil {
t.Fatal("expected error for attach bridge URL with userinfo")
}
- if !strings.Contains(err.Error(), "must not include userinfo") {
+ if !strings.Contains(err.Error(), "userinfo") {
t.Fatalf("unexpected error: %v", err)
}
}
@@ -670,7 +1002,7 @@ func TestValidateAttachURL_RejectsBridgeBaseURLWithQueryOrFragment(t *testing.T)
if err == nil {
t.Fatalf("expected error for attach bridge URL %q", raw)
}
- if !strings.Contains(err.Error(), "must not include query or fragment") {
+ if !strings.Contains(err.Error(), "query or fragment") {
t.Fatalf("unexpected error for %q: %v", raw, err)
}
}
@@ -679,8 +1011,9 @@ func TestValidateAttachURL_RejectsBridgeBaseURLWithQueryOrFragment(t *testing.T)
func TestOrchestrator_AttachBridge_NormalizesBaseURL(t *testing.T) {
runner := &mockRunner{portAvail: true}
o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ allowAttachForTest(o, []string{"http"}, []string{"10.0.0.8"})
- inst, _, err := o.AttachBridge("bridge1", "http://10.0.0.8:9868/?debug=1#frag", "bridge-token")
+ inst, _, err := o.AttachBridge("bridge1", "http://10.0.0.8:9868/", "bridge-token")
if err != nil {
t.Fatalf("AttachBridge failed: %v", err)
}
@@ -689,6 +1022,46 @@ func TestOrchestrator_AttachBridge_NormalizesBaseURL(t *testing.T) {
}
}
+func TestValidateAttachURL_AttachDisabled(t *testing.T) {
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ AttachEnabled: false,
+ AttachAllowHosts: []string{"*"},
+ AttachAllowSchemes: []string{"ws"},
+ })
+ err := o.validateAttachURL("ws://127.0.0.1:9222/devtools/browser/x")
+ if err == nil {
+ t.Fatal("expected error when attach is disabled")
+ }
+ if !strings.Contains(err.Error(), "disabled") {
+ t.Fatalf("unexpected error: %v", err)
+ }
+}
+
+func TestValidateAttachURL_DisallowedHost(t *testing.T) {
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ AttachEnabled: true,
+ AttachAllowHosts: []string{"127.0.0.1"},
+ AttachAllowSchemes: []string{"ws"},
+ })
+ if err := o.validateAttachURL("ws://evil.example/devtools/browser/x"); err == nil {
+ t.Fatal("expected error for disallowed host")
+ }
+}
+
+func TestValidateAttachURL_DisallowedScheme(t *testing.T) {
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ AttachEnabled: true,
+ AttachAllowHosts: []string{"*"},
+ AttachAllowSchemes: []string{"ws"},
+ })
+ if err := o.validateAttachURL("http://127.0.0.1:9222"); err == nil {
+ t.Fatal("expected error for disallowed scheme")
+ }
+}
+
func TestValidateAttachURL_WildcardHost(t *testing.T) {
o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
o.ApplyRuntimeConfig(&config.RuntimeConfig{
diff --git a/internal/orchestrator/process.go b/internal/orchestrator/process.go
index fa9d7326..658af1af 100644
--- a/internal/orchestrator/process.go
+++ b/internal/orchestrator/process.go
@@ -137,3 +137,20 @@ func (rb *ringBuffer) String() string {
defer rb.mu.Unlock()
return string(rb.data)
}
+
+// tailChildLog returns up to maxLines trailing non-empty lines from rb,
+// suitable for embedding in operator-facing error messages.
+func tailChildLog(rb *ringBuffer, maxLines int) string {
+ if rb == nil || maxLines <= 0 {
+ return ""
+ }
+ raw := strings.TrimRight(rb.String(), "\n")
+ if raw == "" {
+ return ""
+ }
+ lines := strings.Split(raw, "\n")
+ if len(lines) > maxLines {
+ lines = lines[len(lines)-maxLines:]
+ }
+ return strings.Join(lines, "\n")
+}
diff --git a/internal/orchestrator/proxy_test.go b/internal/orchestrator/proxy_test.go
index 60463038..28e78935 100644
--- a/internal/orchestrator/proxy_test.go
+++ b/internal/orchestrator/proxy_test.go
@@ -201,6 +201,11 @@ func TestProxyToURL_UsesAttachedBridgeOriginAndAuth(t *testing.T) {
o := NewOrchestrator(t.TempDir())
o.client = backend.Client()
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatalf("parse backend URL: %v", err)
+ }
+ allowAttachForTest(o, []string{"http"}, []string{backendURL.Hostname()})
attached, _, err := o.AttachBridge("bridge1", backend.URL, "bridge-token")
if err != nil {
t.Fatalf("AttachBridge failed: %v", err)
diff --git a/internal/orchestrator/route.go b/internal/orchestrator/route.go
index f023809c..610a25be 100644
--- a/internal/orchestrator/route.go
+++ b/internal/orchestrator/route.go
@@ -1,12 +1,16 @@
package orchestrator
import (
+ "errors"
"fmt"
+ "log/slog"
"net/http"
"strings"
+ "time"
"github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/handlers"
"github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/session"
@@ -23,6 +27,101 @@ const (
RoutingDecisionFallback RoutingDecision = "fallback"
)
+const routeInstanceReadyWait = 30 * time.Second
+
+var routeInstanceReadyPollInterval = 500 * time.Millisecond
+
+// RouteForRequest resolves a shorthand request to a running instance URL,
+// launching the selected target when none is available. This centralizes the
+// target-aware auto-launch behavior used by strategies such as simple.
+func (o *Orchestrator) RouteForRequest(r *http.Request) (string, int, error) {
+ if o == nil {
+ return "", http.StatusServiceUnavailable, fmt.Errorf("no orchestrator configured")
+ }
+
+ requestedTarget := ExtractRequestedBrowserTarget(r)
+ if requestedTarget != "" {
+ resolvedTarget, _, err := o.ResolveRequestedBrowserTarget(requestedTarget)
+ if err != nil {
+ return "", statusForRouteLaunchSelectionError(err), err
+ }
+ if target := o.FirstRunningURLForBrowserTarget(resolvedTarget); target != "" {
+ return target, 0, nil
+ }
+ return o.launchAndWaitForRequestRoute(autoLaunchProfileName(resolvedTarget), requestedTarget)
+ }
+
+ target, status, err := o.FirstRunningURLForRequest(r)
+ if err != nil {
+ return "", status, err
+ }
+ if target != "" {
+ return target, 0, nil
+ }
+
+ return o.launchAndWaitForRequestRoute("default", "")
+}
+
+func (o *Orchestrator) launchAndWaitForRequestRoute(profileName, requestedTarget string) (string, int, error) {
+ slog.Info("request route: no running instance, auto-launching", "profile", profileName, "browserTarget", requestedTarget)
+ launched, err := o.LaunchWithTargetSelection(profileName, "", true, requestedTarget, nil, LaunchOptions{})
+ if err != nil {
+ status := statusForRouteLaunchSelectionError(err)
+ return "", status, fmt.Errorf("auto-launch failed: %w", err)
+ }
+
+ if launched.URL == "" {
+ return "", http.StatusServiceUnavailable, fmt.Errorf("auto-launched instance %q has no URL", launched.ID)
+ }
+ url, err := o.waitForRequestRouteReady(launched.URL, routeInstanceReadyWait)
+ if err != nil {
+ return "", http.StatusServiceUnavailable, err
+ }
+ return url, 0, nil
+}
+
+func (o *Orchestrator) waitForRequestRouteReady(url string, timeout time.Duration) (string, error) {
+ healthURL := strings.TrimRight(url, "/") + "/health"
+ deadline := time.Now().Add(timeout)
+ client := o.client
+ if client == nil {
+ client = http.DefaultClient
+ }
+
+ for time.Now().Before(deadline) {
+ req, _ := http.NewRequest(http.MethodGet, healthURL, nil)
+ resp, err := client.Do(req)
+ if err == nil {
+ _ = resp.Body.Close()
+ if resp.StatusCode == http.StatusOK {
+ return url, nil
+ }
+ }
+ time.Sleep(routeInstanceReadyPollInterval)
+ }
+
+ return "", fmt.Errorf("instance launched but did not become ready in time")
+}
+
+func autoLaunchProfileName(target string) string {
+ target = strings.TrimSpace(target)
+ if target == "" {
+ return "default"
+ }
+ return "default-" + target
+}
+
+func statusForRouteLaunchSelectionError(err error) int {
+ if errors.Is(err, ErrUnknownBrowserTarget) {
+ return http.StatusBadRequest
+ }
+ var exhausted *FallbackExhaustedError
+ if errors.As(err, &exhausted) {
+ return http.StatusBadGateway
+ }
+ return http.StatusServiceUnavailable
+}
+
// WrapShorthand wraps a strategy-supplied fallback handler with the routing
// precedence defined in tab-spec.md:
//
@@ -62,9 +161,18 @@ func (o *Orchestrator) WrapShorthand(fallback http.HandlerFunc) http.HandlerFunc
// routeByTabOwner handles precedence rule 1. Returns true if a response was
// already written (either a successful proxy or an error).
func (o *Orchestrator) routeByTabOwner(w http.ResponseWriter, r *http.Request, tabID string) bool {
+ requestedTarget, status, err := o.requestedBrowserTargetForRoute(r)
+ if err != nil {
+ httpx.Error(w, status, err)
+ return true
+ }
+
// Fast path via locator cache.
if o.instanceMgr != nil {
if inst, err := o.instanceMgr.FindInstanceByTabID(tabID); err == nil && inst != nil {
+ if writeBrowserTargetConflict(w, tabID, inst, requestedTarget) {
+ return true
+ }
if !o.allowCrossInstance(w, r, inst.ID) {
return true
}
@@ -77,6 +185,9 @@ func (o *Orchestrator) routeByTabOwner(w http.ResponseWriter, r *http.Request, t
if o.instanceMgr != nil {
o.instanceMgr.Locator.Register(tabID, internal.ID)
}
+ if writeBrowserTargetConflict(w, tabID, &internal.Instance, requestedTarget) {
+ return true
+ }
if !o.allowCrossInstance(w, r, internal.ID) {
return true
}
@@ -88,6 +199,9 @@ func (o *Orchestrator) routeByTabOwner(w http.ResponseWriter, r *http.Request, t
// — preserves legacy ergonomics for users running `--tab` against a
// just-created tab whose id has not propagated to the dashboard yet.
if only := o.singleRunningInstance(); only != nil {
+ if writeBrowserTargetConflict(w, tabID, &only.Instance, requestedTarget) {
+ return true
+ }
o.proxyToInstanceForRoute(w, r, &only.Instance, tabID, RoutingDecisionFallback)
return true
}
@@ -97,6 +211,43 @@ func (o *Orchestrator) routeByTabOwner(w http.ResponseWriter, r *http.Request, t
return true
}
+func (o *Orchestrator) requestedBrowserTargetForRoute(r *http.Request) (string, int, error) {
+ requested := ExtractRequestedBrowserTarget(r)
+ if requested == "" {
+ return "", 0, nil
+ }
+ resolved, err := config.ResolveExplicitBrowserTarget(o.runtimeCfg, requested)
+ if err != nil {
+ return "", http.StatusBadRequest, err
+ }
+ return resolved.Name, 0, nil
+}
+
+func writeBrowserTargetConflict(w http.ResponseWriter, tabID string, inst *bridge.Instance, requestedTarget string) bool {
+ if requestedTarget == "" || inst == nil || inst.BrowserTarget == "" || inst.BrowserTarget == requestedTarget {
+ return false
+ }
+ detail := fmt.Sprintf("instance %q has browserTarget %q; cannot route with browserTarget %q",
+ inst.ID, inst.BrowserTarget, requestedTarget)
+ if tabID != "" {
+ detail = fmt.Sprintf("tab %q is owned by instance with browserTarget %q; cannot route with browserTarget %q",
+ tabID, inst.BrowserTarget, requestedTarget)
+ }
+ meta := map[string]any{
+ "instanceId": inst.ID,
+ "instanceTarget": inst.BrowserTarget,
+ "requestedTarget": requestedTarget,
+ "instanceProvider": inst.BrowserProvider,
+ }
+ if tabID != "" {
+ meta["tabId"] = tabID
+ }
+ httpx.ErrorCode(w, http.StatusConflict, "browser_target_conflict",
+ detail,
+ false, meta)
+ return true
+}
+
// resolveIdentityBinding implements precedence rules 2 and 3. Public
// session-authenticated requests resolve from the authenticated session
// context. Trusted internal proxy hops resolve from the propagated session
@@ -147,6 +298,16 @@ func (o *Orchestrator) routeToInstanceID(w http.ResponseWriter, r *http.Request,
}
return false
}
+ requestedTarget, status, err := o.requestedBrowserTargetForRoute(r)
+ if err != nil {
+ httpx.Error(w, status, err)
+ return true
+ }
+ if requestedTarget != "" {
+ if internal.BrowserTarget == "" || internal.BrowserTarget != requestedTarget {
+ return false
+ }
+ }
o.proxyToInstanceForRoute(w, r, &internal.Instance, "", decision)
return true
}
diff --git a/internal/orchestrator/route_test.go b/internal/orchestrator/route_test.go
index b48fa2ad..e7689e14 100644
--- a/internal/orchestrator/route_test.go
+++ b/internal/orchestrator/route_test.go
@@ -9,6 +9,7 @@ import (
"github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/handlers"
"github.com/pinchtab/pinchtab/internal/session"
)
@@ -44,6 +45,55 @@ func newBackendInstance(t *testing.T, o *Orchestrator, instanceID string) (*http
return srv, gotPath
}
+func TestRouteForRequest_AutoLaunchesRequestedBrowserTarget(t *testing.T) {
+ alwaysAlive(t)
+ stubPortAvailability(t, func(int) bool { return true })
+
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ o.client = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(bytes.NewReader([]byte(`{"status":"ok"}`))),
+ Header: make(http.Header),
+ Request: req,
+ }, nil
+ })}
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ DefaultTarget: "chrome",
+ Targets: config.BrowserTargetsConfig{
+ "chrome": {Provider: config.BrowserProviderChrome},
+ "cloak": {Provider: config.BrowserProviderCloak},
+ },
+ })
+
+ body := []byte(`{"url":"about:blank","browserTarget":"cloak"}`)
+ req := httptest.NewRequest(http.MethodPost, "/navigate", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ req.ContentLength = int64(len(body))
+
+ target, status, err := o.RouteForRequest(req)
+ if err != nil {
+ t.Fatalf("RouteForRequest status=%d err=%v", status, err)
+ }
+ if target == "" {
+ t.Fatal("target URL is empty")
+ }
+ instances := o.List()
+ if len(instances) != 1 {
+ t.Fatalf("instances = %d, want 1: %+v", len(instances), instances)
+ }
+ if instances[0].BrowserTarget != "cloak" {
+ t.Fatalf("BrowserTarget = %q, want cloak", instances[0].BrowserTarget)
+ }
+ if instances[0].BrowserProvider != config.BrowserProviderCloak {
+ t.Fatalf("BrowserProvider = %q, want cloak", instances[0].BrowserProvider)
+ }
+ if instances[0].ProfileName != "default-cloak" {
+ t.Fatalf("ProfileName = %q, want default-cloak", instances[0].ProfileName)
+ }
+}
+
func TestWrapShorthand_TabOwnerWins(t *testing.T) {
alwaysAlive(t)
o := NewOrchestrator(t.TempDir())
@@ -80,6 +130,45 @@ func TestWrapShorthand_TabOwnerWins(t *testing.T) {
}
}
+func TestWrapShorthand_TabOwnerBrowserTargetConflict(t *testing.T) {
+ alwaysAlive(t)
+ o := NewOrchestrator(t.TempDir())
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ DefaultTarget: "chrome",
+ Targets: config.BrowserTargetsConfig{
+ "chrome": {Provider: config.BrowserProviderChrome},
+ "cloak": {Provider: config.BrowserProviderCloak},
+ },
+ })
+ _, pathB := newBackendInstance(t, o, "inst_b")
+ o.instances["inst_b"].BrowserTarget = "chrome"
+ o.instances["inst_b"].BrowserProvider = config.BrowserProviderChrome
+ o.syncInstanceToManager(&o.instances["inst_b"].Instance)
+ o.instanceMgr.Locator.Register("tab-x", "inst_b")
+
+ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {
+ t.Fatal("fallback should not run for tab-owner conflict")
+ })
+
+ body := []byte(`{"tabId":"tab-x","browserTarget":"cloak"}`)
+ r := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))
+ r.Header.Set("Content-Type", "application/json")
+ r.ContentLength = int64(len(body))
+ w := httptest.NewRecorder()
+
+ wrapped(w, r)
+
+ if w.Code != http.StatusConflict {
+ t.Fatalf("status = %d, want 409 body=%s", w.Code, w.Body.String())
+ }
+ if *pathB != "" {
+ t.Fatalf("conflicting target should not proxy to backend, got path %q", *pathB)
+ }
+ if !bytes.Contains(w.Body.Bytes(), []byte("browser_target_conflict")) {
+ t.Fatalf("body = %s, want browser_target_conflict", w.Body.String())
+ }
+}
+
func TestWrapShorthand_TabNotFoundMultipleInstancesIs404(t *testing.T) {
o := NewOrchestrator(t.TempDir())
alwaysAlive(t)
@@ -120,6 +209,43 @@ func TestWrapShorthand_TabNotFoundSingleInstanceFallsThrough(t *testing.T) {
}
}
+func TestWrapShorthand_BrowserTargetBypassesMismatchedIdentityBinding(t *testing.T) {
+ alwaysAlive(t)
+ o := NewOrchestrator(t.TempDir())
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ DefaultTarget: "chrome",
+ Targets: config.BrowserTargetsConfig{
+ "chrome": {Provider: config.BrowserProviderChrome},
+ "cloak": {Provider: config.BrowserProviderCloak},
+ },
+ })
+ _, pathA := newBackendInstance(t, o, "inst_a")
+ o.instances["inst_a"].BrowserTarget = "chrome"
+ o.instances["inst_a"].BrowserProvider = config.BrowserProviderChrome
+ o.bindings.BindAgent("agent-1", "inst_a")
+
+ fallbackCalled := false
+ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {
+ fallbackCalled = true
+ w.WriteHeader(http.StatusAccepted)
+ })
+
+ r := httptest.NewRequest("GET", "/text?browserTarget=cloak", nil)
+ r.Header.Set(activity.HeaderAgentID, "agent-1")
+ w := httptest.NewRecorder()
+ wrapped(w, r)
+
+ if w.Code != http.StatusAccepted {
+ t.Fatalf("status = %d, want 202 body=%s", w.Code, w.Body.String())
+ }
+ if !fallbackCalled {
+ t.Fatal("fallback should run so browserTarget selection can choose the requested target")
+ }
+ if *pathA != "" {
+ t.Fatalf("mismatched identity binding should not proxy to backend, got path %q", *pathA)
+ }
+}
+
func TestWrapShorthand_SessionBindingHonoredOnTrustedHop(t *testing.T) {
alwaysAlive(t)
o := NewOrchestrator(t.TempDir())
diff --git a/internal/orchestrator/tab_extract.go b/internal/orchestrator/tab_extract.go
index 43791fa3..8aee6af5 100644
--- a/internal/orchestrator/tab_extract.go
+++ b/internal/orchestrator/tab_extract.go
@@ -50,7 +50,21 @@ func ExtractExplicitTabID(r *http.Request) (string, TabIDSource) {
return "", TabIDSourceNone
}
+func ExtractRequestedBrowserTarget(r *http.Request) string {
+ if r == nil {
+ return ""
+ }
+ if target := strings.TrimSpace(r.URL.Query().Get("browserTarget")); target != "" {
+ return target
+ }
+ return peekBodyStringField(r, "browserTarget")
+}
+
func peekBodyTabID(r *http.Request) string {
+ return peekBodyStringField(r, "tabId")
+}
+
+func peekBodyStringField(r *http.Request, field string) string {
if r == nil || r.Body == nil || r.Body == http.NoBody {
return ""
}
@@ -79,11 +93,17 @@ func peekBodyTabID(r *http.Request) string {
return ""
}
- var probe struct {
- TabID string `json:"tabId"`
- }
+ var probe map[string]any
if err := json.Unmarshal(buf, &probe); err != nil {
return ""
}
- return strings.TrimSpace(probe.TabID)
+ raw, ok := probe[field]
+ if !ok {
+ return ""
+ }
+ value, ok := raw.(string)
+ if !ok {
+ return ""
+ }
+ return strings.TrimSpace(value)
}
diff --git a/internal/orchestrator/tab_extract_test.go b/internal/orchestrator/tab_extract_test.go
index 606b229b..a13b4e87 100644
--- a/internal/orchestrator/tab_extract_test.go
+++ b/internal/orchestrator/tab_extract_test.go
@@ -145,3 +145,40 @@ func TestExtractExplicitTabID_LongOKBody(t *testing.T) {
t.Fatalf("got %q, want tail", got)
}
}
+
+func TestExtractRequestedBrowserTarget_Query(t *testing.T) {
+ r := httptest.NewRequest("GET", "/navigate?browserTarget=cloak-1", nil)
+ if got := ExtractRequestedBrowserTarget(r); got != "cloak-1" {
+ t.Fatalf("got %q, want cloak-1", got)
+ }
+}
+
+func TestExtractRequestedBrowserTarget_BodyJSON(t *testing.T) {
+ body := []byte(`{"url":"about:blank","browserTarget":"cloak-1"}`)
+ r := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))
+ r.Header.Set("Content-Type", "application/json")
+ r.ContentLength = int64(len(body))
+
+ if got := ExtractRequestedBrowserTarget(r); got != "cloak-1" {
+ t.Fatalf("got %q, want cloak-1", got)
+ }
+
+ rest, err := io.ReadAll(r.Body)
+ if err != nil {
+ t.Fatalf("body read after peek: %v", err)
+ }
+ if !bytes.Equal(rest, body) {
+ t.Fatalf("body after peek = %q; want %q", rest, body)
+ }
+}
+
+func TestExtractRequestedBrowserTarget_QueryWinsOverBody(t *testing.T) {
+ body := []byte(`{"browserTarget":"body-target"}`)
+ r := httptest.NewRequest("POST", "/navigate?browserTarget=query-target", bytes.NewReader(body))
+ r.Header.Set("Content-Type", "application/json")
+ r.ContentLength = int64(len(body))
+
+ if got := ExtractRequestedBrowserTarget(r); got != "query-target" {
+ t.Fatalf("got %q, want query-target", got)
+ }
+}
diff --git a/internal/schema/config.json b/internal/schema/config.json
index a194ed99..bd5f9110 100644
--- a/internal/schema/config.json
+++ b/internal/schema/config.json
@@ -569,8 +569,15 @@
},
"default": [
"ws",
- "wss"
+ "wss",
+ "http",
+ "https"
]
+ },
+ "forwardProxyAuth": {
+ "$ref": "#/definitions/nullableBoolean",
+ "default": false,
+ "description": "Allow forwarding configured proxy authentication credentials over remote CDP attach. Disabled by default because the attached browser is outside PinchTab's process trust boundary."
}
}
},
diff --git a/internal/server/server.go b/internal/server/server.go
index bffac32f..50d28231 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -333,10 +333,6 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
doShutdown := func() {
shutdownOnce.Do(func() {
slog.Info("shutting down dashboard...")
- // Kill all Chrome processes under our profiles dir immediately.
- // This runs before strategy.Stop() to ensure cleanup happens
- // even if launchd SIGKILL arrives during graceful shutdown.
- bridge.KillAllPinchtabChrome()
if err := activeStrategy.Stop(); err != nil {
slog.Warn("strategy stop failed", "err", err)
}
@@ -346,7 +342,8 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
syncCancel()
maintenanceCancel()
dash.Shutdown()
- orch.Shutdown()
+ gracefulShutdownWithCap(orch, bridgeShutdownTotalCap)
+ bridge.KillAllPinchtabChrome()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
@@ -365,9 +362,6 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
sig := make(chan os.Signal, 2)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
<-sig
- // Kill Chrome immediately on signal — synchronous, before anything else.
- // launchd may SIGKILL us shortly after SIGTERM, so this must happen first.
- bridge.KillAllPinchtabChrome()
go doShutdown()
<-sig
slog.Warn("force shutdown requested")
@@ -381,3 +375,23 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
os.Exit(1)
}
}
+
+const bridgeShutdownTotalCap = 8 * time.Second
+
+func gracefulShutdownWithCap(orch *orchestrator.Orchestrator, cap time.Duration) bool {
+ if orch == nil {
+ return true
+ }
+ done := make(chan struct{})
+ go func() {
+ orch.Shutdown()
+ close(done)
+ }()
+ select {
+ case <-done:
+ return true
+ case <-time.After(cap):
+ slog.Warn("graceful bridge shutdown exceeded cap, escalating", "cap", cap)
+ return false
+ }
+}
diff --git a/internal/stealth/bundle.go b/internal/stealth/bundle.go
index 144a7534..05d35916 100644
--- a/internal/stealth/bundle.go
+++ b/internal/stealth/bundle.go
@@ -25,6 +25,7 @@ const (
LaunchModeAllocator LaunchMode = "allocator"
LaunchModeDirectFallback LaunchMode = "direct_fallback"
LaunchModeAttached LaunchMode = "attached"
+ LaunchModeRemoteCDP LaunchMode = "remote-cdp"
)
type WebdriverMode string
@@ -34,17 +35,18 @@ const (
)
type Bundle struct {
- Level Level `json:"level"`
- Provider string `json:"provider"`
- Native bool `json:"native"`
- Seed int64 `json:"seed"`
- Script string `json:"-"`
- ScriptHash string `json:"scriptHash"`
- Launch LaunchContract `json:"-"`
- PatchIDs []string `json:"patchIds"`
- Capabilities map[string]bool `json:"capabilities"`
- Tradeoffs []string `json:"tradeoffs,omitempty"`
- Webdriver WebdriverMode `json:"webdriverMode"`
+ Level Level `json:"level"`
+ Provider string `json:"provider"`
+ Native bool `json:"native"`
+ PinchTabOverlaysDisabled bool `json:"pinchtabOverlaysDisabled"`
+ Seed int64 `json:"seed"`
+ Script string `json:"-"`
+ ScriptHash string `json:"scriptHash"`
+ Launch LaunchContract `json:"-"`
+ PatchIDs []string `json:"patchIds"`
+ Capabilities map[string]bool `json:"capabilities"`
+ Tradeoffs []string `json:"tradeoffs,omitempty"`
+ Webdriver WebdriverMode `json:"webdriverMode"`
}
type Status struct {
@@ -61,8 +63,10 @@ type Status struct {
PatchIDs []string `json:"patchIds"`
Flags map[string]bool `json:"flags"`
Capabilities map[string]bool `json:"capabilities"`
- Tradeoffs []string `json:"tradeoffs,omitempty"`
- TabOverrides map[string]bool `json:"tabOverrides"`
+ // ProviderCapabilities is advisory; omitted for empty/unknown providers to preserve legacy JSON shape.
+ ProviderCapabilities []string `json:"providerCapabilities,omitempty"`
+ Tradeoffs []string `json:"tradeoffs,omitempty"`
+ TabOverrides map[string]bool `json:"tabOverrides"`
}
func NewBundle(cfg *config.RuntimeConfig, seed int64) *Bundle {
@@ -75,7 +79,8 @@ func NewBundle(cfg *config.RuntimeConfig, seed int64) *Bundle {
provider = config.NormalizeBrowserProvider(cfg.BrowserProvider)
}
level := NormalizeLevel(levelName)
- nativeCloak := config.NativeCloakStealthEnabled(cfg)
+ nativeCloak := config.CloakBrowserProviderActive(cfg)
+ disablePinchTabStealth := config.PinchTabStealthDefaultsDisabled(cfg)
personaJSON := "{}"
if cfg != nil {
if encoded, err := json.Marshal(BuildPersona(cfg.UserAgent, cfg.ChromeVersion)); err == nil {
@@ -87,7 +92,7 @@ func NewBundle(cfg *config.RuntimeConfig, seed int64) *Bundle {
patchIDs := patchIDsForLevel(level, headless)
capabilities := capabilityMap(level, headless)
tradeoffIDs := tradeoffs(level)
- if nativeCloak {
+ if disablePinchTabStealth {
script = renderNativeCloakScript()
hashSource = script
patchIDs = nativeCloakPatchIDs()
@@ -96,11 +101,12 @@ func NewBundle(cfg *config.RuntimeConfig, seed int64) *Bundle {
}
return &Bundle{
- Level: level,
- Provider: provider,
- Native: nativeCloak,
- Seed: seed,
- Script: script,
+ Level: level,
+ Provider: provider,
+ Native: nativeCloak,
+ PinchTabOverlaysDisabled: disablePinchTabStealth,
+ Seed: seed,
+ Script: script,
// Keep the status hash stable across identical configs even when the
// per-process seed changes. The seed is runtime entropy, not contract.
ScriptHash: hashScript(hashSource),
@@ -154,10 +160,11 @@ func StatusFromBundle(bundle *Bundle, cfg *config.RuntimeConfig, launchMode Laun
UserAgent: bundle.LaunchUserAgent(),
FingerprintSeed: statusFingerprintSeed(cfg),
WebdriverMode: bundle.Webdriver,
- PinchTabOverlaysDisabled: bundle.Native,
+ PinchTabOverlaysDisabled: bundle.PinchTabOverlaysDisabled,
PatchIDs: append([]string(nil), bundle.PatchIDs...),
Flags: statusFlags(bundle, cfg),
Capabilities: cloneBoolMap(bundle.Capabilities),
+ ProviderCapabilities: providerCapabilityStrings(bundle.Provider),
Tradeoffs: append([]string(nil), bundle.Tradeoffs...),
TabOverrides: map[string]bool{
"fingerprintRotateActive": false,
@@ -169,6 +176,18 @@ func StatusFromBundle(bundle *Bundle, cfg *config.RuntimeConfig, launchMode Laun
return status
}
+func providerCapabilityStrings(provider string) []string {
+ caps := config.ProviderCapabilities(provider)
+ if len(caps) == 0 {
+ return nil
+ }
+ out := make([]string, len(caps))
+ for i, c := range caps {
+ out[i] = string(c)
+ }
+ return out
+}
+
func statusFingerprintSeed(cfg *config.RuntimeConfig) string {
if cfg == nil || !config.IsCloakBrowserProvider(cfg.BrowserProvider) {
return ""
diff --git a/internal/stealth/bundle_test.go b/internal/stealth/bundle_test.go
index 658ff5c5..43a6515f 100644
--- a/internal/stealth/bundle_test.go
+++ b/internal/stealth/bundle_test.go
@@ -168,6 +168,9 @@ func TestNewBundleNativeCloakDisablesPinchTabStealthOverlays(t *testing.T) {
if !bundle.Native {
t.Fatal("expected native Cloak bundle")
}
+ if !bundle.PinchTabOverlaysDisabled {
+ t.Fatal("expected PinchTab overlays to be disabled")
+ }
if strings.Contains(bundle.Script, "__pinchtab_stealth_level") {
t.Fatalf("native Cloak script should not include PinchTab JS stealth overlay")
}
@@ -192,3 +195,92 @@ func TestNewBundleNativeCloakDisablesPinchTabStealthOverlays(t *testing.T) {
t.Fatalf("status capabilities = %v, want sourceLevelFingerprinting", status.Capabilities)
}
}
+
+func TestNewBundleCloakProviderCanKeepPinchTabStealthOverlays(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ BrowserProvider: config.BrowserProviderCloak,
+ Cloak: config.CloakBrowserRuntimeConfig{
+ FingerprintSeed: "42069",
+ DisableDefaultStealthArgs: false,
+ },
+ StealthLevel: "full",
+ Headless: true,
+ }
+
+ bundle := NewBundle(cfg, 1234)
+ if !bundle.Native {
+ t.Fatal("expected Cloak provider to report native Cloak mode")
+ }
+ if bundle.PinchTabOverlaysDisabled {
+ t.Fatal("expected PinchTab overlays to remain enabled")
+ }
+ if !strings.Contains(bundle.Script, "__pinchtab_stealth_level") {
+ t.Fatal("expected PinchTab JS stealth overlay to remain in bundle")
+ }
+ if len(bundle.Launch.Args) == 0 {
+ t.Fatalf("expected PinchTab launch args to remain enabled")
+ }
+ if !bundle.Launch.Flags["nativeCloakBrowser"] {
+ t.Fatalf("launch flags = %v, want nativeCloakBrowser", bundle.Launch.Flags)
+ }
+ if bundle.Launch.Flags["pinchtabStealthArgsDisabled"] {
+ t.Fatalf("launch flags = %v, did not expect pinchtabStealthArgsDisabled", bundle.Launch.Flags)
+ }
+
+ status := StatusFromBundle(bundle, cfg, LaunchModeAllocator)
+ if status.Provider != config.BrowserProviderCloak || !status.Native || status.PinchTabOverlaysDisabled {
+ t.Fatalf("status = %+v, want native cloak provider with overlays enabled", status)
+ }
+}
+
+func TestStatusFromBundleEchoesProviderCapabilities(t *testing.T) {
+ t.Run("chrome", func(t *testing.T) {
+ cfg := &config.RuntimeConfig{BrowserProvider: config.BrowserProviderChrome}
+ bundle := NewBundle(cfg, 1)
+ status := StatusFromBundle(bundle, cfg, LaunchModeAllocator)
+ if status == nil {
+ t.Fatal("expected non-nil status")
+ return
+ }
+ want := []string{"cdp", "headless", "pdf", "extensions", "downloads", "networkInterception"}
+ if !equalStringSlices(status.ProviderCapabilities, want) {
+ t.Fatalf("chrome ProviderCapabilities = %v, want %v", status.ProviderCapabilities, want)
+ }
+ for _, c := range want {
+ if c == "nativeStealth" {
+ t.Fatalf("chrome should not advertise nativeStealth")
+ }
+ }
+ })
+
+ t.Run("cloak", func(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ BrowserProvider: config.BrowserProviderCloak,
+ Cloak: config.CloakBrowserRuntimeConfig{
+ DisableDefaultStealthArgs: true,
+ },
+ }
+ bundle := NewBundle(cfg, 1)
+ status := StatusFromBundle(bundle, cfg, LaunchModeAllocator)
+ if status == nil {
+ t.Fatal("expected non-nil status")
+ return
+ }
+ want := []string{"cdp", "headless", "pdf", "extensions", "downloads", "networkInterception", "nativeStealth"}
+ if !equalStringSlices(status.ProviderCapabilities, want) {
+ t.Fatalf("cloak ProviderCapabilities = %v, want %v", status.ProviderCapabilities, want)
+ }
+ })
+}
+
+func equalStringSlices(a, b []string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for i := range a {
+ if a[i] != b[i] {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/stealth/launch.go b/internal/stealth/launch.go
index 945c0d99..1901a68c 100644
--- a/internal/stealth/launch.go
+++ b/internal/stealth/launch.go
@@ -12,7 +12,7 @@ type LaunchContract struct {
}
func BuildLaunchContract(cfg *config.RuntimeConfig, level Level) LaunchContract {
- if config.NativeCloakStealthEnabled(cfg) {
+ if config.PinchTabStealthDefaultsDisabled(cfg) {
return LaunchContract{
Flags: map[string]bool{
"nativeCloakBrowser": true,
@@ -54,15 +54,20 @@ func BuildLaunchContract(cfg *config.RuntimeConfig, level Level) LaunchContract
args = append(args, "--lang="+persona.Language)
}
+ flags := map[string]bool{
+ "automationControlledDisabled": true,
+ "enableAutomationFalse": true,
+ "downlinkMaxFlag": true,
+ "globalUserAgent": pinUA,
+ "globalLanguage": persona.Language != "",
+ }
+ if config.CloakBrowserProviderActive(cfg) {
+ flags["nativeCloakBrowser"] = true
+ }
+
return LaunchContract{
- Args: args,
- Flags: map[string]bool{
- "automationControlledDisabled": true,
- "enableAutomationFalse": true,
- "downlinkMaxFlag": true,
- "globalUserAgent": pinUA,
- "globalLanguage": persona.Language != "",
- },
+ Args: args,
+ Flags: flags,
}
}
diff --git a/internal/strategy/autorestart/autorestart_test.go b/internal/strategy/autorestart/autorestart_test.go
index facfe3ec..f45400fa 100644
--- a/internal/strategy/autorestart/autorestart_test.go
+++ b/internal/strategy/autorestart/autorestart_test.go
@@ -329,7 +329,7 @@ func TestStrategy_Stop_SetsDeliberate(t *testing.T) {
func TestStrategy_EnsureRunning_NoOrch(t *testing.T) {
s := New(AutorestartConfig{})
- _, err := s.ensureRunning()
+ _, _, err := s.ensureRunning(httptest.NewRequest("GET", "/snapshot", nil))
if err == nil {
t.Error("expected error when no orchestrator")
}
@@ -555,6 +555,11 @@ func TestStrategy_LaunchInitial_TracksLaunchedMode(t *testing.T) {
func TestStrategy_RestartInstance_UsesTrackedMode(t *testing.T) {
orch := orchestrator.NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ orch.ApplyRuntimeConfig(&config.RuntimeConfig{
+ AttachEnabled: true,
+ AttachAllowHosts: []string{"127.0.0.1"},
+ AttachAllowSchemes: []string{"http"},
+ })
if _, _, err := orch.AttachBridge("default", "http://127.0.0.1:9999", ""); err != nil {
t.Fatalf("AttachBridge failed: %v", err)
}
diff --git a/internal/strategy/autorestart/handlers.go b/internal/strategy/autorestart/handlers.go
index 32bc5121..2f5fb680 100644
--- a/internal/strategy/autorestart/handlers.go
+++ b/internal/strategy/autorestart/handlers.go
@@ -26,9 +26,12 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
// proxyToManaged ensures the managed instance is running, then proxies.
func (s *Strategy) proxyToManaged(w http.ResponseWriter, r *http.Request) {
- target, err := s.ensureRunning()
+ target, status, err := s.ensureRunning(r)
if err != nil {
- httpx.Error(w, 503, err)
+ if status == 0 {
+ status = 503
+ }
+ httpx.Error(w, status, err)
return
}
activity.EnrichRouteActivity(r)
@@ -38,25 +41,33 @@ func (s *Strategy) proxyToManaged(w http.ResponseWriter, r *http.Request) {
// ensureRunning returns the URL of the managed instance, waiting briefly for
// the initial launch / a restart to finish before giving up.
-func (s *Strategy) ensureRunning() (string, error) {
+func (s *Strategy) ensureRunning(r *http.Request) (string, int, error) {
if s.orch == nil {
- return "", fmt.Errorf("no orchestrator configured")
+ return "", 503, fmt.Errorf("no orchestrator configured")
}
- if target := s.orch.FirstRunningURL(); target != "" {
- return target, nil
+ if target, status, err := s.orch.FirstRunningURLForRequest(r); err != nil {
+ return "", status, err
+ } else if target != "" {
+ return target, 0, nil
}
deadline := time.Now().Add(instanceReadyWait)
for time.Now().Before(deadline) {
time.Sleep(200 * time.Millisecond)
- if target := s.orch.FirstRunningURL(); target != "" {
- return target, nil
+ if target, status, err := s.orch.FirstRunningURLForRequest(r); err != nil {
+ return "", status, err
+ } else if target != "" {
+ return target, 0, nil
}
}
- return "", fmt.Errorf("instance not ready after %s (may be restarting)", instanceReadyWait)
+ return "", 503, fmt.Errorf("instance not ready after %s (may be restarting)", instanceReadyWait)
}
func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
- target := s.orch.FirstRunningURL()
+ target, status, err := s.orch.FirstRunningURLForRequest(r)
+ if err != nil {
+ httpx.Error(w, status, err)
+ return
+ }
if target == "" {
httpx.JSON(w, 200, map[string]any{"tabs": []any{}})
return
diff --git a/internal/strategy/explicit/explicit.go b/internal/strategy/explicit/explicit.go
index 1d773cc5..9ae57c0c 100644
--- a/internal/strategy/explicit/explicit.go
+++ b/internal/strategy/explicit/explicit.go
@@ -44,7 +44,11 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
}
func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {
- target := s.orch.FirstRunningURL()
+ target, status, err := s.orch.FirstRunningURLForRequest(r)
+ if err != nil {
+ httpx.Error(w, status, err)
+ return
+ }
if target == "" {
httpx.Error(w, 503, fmt.Errorf("no running instances — launch one from the Profiles tab"))
return
@@ -55,7 +59,11 @@ func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {
}
func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
- target := s.orch.FirstRunningURL()
+ target, status, err := s.orch.FirstRunningURLForRequest(r)
+ if err != nil {
+ httpx.Error(w, status, err)
+ return
+ }
if target == "" {
httpx.JSON(w, 200, map[string]any{"tabs": []any{}})
return
diff --git a/internal/strategy/noinstance/noinstance.go b/internal/strategy/noinstance/noinstance.go
index 01c35b76..55dd0b0b 100644
--- a/internal/strategy/noinstance/noinstance.go
+++ b/internal/strategy/noinstance/noinstance.go
@@ -41,7 +41,11 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
}
func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {
- target := s.orch.FirstRunningURL()
+ target, status, err := s.orch.FirstRunningURLForRequest(r)
+ if err != nil {
+ httpx.Error(w, status, err)
+ return
+ }
if target == "" {
httpx.Error(w, 503, fmt.Errorf("no remote instances connected — attach a bridge first"))
return
@@ -52,7 +56,11 @@ func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {
}
func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
- target := s.orch.FirstRunningURL()
+ target, status, err := s.orch.FirstRunningURLForRequest(r)
+ if err != nil {
+ httpx.Error(w, status, err)
+ return
+ }
if target == "" {
httpx.JSON(w, 200, map[string]any{"tabs": []any{}})
return
diff --git a/internal/strategy/simple/simple.go b/internal/strategy/simple/simple.go
index 4e522f3a..fd800371 100644
--- a/internal/strategy/simple/simple.go
+++ b/internal/strategy/simple/simple.go
@@ -11,9 +11,7 @@ package simple
import (
"context"
"fmt"
- "log/slog"
"net/http"
- "time"
"github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/httpx"
@@ -52,9 +50,12 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
// proxyToFirst ensures an instance is running, then proxies the request to it.
func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {
- target, err := s.ensureRunning()
+ target, status, err := s.ensureRunning(r)
if err != nil {
- httpx.Error(w, 503, err)
+ if status == 0 {
+ status = 503
+ }
+ httpx.Error(w, status, err)
return
}
activity.EnrichRouteActivity(r)
@@ -63,7 +64,11 @@ func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {
}
func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
- target := s.orch.FirstRunningURL()
+ target, status, err := s.orch.FirstRunningURLForRequest(r)
+ if err != nil {
+ httpx.Error(w, status, err)
+ return
+ }
if target == "" {
httpx.JSON(w, 200, map[string]any{"tabs": []any{}})
return
@@ -72,41 +77,9 @@ func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
}
// ensureRunning returns the URL of a running instance, auto-launching one if needed.
-func (s *Strategy) ensureRunning() (string, error) {
+func (s *Strategy) ensureRunning(r *http.Request) (string, int, error) {
if s.orch == nil {
- return "", fmt.Errorf("no running instances")
+ return "", 503, fmt.Errorf("no running instances")
}
- if target := s.orch.FirstRunningURL(); target != "" {
- return target, nil
- }
-
- slog.Info("simple strategy: no running instances, auto-launching")
- mgr := s.orch.InstanceManager()
- if mgr == nil {
- return "", fmt.Errorf("no running instances")
- }
-
- launched, err := mgr.Launch("default", "", true)
- if err != nil {
- return "", fmt.Errorf("auto-launch failed: %w", err)
- }
-
- // Wait for instance to become ready.
- deadline := time.Now().Add(30 * time.Second)
- if launched.URL == "" {
- return "", fmt.Errorf("auto-launched instance %q has no URL", launched.ID)
- }
- for time.Now().Before(deadline) {
- time.Sleep(500 * time.Millisecond)
- url := launched.URL
- resp, healthErr := http.Get(url + "/health")
- if healthErr == nil {
- _ = resp.Body.Close()
- if resp.StatusCode == 200 {
- return url, nil
- }
- }
- }
-
- return "", fmt.Errorf("instance launched but did not become ready in time")
+ return s.orch.RouteForRequest(r)
}
diff --git a/internal/strategy/simple/simple_test.go b/internal/strategy/simple/simple_test.go
index d0a263c7..0e866fdc 100644
--- a/internal/strategy/simple/simple_test.go
+++ b/internal/strategy/simple/simple_test.go
@@ -7,6 +7,7 @@ import (
"net/http"
"net/http/httptest"
"strings"
+ "sync"
"testing"
"github.com/pinchtab/pinchtab/internal/config"
@@ -16,10 +17,35 @@ import (
type mockRunner struct {
portAvail bool
+ cmds []*mockCmd
+}
+
+type mockCmd struct {
+ done chan struct{}
+ once sync.Once
+}
+
+func newMockCmd() *mockCmd {
+ return &mockCmd{done: make(chan struct{})}
+}
+
+func (m *mockCmd) Wait() error {
+ <-m.done
+ return nil
+}
+
+func (m *mockCmd) PID() int { return 1234 }
+
+func (m *mockCmd) Cancel() {
+ m.once.Do(func() {
+ close(m.done)
+ })
}
func (m *mockRunner) Run(context.Context, string, []string, []string, io.Writer, io.Writer) (orchestrator.Cmd, error) {
- return nil, nil
+ cmd := newMockCmd()
+ m.cmds = append(m.cmds, cmd)
+ return cmd, nil
}
func (m *mockRunner) InspectPort(string) orchestrator.PortInspection {
@@ -95,6 +121,66 @@ func TestStrategy_ProxyToFirst_NoOrch_Returns503(t *testing.T) {
}
}
+type roundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) {
+ return f(r)
+}
+
+func TestStrategy_EnsureRunning_BrowserTargetAutoLaunchesRequestedTarget(t *testing.T) {
+ oldTransport := http.DefaultTransport
+ http.DefaultTransport = roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader(`{"status":"ok"}`)),
+ Header: make(http.Header),
+ Request: req,
+ }, nil
+ })
+ t.Cleanup(func() { http.DefaultTransport = oldTransport })
+
+ runner := &mockRunner{portAvail: true}
+ orch := orchestrator.NewOrchestratorWithRunner(t.TempDir(), runner)
+ orch.ApplyRuntimeConfig(&config.RuntimeConfig{
+ DefaultTarget: "chrome",
+ Targets: config.BrowserTargetsConfig{
+ "chrome": {Provider: config.BrowserProviderChrome},
+ "cloak": {Provider: config.BrowserProviderCloak},
+ },
+ })
+ t.Cleanup(func() {
+ for _, inst := range orch.List() {
+ _ = orch.Stop(inst.ID)
+ }
+ })
+
+ body := `{"url":"about:blank","browserTarget":"cloak"}`
+ req := httptest.NewRequest(http.MethodPost, "/navigate", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+
+ s := &Strategy{orch: orch}
+ target, status, err := s.ensureRunning(req)
+ if err != nil {
+ t.Fatalf("ensureRunning status=%d err=%v", status, err)
+ }
+ if target == "" {
+ t.Fatal("target URL is empty")
+ }
+ instances := orch.List()
+ if len(instances) != 1 {
+ t.Fatalf("instances = %d, want 1: %+v", len(instances), instances)
+ }
+ if instances[0].BrowserTarget != "cloak" {
+ t.Fatalf("BrowserTarget = %q, want cloak", instances[0].BrowserTarget)
+ }
+ if instances[0].BrowserProvider != config.BrowserProviderCloak {
+ t.Fatalf("BrowserProvider = %q, want cloak", instances[0].BrowserProvider)
+ }
+ if instances[0].ProfileName != "default-cloak" {
+ t.Fatalf("ProfileName = %q, want default-cloak", instances[0].ProfileName)
+ }
+}
+
func TestStrategy_HandleTabs_NoInstances(t *testing.T) {
// handleTabs with nil orch would panic — test the empty-tabs path
// by checking the JSON response format of proxyHTTP fallback.
diff --git a/scripts/README.md b/scripts/README.md
index a1cfe5f0..09a9301e 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -27,7 +27,6 @@ Development and CI scripts for PinchTab.
| `autosolver-realworld-smoke.sh` | Smoke-test real-world autosolver flow against an external detection page |
| `dev.sh` | Full build (dashboard + Go) and run |
| `dev-e2e.sh` | Lookup wrapper for `./dev e2e test`; delegates execution to the Go E2E runner |
-| `docker-cloakbrowser-smoke.sh` | Docker CloakBrowser smoke using the dedicated local-only `tests/tools/docker/cloakbrowser-smoke.Dockerfile` image |
| `docker-smoke.sh` | Host Docker smoke helper invoked by the Go E2E runner |
| `npm-dev-binary.sh` | Build the canonical `./pinchtab-dev` binary for source-checkout npm-package testing |
| `run.sh` | Run the existing `./pinchtab` binary |
@@ -38,6 +37,7 @@ Development and CI scripts for PinchTab.
|--------|---------|
| `doctor.sh` | Verify & setup dev environment (interactive — prompts before installing) |
| `install-hooks.sh` | Install git pre-commit hook |
+| `install-skills.sh` | Symlink repo skills into `./.claude/skills` by default; set `CLAUDE_SKILLS_DIR=~/.claude/skills` for a global install |
## Testing
@@ -48,6 +48,8 @@ Development and CI scripts for PinchTab.
## `./dev` shortcuts
-- `./dev e2e smoke` runs the smoke tier through the Go e2e runner, including host Docker smoke checks.
-- `PINCHTAB_DOCKER_SMOKE_RELEASE_IMAGE=<image> ./dev e2e smoke --filter release` skips the release-image build and runs the matching Docker smoke checks against the specified image tag.
-- `./dev smoke cloakbrowser [image]` runs the manual Docker CloakBrowser smoke. By default it builds `pinchtab-cloakbrowser:test` from `tests/tools/docker/cloakbrowser-smoke.Dockerfile`, which installs the CloakBrowser binary into that local image. The smoke mounts `/data` and `/tmp` as tmpfs for Chromium profile and socket paths, serves `tests/e2e/fixtures`, checks a representative endpoint subset, and runs the Cloak-compatible API basic E2E scenario files in the API runner container attached to the Cloak container's network namespace. Set `SKIP_BUILD=1` to require a prebuilt image, or set `PINCHTAB_CLOAKBROWSER_E2E_SCENARIOS` to override the scenario list.
+- `./dev smoke ci` runs the CI-backed smoke subset through the Go e2e runner, including host Docker smoke checks.
+- `PINCHTAB_DOCKER_SMOKE_RELEASE_IMAGE=<image> ./dev smoke ci --filter release` skips the release-image build and runs the matching Docker smoke checks against the specified image tag.
+- `./dev smoke` runs all local smoke categories: CI smoke, browser parity, CDP attach, and live detection.
+- `./dev e2e --provider=cloak` runs the regular e2e suites against the prebuilt CloakBrowser provider image.
+- `./dev smoke cloakbrowser [--provider=chrome|cloak|all] [--multi-target|--profile-persistence|--profile-lock-recovery]` runs the specialized Chrome/CloakBrowser parity smoke via `scripts/docker-browser-parity-smoke.sh`. It builds the provider images from `tests/tools/docker/chrome-smoke.Dockerfile` and `tests/tools/docker/cloakbrowser-smoke.Dockerfile`; set `SKIP_BUILD=1` to require prebuilt images. The Cloak leg also honors `PINCHTAB_CLOAKBROWSER_E2E_SCENARIOS` for the scenario list.
diff --git a/scripts/dev-smoke.sh b/scripts/dev-smoke.sh
new file mode 100644
index 00000000..0e21c23c
--- /dev/null
+++ b/scripts/dev-smoke.sh
@@ -0,0 +1,359 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+cd "$ROOT"
+
+BOLD=$'\033[1m'
+ACCENT=$'\033[38;2;251;191;36m'
+MUTED=$'\033[38;2;90;100;128m'
+SUCCESS=$'\033[38;2;0;229;204m'
+ERROR=$'\033[38;2;230;57;70m'
+NC=$'\033[0m'
+
+usage() {
+ cat <<'EOF'
+Usage:
+ ./dev smoke [--provider=chrome|cloak|all] [filter...]
+ ./dev smoke ci [--provider=chrome|cloak] [--filter TEXT]
+ ./dev smoke cdp-attach [chrome|cloak|all]
+ ./dev smoke live-detection [--provider=chrome|cloak|all]
+ ./dev smoke cloakbrowser [--provider=chrome|cloak|all] [special flags]
+
+Filters:
+ ci, e2e Run the CI-backed E2E smoke subset
+ cloakbrowser Run browser parity / CloakBrowser smoke
+ browser-parity Alias for cloakbrowser
+ cdp-attach Run CDP attach smoke
+ live-detection Run advisory live detection smoke
+ docker, mcp, api... Passed to the E2E smoke runner as --filter
+
+Defaults:
+ ./dev smoke Runs all local smoke categories for all supported providers
+ ./dev smoke ci Runs only the CI smoke subset, default provider chrome
+
+Special cloakbrowser flags:
+ --multi-target
+ --profile-persistence
+ --profile-lock-recovery
+EOF
+}
+
+provider=""
+ci_only=0
+dry_run=0
+logs="${E2E_LOGS:-hide}"
+e2e_filter=""
+declare -a filters=()
+declare -a parity_args=()
+
+append_unique() {
+ local value="$1"
+ local existing
+ for existing in "${filters[@]:-}"; do
+ [ "$existing" = "$value" ] && return
+ done
+ filters+=("$value")
+}
+
+is_named_smoke_filter() {
+ case "$1" in
+ ci|ci-smoke|e2e|e2e-smoke|cloakbrowser|browser-parity|cdp-attach|live-detection)
+ return 0
+ ;;
+ *)
+ return 1
+ ;;
+ esac
+}
+
+append_smoke_filter() {
+ case "$1" in
+ ci|ci-smoke)
+ ci_only=1
+ append_unique "e2e"
+ ;;
+ e2e|e2e-smoke)
+ append_unique "e2e"
+ ;;
+ cloakbrowser|browser-parity)
+ append_unique "browser-parity"
+ ;;
+ cdp-attach|live-detection)
+ append_unique "$1"
+ ;;
+ *)
+ append_unique "$1"
+ ;;
+ esac
+}
+
+append_requested_filter() {
+ local value="$1"
+ if [[ "$value" == */* ]]; then
+ local old_ifs="$IFS"
+ local -a parts=()
+ IFS='/'
+ read -r -a parts <<<"$value"
+ IFS="$old_ifs"
+
+ local part
+ for part in "${parts[@]}"; do
+ if ! is_named_smoke_filter "$part"; then
+ append_unique "$value"
+ return
+ fi
+ done
+ for part in "${parts[@]}"; do
+ append_smoke_filter "$part"
+ done
+ return
+ fi
+ append_smoke_filter "$value"
+}
+
+normalize_provider() {
+ case "$1" in
+ chrome|cloak|all) printf '%s\n' "$1" ;;
+ *) echo "invalid --provider: $1 (expected chrome|cloak|all)" >&2; return 1 ;;
+ esac
+}
+
+set_provider() {
+ local normalized
+ normalized="$(normalize_provider "$1")" || exit 1
+ provider="$normalized"
+}
+
+while [ "$#" -gt 0 ]; do
+ case "$1" in
+ --help|-h)
+ usage
+ exit 0
+ ;;
+ --ci)
+ ci_only=1
+ append_unique "e2e"
+ ;;
+ --dry-run)
+ dry_run=1
+ ;;
+ --logs=*)
+ logs="${1#--logs=}"
+ ;;
+ --logs)
+ if [ "$#" -lt 2 ]; then
+ echo "${ERROR}--logs requires a value${NC}" >&2
+ exit 1
+ fi
+ shift
+ logs="$1"
+ ;;
+ --provider=*)
+ set_provider "${1#--provider=}"
+ ;;
+ --provider)
+ if [ "$#" -lt 2 ]; then
+ echo "${ERROR}--provider requires a value${NC}" >&2
+ exit 1
+ fi
+ shift
+ set_provider "$1"
+ ;;
+ --filter=*)
+ append_requested_filter "${1#--filter=}"
+ ;;
+ --filter)
+ if [ "$#" -lt 2 ]; then
+ echo "${ERROR}--filter requires a value${NC}" >&2
+ exit 1
+ fi
+ shift
+ append_requested_filter "$1"
+ ;;
+ --multi-target|--profile-persistence|--profile-lock-recovery)
+ parity_args+=("$1")
+ ;;
+ --*)
+ echo "${ERROR}unknown smoke flag: $1${NC}" >&2
+ usage >&2
+ exit 1
+ ;;
+ ci|ci-smoke)
+ append_smoke_filter "$1"
+ ;;
+ e2e|e2e-smoke)
+ append_smoke_filter "$1"
+ ;;
+ cloakbrowser|browser-parity)
+ append_smoke_filter "$1"
+ ;;
+ cdp-attach|live-detection)
+ append_smoke_filter "$1"
+ ;;
+ chrome|cloak|all)
+ set_provider "$1"
+ ;;
+ *)
+ append_requested_filter "$1"
+ ;;
+ esac
+ shift
+done
+
+if [ -z "$provider" ]; then
+ if [ "$ci_only" -eq 1 ]; then
+ provider="chrome"
+ else
+ provider="all"
+ fi
+fi
+
+case "$logs" in
+ show|hide) ;;
+ *) echo "${ERROR}--logs must be show or hide${NC}" >&2; exit 1 ;;
+esac
+
+run_step() {
+ local allow_skip="$1"
+ local title="$2"
+ shift 2
+ local -a cmd=("$@")
+
+ echo ""
+ echo " ${ACCENT}${BOLD}${title}${NC}"
+ printf " ${MUTED}"
+ printf "%q " "${cmd[@]}"
+ printf "${NC}\n"
+
+ if [ "$dry_run" -eq 1 ]; then
+ return 0
+ fi
+
+ set +e
+ "${cmd[@]}"
+ local code=$?
+ set -e
+ if [ "$code" -eq 0 ]; then
+ echo " ${SUCCESS}${BOLD}passed:${NC} ${title}"
+ return 0
+ fi
+ if [ "$code" -eq 77 ] && [ "$allow_skip" -eq 1 ]; then
+ echo " ${MUTED}skipped:${NC} ${title}"
+ return 0
+ fi
+ echo " ${ERROR}${BOLD}failed:${NC} ${title} (exit ${code})" >&2
+ return "$code"
+}
+
+run_e2e_smoke() {
+ local selected_provider="$1"
+ local filter="${2:-}"
+ local -a args=(go run ./tests/tools/runner e2e --suite smoke --provider "$selected_provider" --logs "$logs")
+ [ "$dry_run" -eq 1 ] && args+=(--dry-run)
+ [ -n "$filter" ] && args+=(--filter "$filter")
+ run_step 0 "E2E smoke subset (${selected_provider}${filter:+, filter=${filter}})" "${args[@]}"
+}
+
+run_cdp_attach() {
+ local selected_provider="$1"
+ run_step "$2" "CDP attach smoke (${selected_provider})" bash scripts/docker-cdp-attach-smoke.sh "$selected_provider"
+}
+
+run_live_detection() {
+ local selected_provider="$1"
+ run_step "$2" "Live detection smoke (${selected_provider})" bash scripts/docker-live-detection-smoke.sh --provider="$selected_provider"
+}
+
+provider_list() {
+ case "$1" in
+ all) printf '%s\n' chrome cloak ;;
+ *) printf '%s\n' "$1" ;;
+ esac
+}
+
+failures=0
+
+run_or_record() {
+ "$@" || failures=1
+}
+
+if [ "$ci_only" -eq 1 ]; then
+ if [ "$provider" = "all" ]; then
+ echo "${ERROR}./dev smoke ci accepts --provider=chrome|cloak, not all${NC}" >&2
+ exit 1
+ fi
+ if [ "${#filters[@]}" -gt 0 ]; then
+ for filter in "${filters[@]}"; do
+ [ "$filter" = "e2e" ] && continue
+ e2e_filter="$filter"
+ done
+ fi
+ run_e2e_smoke "$provider" "$e2e_filter"
+ exit $?
+fi
+
+if [ "${#filters[@]}" -eq 0 ]; then
+ # Full local smoke: run all categories. Browser parity runs before Cloak E2E
+ # because it builds the local CloakBrowser smoke image when needed.
+ case "$provider" in
+ chrome)
+ run_or_record run_e2e_smoke chrome ""
+ run_or_record run_step 1 "Browser parity smoke (chrome)" bash scripts/docker-browser-parity-smoke.sh --provider=chrome "${parity_args[@]}"
+ run_or_record run_cdp_attach chrome 1
+ run_or_record run_live_detection chrome 1
+ ;;
+ cloak)
+ run_or_record run_step 1 "Browser parity smoke (cloak)" bash scripts/docker-browser-parity-smoke.sh --provider=cloak "${parity_args[@]}"
+ run_or_record run_e2e_smoke cloak ""
+ run_or_record run_cdp_attach cloak 1
+ run_or_record run_live_detection cloak 1
+ ;;
+ all)
+ run_or_record run_e2e_smoke chrome ""
+ run_or_record run_step 1 "Browser parity smoke (all)" bash scripts/docker-browser-parity-smoke.sh --provider=all "${parity_args[@]}"
+ run_or_record run_e2e_smoke cloak ""
+ run_or_record run_cdp_attach all 1
+ run_or_record run_live_detection chrome 1
+ run_or_record run_live_detection cloak 1
+ ;;
+ esac
+else
+ for filter in "${filters[@]}"; do
+ case "$filter" in
+ e2e)
+ while IFS= read -r selected_provider; do
+ run_or_record run_e2e_smoke "$selected_provider" ""
+ done < <(provider_list "$provider")
+ ;;
+ browser-parity)
+ run_or_record run_step 0 "Browser parity smoke (${provider})" bash scripts/docker-browser-parity-smoke.sh --provider="$provider" "${parity_args[@]}"
+ ;;
+ cdp-attach)
+ run_or_record run_cdp_attach "$provider" 0
+ ;;
+ live-detection)
+ if [ "$provider" = "all" ]; then
+ run_or_record run_live_detection chrome 0
+ run_or_record run_live_detection cloak 0
+ else
+ run_or_record run_live_detection "$provider" 0
+ fi
+ ;;
+ *)
+ while IFS= read -r selected_provider; do
+ run_or_record run_e2e_smoke "$selected_provider" "$filter"
+ done < <(provider_list "$provider")
+ ;;
+ esac
+ done
+fi
+
+if [ "$failures" -ne 0 ]; then
+ echo ""
+ echo " ${ERROR}${BOLD}Smoke failed${NC}" >&2
+ exit 1
+fi
+
+echo ""
+echo " ${SUCCESS}${BOLD}Smoke complete${NC}"
diff --git a/scripts/docker-browser-parity-smoke.sh b/scripts/docker-browser-parity-smoke.sh
new file mode 100755
index 00000000..dae67319
--- /dev/null
+++ b/scripts/docker-browser-parity-smoke.sh
@@ -0,0 +1,774 @@
+#!/usr/bin/env bash
+# docker-browser-parity-smoke.sh — Browser-provider parity smoke harness.
+#
+# Runs the same fixture-backed endpoint assertions and API basic E2E suite
+# against both providers, sequentially, with full teardown between legs:
+#
+# chrome — standard pinchtab:local image (Chromium already bundled).
+# cloak — pinchtab-cloakbrowser:test image with the CloakBrowser binary
+# baked in via tests/tools/docker/cloakbrowser-smoke.Dockerfile.
+#
+# Provider-specific assertions:
+# chrome → /stealth/status.provider == "chrome"
+# cloak → /stealth/status.provider == "cloak" && .native == true
+# && .pinchtabOverlaysDisabled == true && .fingerprintSeed == "42069"
+#
+# This smoke is opt-in and NOT part of default CI / ./dev all.
+#
+# Usage:
+# ./dev smoke cloakbrowser # both legs (default)
+# ./dev smoke cloakbrowser --provider=chrome # Chrome leg only
+# ./dev smoke cloakbrowser --provider=cloak # Cloak leg only
+# ./dev smoke cloakbrowser --provider=all
+# ./dev smoke cloakbrowser --multi-target # one-container multi-target leg
+# ./dev smoke cloakbrowser --provider=all --multi-target # per-leg + multi-target
+# ./dev smoke cloakbrowser --profile-persistence # opt-in profile-persistence leg
+# # (Docker named volume + UUID round-trip;
+# # defaults to --provider=cloak,
+# # honors an explicit --provider=chrome)
+# ./dev smoke cloakbrowser --profile-lock-recovery
+# # opt-in lock-recovery leg (P3b):
+# # seeds the P3a marker, plants a stale
+# # Chrome SingletonLock referencing a
+# # probably-unused PID, restarts the
+# # container, and asserts PinchTab
+# # recovers cleanly without losing
+# # profile state. Mutually exclusive with
+# # --multi-target; defaults to
+# # --provider=cloak.
+#
+# Env overrides:
+# PINCHTAB_PARITY_CHROME_IMAGE Chrome leg image (default: pinchtab-local:test)
+# PINCHTAB_PARITY_CLOAK_IMAGE Cloak leg image (default: pinchtab-cloakbrowser:test)
+# PINCHTAB_CLOAKBROWSER_RUNNER_IMAGE E2E runner image (default: pinchtab-e2e-runner-api:cloak-smoke)
+# PINCHTAB_PARITY_E2E_SCENARIOS Override scenario list (space-separated)
+# PINCHTAB_CLOAKBROWSER_DOCKERFILE Path to Cloak smoke Dockerfile
+# PINCHTAB_CLOAKBROWSER_RUNNER_DOCKERFILE Runner Dockerfile path
+# SKIP_BUILD=1 Reuse existing provider image
+# SKIP_RUNNER_BUILD=1 Reuse existing E2E runner image
+#
+# Backwards compat:
+# PINCHTAB_CLOAKBROWSER_E2E_SCENARIOS honored on the cloak leg only.
+# First positional arg can be a Cloak image name (legacy).
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
+LIB_DIR="$SCRIPT_DIR/lib"
+
+# shellcheck source=lib/smoke-common.sh
+source "$LIB_DIR/smoke-common.sh"
+# shellcheck source=lib/smoke-config.sh
+source "$LIB_DIR/smoke-config.sh"
+# shellcheck source=lib/smoke-container.sh
+source "$LIB_DIR/smoke-container.sh"
+# shellcheck source=lib/smoke-health.sh
+source "$LIB_DIR/smoke-health.sh"
+# shellcheck source=lib/smoke-fixtures.sh
+source "$LIB_DIR/smoke-fixtures.sh"
+# shellcheck source=lib/smoke-endpoints.sh
+source "$LIB_DIR/smoke-endpoints.sh"
+# shellcheck source=lib/smoke-scenarios.sh
+source "$LIB_DIR/smoke-scenarios.sh"
+# shellcheck source=lib/smoke-diagnostics.sh
+source "$LIB_DIR/smoke-diagnostics.sh"
+# shellcheck source=lib/smoke-assertions.sh
+source "$LIB_DIR/smoke-assertions.sh"
+# shellcheck source=lib/smoke-multi-target.sh
+source "$LIB_DIR/smoke-multi-target.sh"
+# shellcheck source=lib/smoke-persistence.sh
+source "$LIB_DIR/smoke-persistence.sh"
+
+# ── CLI parsing ──────────────────────────────────────────────────────────────
+
+PROVIDERS_ARG=""
+MULTI_TARGET=0
+PROFILE_PERSISTENCE=0
+PROFILE_LOCK_RECOVERY=0
+LEGACY_CLOAK_IMAGE=""
+
+for arg in "$@"; do
+ case "$arg" in
+ --provider=*)
+ PROVIDERS_ARG="${arg#--provider=}"
+ ;;
+ --provider)
+ fail "--provider requires =VALUE (e.g. --provider=chrome)"
+ ;;
+ --multi-target)
+ MULTI_TARGET=1
+ ;;
+ --profile-persistence)
+ PROFILE_PERSISTENCE=1
+ ;;
+ --profile-lock-recovery)
+ PROFILE_LOCK_RECOVERY=1
+ ;;
+ --help|-h)
+ sed -n '2,52p' "$0"
+ exit 0
+ ;;
+ --*)
+ fail "unknown flag: $arg"
+ ;;
+ *)
+ if [ -z "$LEGACY_CLOAK_IMAGE" ]; then
+ LEGACY_CLOAK_IMAGE="$arg"
+ else
+ fail "unexpected positional arg: $arg"
+ fi
+ ;;
+ esac
+done
+
+PROVIDERS=()
+RUN_MULTI_TARGET=0
+RUN_PROFILE_PERSISTENCE=0
+RUN_PROFILE_LOCK_RECOVERY=0
+PERSISTENCE_PROVIDER=""
+LOCK_RECOVERY_PROVIDER=""
+if [ "$PROFILE_LOCK_RECOVERY" -eq 1 ]; then
+ if [ "$MULTI_TARGET" -eq 1 ]; then
+ fail "--profile-lock-recovery is mutually exclusive with --multi-target"
+ fi
+ case "${PROVIDERS_ARG:-cloak}" in
+ cloak) LOCK_RECOVERY_PROVIDER="cloak" ;;
+ chrome) LOCK_RECOVERY_PROVIDER="chrome" ;;
+ ""|all)
+ fail "--profile-lock-recovery requires a single provider (--provider=chrome or --provider=cloak; default cloak)"
+ ;;
+ *)
+ fail "invalid --provider for --profile-lock-recovery: $PROVIDERS_ARG (expected chrome|cloak)"
+ ;;
+ esac
+ RUN_PROFILE_LOCK_RECOVERY=1
+ # Lock-recovery internally invokes assert_persistence_round_trip, so
+ # --profile-persistence becomes a no-op subset here.
+ PROFILE_PERSISTENCE=0
+ RUN_PROFILE_PERSISTENCE=0
+ PROVIDERS=()
+elif [ "$PROFILE_PERSISTENCE" -eq 1 ]; then
+ if [ "$MULTI_TARGET" -eq 1 ]; then
+ fail "--profile-persistence is mutually exclusive with --multi-target"
+ fi
+ case "${PROVIDERS_ARG:-cloak}" in
+ cloak) PERSISTENCE_PROVIDER="cloak" ;;
+ chrome) PERSISTENCE_PROVIDER="chrome" ;;
+ ""|all)
+ fail "--profile-persistence requires a single provider (--provider=chrome or --provider=cloak; default cloak)"
+ ;;
+ *)
+ fail "invalid --provider for --profile-persistence: $PROVIDERS_ARG (expected chrome|cloak)"
+ ;;
+ esac
+ RUN_PROFILE_PERSISTENCE=1
+ PROVIDERS=()
+elif [ "$MULTI_TARGET" -eq 1 ]; then
+ case "$PROVIDERS_ARG" in
+ ""|all)
+ RUN_MULTI_TARGET=1
+ if [ "$PROVIDERS_ARG" = "all" ]; then
+ PROVIDERS=(chrome cloak)
+ fi
+ ;;
+ chrome|cloak)
+ fail "--multi-target is mutually exclusive with --provider=${PROVIDERS_ARG} (use --provider=all to run both)"
+ ;;
+ *)
+ fail "invalid --provider: $PROVIDERS_ARG (expected chrome|cloak|all)"
+ ;;
+ esac
+else
+ case "${PROVIDERS_ARG:-all}" in
+ all) PROVIDERS=(chrome cloak) ;;
+ chrome) PROVIDERS=(chrome) ;;
+ cloak) PROVIDERS=(cloak) ;;
+ *) fail "invalid --provider: $PROVIDERS_ARG (expected chrome|cloak|all)" ;;
+ esac
+fi
+
+CHROME_BASE_IMAGE="${PINCHTAB_PARITY_CHROME_BASE_IMAGE:-pinchtab-local:test}"
+CHROME_IMAGE="${PINCHTAB_PARITY_CHROME_IMAGE:-pinchtab-chrome-smoke:test}"
+CLOAK_IMAGE="${PINCHTAB_PARITY_CLOAK_IMAGE:-${LEGACY_CLOAK_IMAGE:-pinchtab-cloakbrowser:test}}"
+RUNNER_IMAGE="${PINCHTAB_CLOAKBROWSER_RUNNER_IMAGE:-pinchtab-e2e-runner-api:cloak-smoke}"
+CLOAK_CONTAINER_BIN="/opt/cloakbrowser/chrome"
+CLOAK_IMAGE_CHROME_BIN="${PINCHTAB_PARITY_MULTI_CHROME_BIN:-/usr/bin/chromium}"
+CHROME_DOCKERFILE="${PINCHTAB_PARITY_CHROME_DOCKERFILE:-tests/tools/docker/chrome-smoke.Dockerfile}"
+CLOAK_DOCKERFILE="${PINCHTAB_CLOAKBROWSER_DOCKERFILE:-tests/tools/docker/cloakbrowser-smoke.Dockerfile}"
+RUNNER_DOCKERFILE="${PINCHTAB_CLOAKBROWSER_RUNNER_DOCKERFILE:-tests/e2e/runner-api/Dockerfile}"
+
+# ── Prereqs ──────────────────────────────────────────────────────────────────
+
+FAILED=0
+command -v docker >/dev/null 2>&1 || skip "docker is not installed"
+require_cmd python3
+require_cmd jq
+require_cmd curl
+
+# ── Top-level TMP_DIR (legs use a per-leg sub-directory) ─────────────────────
+
+TOP_TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/pinchtab-browser-parity.XXXXXX")"
+
+TMP_DIR=""
+TOKEN=""
+NAME=""
+HOST_PORT=""
+HOST_FIXTURES_URL=""
+FIXTURES_URL=""
+FIXTURES_HOST=""
+FIXTURES_PORT=""
+CONFIG_PATH=""
+CONTAINER_STARTED=0
+FIXTURES_STARTED=0
+API_RESULT=""
+API_STATUS=""
+CURRENT_PROVIDER=""
+LEG_PROFILE_VOLUME=""
+
+declare -a LEG_RESULTS=()
+
+top_cleanup() {
+ set +e
+ if [ "$FAILED" -ne 0 ]; then
+ echo ""
+ echo "Artifacts kept at: $TOP_TMP_DIR"
+ else
+ rm -rf "$TOP_TMP_DIR"
+ fi
+}
+trap top_cleanup EXIT
+
+# ── Image builds ─────────────────────────────────────────────────────────────
+
+ensure_chrome_image() {
+ if [ "${SKIP_BUILD:-}" = "1" ]; then
+ if docker image inspect "$CHROME_IMAGE" >/dev/null 2>&1; then
+ echo "Using existing Chrome smoke image: $CHROME_IMAGE (SKIP_BUILD=1)"
+ return
+ fi
+ skip "Chrome smoke image $CHROME_IMAGE not found and SKIP_BUILD=1 is set"
+ fi
+
+ if ! docker image inspect "$CHROME_BASE_IMAGE" >/dev/null 2>&1; then
+ echo "Building base PinchTab image: $CHROME_BASE_IMAGE"
+ docker build -t "$CHROME_BASE_IMAGE" "$ROOT"
+ else
+ echo "Reusing existing base PinchTab image: $CHROME_BASE_IMAGE"
+ fi
+
+ echo "Building Chrome smoke overlay image: $CHROME_IMAGE (BASE_IMAGE=$CHROME_BASE_IMAGE)"
+ docker build \
+ -f "$ROOT/$CHROME_DOCKERFILE" \
+ --build-arg "BASE_IMAGE=$CHROME_BASE_IMAGE" \
+ -t "$CHROME_IMAGE" \
+ "$ROOT"
+}
+
+ensure_cloak_image() {
+ if [ "${SKIP_BUILD:-}" = "1" ]; then
+ if docker image inspect "$CLOAK_IMAGE" >/dev/null 2>&1; then
+ echo "Using existing Cloak image: $CLOAK_IMAGE (SKIP_BUILD=1)"
+ else
+ skip "Cloak image $CLOAK_IMAGE not found and SKIP_BUILD=1 is set"
+ fi
+ else
+ echo "Building PinchTab CloakBrowser Docker image: $CLOAK_IMAGE"
+ docker build -f "$ROOT/$CLOAK_DOCKERFILE" -t "$CLOAK_IMAGE" "$ROOT"
+ fi
+ docker run --rm --entrypoint /bin/sh "$CLOAK_IMAGE" -lc "test -x '$CLOAK_CONTAINER_BIN'" \
+ || fail "CloakBrowser binary not found in image at $CLOAK_CONTAINER_BIN"
+}
+
+ensure_runner_image() {
+ if [ "${SKIP_RUNNER_BUILD:-}" = "1" ]; then
+ if docker image inspect "$RUNNER_IMAGE" >/dev/null 2>&1; then
+ echo "Using existing E2E runner image: $RUNNER_IMAGE (SKIP_RUNNER_BUILD=1)"
+ return
+ fi
+ skip "E2E runner image $RUNNER_IMAGE not found and SKIP_RUNNER_BUILD=1 is set"
+ fi
+ echo "Building API E2E runner image: $RUNNER_IMAGE"
+ docker build -f "$ROOT/$RUNNER_DOCKERFILE" -t "$RUNNER_IMAGE" "$ROOT/tests/e2e/runner-api"
+}
+
+# ── Per-leg runner ───────────────────────────────────────────────────────────
+
+leg_cleanup() {
+ local rc=$?
+ set +e
+ if [ "$rc" -ne 0 ] && [ -n "$CURRENT_PROVIDER" ]; then
+ if [ "$CONTAINER_STARTED" -eq 1 ] && docker ps -a --format '{{.Names}}' | grep -Fxq "$NAME"; then
+ dump_diagnostics "$CURRENT_PROVIDER" "$NAME" "$HOST_PORT" "$TOKEN" "$CONFIG_PATH" "$FIXTURES_STARTED" || true
+ fi
+ fi
+ if [ -n "$NAME" ]; then
+ teardown_container "$NAME"
+ fi
+ if [ -n "${LEG_PROFILE_VOLUME:-}" ]; then
+ cleanup_profile_volume "$LEG_PROFILE_VOLUME"
+ LEG_PROFILE_VOLUME=""
+ fi
+ return $rc
+}
+
+run_leg() {
+ local provider="$1"
+ local image="$2"
+
+ echo ""
+ echo "=============================================="
+ echo "=== Browser parity leg: provider=${provider}"
+ echo "=============================================="
+
+ trap leg_cleanup EXIT
+
+ CURRENT_PROVIDER="$provider"
+ TMP_DIR="$TOP_TMP_DIR/$provider"
+ mkdir -p "$TMP_DIR"
+ TOKEN="pinchtab-parity-${provider}-${RANDOM}${RANDOM}"
+ NAME="pinchtab-parity-${provider}-${RANDOM}${RANDOM}"
+ HOST_PORT=""
+ CONTAINER_STARTED=0
+ FIXTURES_STARTED=0
+ API_RESULT=""
+ API_STATUS=""
+ FIXTURES_HOST="parity-${provider}-fixtures.local"
+ FIXTURES_PORT="$(choose_free_port)"
+ HOST_FIXTURES_URL="http://127.0.0.1:${FIXTURES_PORT}"
+ FIXTURES_URL="http://${FIXTURES_HOST}:${FIXTURES_PORT}"
+ CONFIG_PATH="$TMP_DIR/pinchtab-${provider}.json"
+
+ if [ "$provider" = "cloak" ]; then
+ write_provider_config "$provider" "$CONFIG_PATH" "$TOKEN" "$FIXTURES_HOST" "" "$CLOAK_CONTAINER_BIN"
+ else
+ write_provider_config "$provider" "$CONFIG_PATH" "$TOKEN" "$FIXTURES_HOST" "" ""
+ fi
+
+ start_provider_container "$NAME" "$image" "$CONFIG_PATH" "$FIXTURES_HOST" "$FIXTURES_PORT" "$ROOT"
+ HOST_PORT="$(resolve_host_port "$NAME")"
+ echo "Container $NAME up — PinchTab on host port $HOST_PORT"
+
+ start_fixture_server "$NAME" "$FIXTURES_PORT"
+ wait_fixtures_ready "$NAME" "$FIXTURES_URL" "$HOST_FIXTURES_URL"
+
+ echo "Waiting for PinchTab health on :${HOST_PORT}..."
+ wait_for_health "$HOST_PORT" "$TOKEN"
+
+ local uid
+ uid="$(docker exec "$NAME" id -u | tr -d '\r')"
+ [ "$uid" != "0" ] || fail "container is running as root; expected non-root user"
+
+ local shm_mb
+ shm_mb="$(docker exec "$NAME" sh -lc "df -Pm /dev/shm | awk 'NR==2 {print \$2}'" | tr -d '\r')"
+ if [ "${shm_mb:-0}" -lt 1024 ]; then
+ fail "/dev/shm too small: ${shm_mb:-unknown} MB"
+ fi
+
+ docker exec "$NAME" sh -lc \
+ 'if command -v fc-list >/dev/null 2>&1; then fc-list | grep -q .; else find /usr/share/fonts -type f 2>/dev/null | head -1 | grep -q .; fi' \
+ || fail "no fonts found in container"
+
+ echo "Waiting for managed ${provider} instance..."
+ wait_for_instance_running "$HOST_PORT" "$TOKEN"
+
+ assert_stealth_status "$provider"
+ run_fixture_endpoint_smoke
+ run_e2e_scenarios "$provider" "$NAME"
+
+ echo "Leg passed: provider=${provider}"
+}
+
+# ── Multi-target leg ─────────────────────────────────────────────────────────
+
+ensure_multi_target_image_binaries() {
+ # Fail-fast: verify both browser binaries are still present in the shared
+ # Cloak smoke image before launching the multi-target container.
+ docker run --rm --entrypoint /bin/sh "$CLOAK_IMAGE" -lc \
+ "test -x '$CLOAK_CONTAINER_BIN' && test -x '$CLOAK_IMAGE_CHROME_BIN'" \
+ || fail "multi-target leg: image $CLOAK_IMAGE must contain both $CLOAK_CONTAINER_BIN and $CLOAK_IMAGE_CHROME_BIN"
+}
+
+run_multi_target_leg() {
+ echo ""
+ echo "=============================================="
+ echo "=== Browser parity leg: multi-target"
+ echo "=============================================="
+
+ trap leg_cleanup EXIT
+
+ CURRENT_PROVIDER="multi-target"
+ TMP_DIR="$TOP_TMP_DIR/multi-target"
+ mkdir -p "$TMP_DIR"
+ TOKEN="pinchtab-parity-multi-${RANDOM}${RANDOM}"
+ NAME="pinchtab-parity-multi-${RANDOM}${RANDOM}"
+ HOST_PORT=""
+ CONTAINER_STARTED=0
+ FIXTURES_STARTED=0
+ API_RESULT=""
+ API_STATUS=""
+ FIXTURES_HOST="parity-multi-fixtures.local"
+ FIXTURES_PORT="$(choose_free_port)"
+ HOST_FIXTURES_URL="http://127.0.0.1:${FIXTURES_PORT}"
+ FIXTURES_URL="http://${FIXTURES_HOST}:${FIXTURES_PORT}"
+ CONFIG_PATH="$TMP_DIR/pinchtab-multi.json"
+
+ # Stub lives on the host so the non-root container user can exec it via bind-mount.
+ local broken_host="$TMP_DIR/broken-chrome.sh"
+ setup_broken_binary "$broken_host" >/dev/null
+ local broken_container="/opt/broken-chrome.sh"
+
+ write_multi_target_config \
+ "$CONFIG_PATH" "$TOKEN" "$FIXTURES_HOST" \
+ "$CLOAK_IMAGE_CHROME_BIN" "$CLOAK_CONTAINER_BIN"
+ jq -e '.browser.targets.chrome and .browser.targets.cloak and .browser.defaultTarget == "chrome" and (.browser.fallbackOrder | index("chrome") != null) and (.browser.fallbackOrder | index("cloak") != null)' \
+ "$CONFIG_PATH" >/dev/null \
+ || fail "generated multi-target config is malformed: $(cat "$CONFIG_PATH")"
+
+ docker run -d \
+ --name "$NAME" \
+ --user 1000:1000 \
+ --shm-size=2g \
+ --tmpfs /data:rw,size=1024m,uid=1000,gid=1000,mode=0755 \
+ --tmpfs /tmp:rw,size=512m,mode=1777 \
+ --add-host "${FIXTURES_HOST}:127.0.0.1" \
+ -e "PINCHTAB_CONFIG=/config/pinchtab.json" \
+ -v "${CONFIG_PATH}:/config/pinchtab.json:ro" \
+ -v "${broken_host}:${broken_container}:ro" \
+ -v "${ROOT}/tests/e2e/fixtures:/fixtures:ro" \
+ -v "${ROOT}/tests/tools/fixtures/static-server.pl:/usr/local/bin/fixture-server.pl:ro" \
+ --publish "127.0.0.1::9867" \
+ --publish "127.0.0.1:${FIXTURES_PORT}:${FIXTURES_PORT}" \
+ "$CLOAK_IMAGE" >/dev/null
+ CONTAINER_STARTED=1
+
+ HOST_PORT="$(resolve_host_port "$NAME")"
+ echo "Container $NAME up — PinchTab on host port $HOST_PORT (multi-target)"
+
+ start_fixture_server "$NAME" "$FIXTURES_PORT"
+ wait_fixtures_ready "$NAME" "$FIXTURES_URL" "$HOST_FIXTURES_URL"
+
+ echo "Waiting for PinchTab health on :${HOST_PORT}..."
+ wait_for_health "$HOST_PORT" "$TOKEN"
+
+ echo "→ Phase A: per-request target selection"
+ assert_target_selection "$HOST_PORT" "$TOKEN" "chrome" "chrome"
+ assert_target_selection "$HOST_PORT" "$TOKEN" "cloak" "cloak"
+
+ echo "→ Phase B: default target resolution"
+ assert_default_target "$HOST_PORT" "$TOKEN" "chrome"
+
+ # Phase C uses a second config that points the chrome target at the broken
+ # stub, then restarts the container so PinchTab loads it.
+ local broken_cfg="$TMP_DIR/pinchtab-multi-broken.json"
+ write_multi_target_config \
+ "$broken_cfg" "$TOKEN" "$FIXTURES_HOST" \
+ "$CLOAK_IMAGE_CHROME_BIN" "$CLOAK_CONTAINER_BIN" \
+ "$broken_container"
+
+ echo "→ Phase C: fallback (restarting container with broken chrome primary)"
+ teardown_container "$NAME"
+ CONTAINER_STARTED=0
+ FIXTURES_STARTED=0
+
+ docker run -d \
+ --name "$NAME" \
+ --user 1000:1000 \
+ --shm-size=2g \
+ --tmpfs /data:rw,size=1024m,uid=1000,gid=1000,mode=0755 \
+ --tmpfs /tmp:rw,size=512m,mode=1777 \
+ --add-host "${FIXTURES_HOST}:127.0.0.1" \
+ -e "PINCHTAB_CONFIG=/config/pinchtab.json" \
+ -v "${broken_cfg}:/config/pinchtab.json:ro" \
+ -v "${broken_host}:${broken_container}:ro" \
+ -v "${ROOT}/tests/e2e/fixtures:/fixtures:ro" \
+ -v "${ROOT}/tests/tools/fixtures/static-server.pl:/usr/local/bin/fixture-server.pl:ro" \
+ --publish "127.0.0.1::9867" \
+ --publish "127.0.0.1:${FIXTURES_PORT}:${FIXTURES_PORT}" \
+ "$CLOAK_IMAGE" >/dev/null
+ CONTAINER_STARTED=1
+ HOST_PORT="$(resolve_host_port "$NAME")"
+ start_fixture_server "$NAME" "$FIXTURES_PORT"
+ wait_fixtures_ready "$NAME" "$FIXTURES_URL" "$HOST_FIXTURES_URL"
+ wait_for_health "$HOST_PORT" "$TOKEN"
+ CONFIG_PATH="$broken_cfg"
+
+ assert_fallback "$HOST_PORT" "$TOKEN" "chrome" "cloak" "cloak"
+
+ echo "Leg passed: multi-target"
+}
+
+# Profile-persistence leg (P3a): single provider against a Docker named
+# volume; navigates a marker fixture, restarts container, asserts marker
+# survives. Opt-in only.
+
+run_profile_persistence_leg() {
+ local provider="$1"
+ local image="$2"
+
+ echo ""
+ echo "=============================================="
+ echo "=== Browser parity leg: profile-persistence (provider=${provider})"
+ echo "=============================================="
+
+ trap leg_cleanup EXIT
+
+ CURRENT_PROVIDER="persistence-${provider}"
+ TMP_DIR="$TOP_TMP_DIR/persistence-${provider}"
+ mkdir -p "$TMP_DIR"
+ TOKEN="pinchtab-persistence-${provider}-${RANDOM}${RANDOM}"
+ NAME="pinchtab-persistence-${provider}-${RANDOM}${RANDOM}"
+ HOST_PORT=""
+ CONTAINER_STARTED=0
+ FIXTURES_STARTED=0
+ API_RESULT=""
+ API_STATUS=""
+ FIXTURES_HOST="persistence-${provider}-fixtures.local"
+ FIXTURES_PORT="$(choose_free_port)"
+ HOST_FIXTURES_URL="http://127.0.0.1:${FIXTURES_PORT}"
+ FIXTURES_URL="http://${FIXTURES_HOST}:${FIXTURES_PORT}"
+ CONFIG_PATH="$TMP_DIR/pinchtab-${provider}.json"
+ LEG_PROFILE_VOLUME="pinchtab-persistence-${provider}-$$-${RANDOM}"
+
+ # Identical config bytes are reused on restart.
+ if [ "$provider" = "cloak" ]; then
+ write_provider_config "$provider" "$CONFIG_PATH" "$TOKEN" "$FIXTURES_HOST" "" "$CLOAK_CONTAINER_BIN"
+ else
+ write_provider_config "$provider" "$CONFIG_PATH" "$TOKEN" "$FIXTURES_HOST" "" ""
+ fi
+ jq -e '.server.stateDir == "/data"' "$CONFIG_PATH" >/dev/null \
+ || fail "persistence leg: generated config did not set server.stateDir=/data"
+
+ setup_profile_volume "$LEG_PROFILE_VOLUME" >/dev/null
+ echo "Profile volume ready: $LEG_PROFILE_VOLUME"
+
+ PROFILE_VOLUME="$LEG_PROFILE_VOLUME" start_provider_container \
+ "$NAME" "$image" "$CONFIG_PATH" "$FIXTURES_HOST" "$FIXTURES_PORT" "$ROOT"
+ HOST_PORT="$(resolve_host_port "$NAME")"
+ echo "Container $NAME up — PinchTab on host port $HOST_PORT (volume=$LEG_PROFILE_VOLUME)"
+
+ start_fixture_server "$NAME" "$FIXTURES_PORT"
+ wait_fixtures_ready "$NAME" "$FIXTURES_URL" "$HOST_FIXTURES_URL"
+
+ echo "Waiting for PinchTab health on :${HOST_PORT}..."
+ wait_for_health "$HOST_PORT" "$TOKEN"
+ echo "Waiting for managed ${provider} instance..."
+ wait_for_instance_running "$HOST_PORT" "$TOKEN"
+
+ assert_persistence_round_trip \
+ "$provider" "$image" "$NAME" "$CONFIG_PATH" \
+ "$FIXTURES_HOST" "$FIXTURES_PORT" \
+ "$FIXTURES_URL" "$HOST_FIXTURES_URL" \
+ "$TOKEN" "$ROOT" "$LEG_PROFILE_VOLUME"
+
+ echo "Leg passed: profile-persistence (provider=${provider})"
+}
+
+# Profile-lock-recovery leg (P3b): strict superset of P3a. After the
+# persistence round-trip, plants stale SingletonLock/Socket/Cookie referencing
+# an unused PID and asserts PinchTab recovers cleanly. Opt-in only.
+
+run_profile_lock_recovery_leg() {
+ local provider="$1"
+ local image="$2"
+
+ echo ""
+ echo "=============================================="
+ echo "=== Browser parity leg: profile-lock-recovery (provider=${provider})"
+ echo "=============================================="
+
+ trap leg_cleanup EXIT
+
+ CURRENT_PROVIDER="lock-recovery-${provider}"
+ TMP_DIR="$TOP_TMP_DIR/lock-recovery-${provider}"
+ mkdir -p "$TMP_DIR"
+ TOKEN="pinchtab-lockrec-${provider}-${RANDOM}${RANDOM}"
+ NAME="pinchtab-lockrec-${provider}-${RANDOM}${RANDOM}"
+ HOST_PORT=""
+ CONTAINER_STARTED=0
+ FIXTURES_STARTED=0
+ API_RESULT=""
+ API_STATUS=""
+ FIXTURES_HOST="lockrec-${provider}-fixtures.local"
+ FIXTURES_PORT="$(choose_free_port)"
+ HOST_FIXTURES_URL="http://127.0.0.1:${FIXTURES_PORT}"
+ FIXTURES_URL="http://${FIXTURES_HOST}:${FIXTURES_PORT}"
+ CONFIG_PATH="$TMP_DIR/pinchtab-${provider}.json"
+ LEG_PROFILE_VOLUME="pinchtab-lockrec-${provider}-$$-${RANDOM}"
+
+ # Config bytes must be byte-stable across the two restarts in this flow.
+ if [ "$provider" = "cloak" ]; then
+ write_provider_config "$provider" "$CONFIG_PATH" "$TOKEN" "$FIXTURES_HOST" "" "$CLOAK_CONTAINER_BIN"
+ else
+ write_provider_config "$provider" "$CONFIG_PATH" "$TOKEN" "$FIXTURES_HOST" "" ""
+ fi
+ jq -e '.server.stateDir == "/data"' "$CONFIG_PATH" >/dev/null \
+ || fail "lock-recovery leg: generated config did not set server.stateDir=/data"
+
+ # The live profile name (queried below) is not always profiles.defaultProfile —
+ # the cloak orchestrator currently launches a hard-coded "default" profile.
+ local profile_basedir
+ profile_basedir="$(jq -r '.profiles.baseDir // empty' "$CONFIG_PATH")"
+ [ -n "$profile_basedir" ] || fail "lock-recovery leg: profiles.baseDir missing"
+ local profile_basedir_rel="${profile_basedir#/data/}"
+
+ setup_profile_volume "$LEG_PROFILE_VOLUME" >/dev/null
+ echo "Profile volume ready: $LEG_PROFILE_VOLUME"
+
+ PROFILE_VOLUME="$LEG_PROFILE_VOLUME" start_provider_container \
+ "$NAME" "$image" "$CONFIG_PATH" "$FIXTURES_HOST" "$FIXTURES_PORT" "$ROOT"
+ HOST_PORT="$(resolve_host_port "$NAME")"
+ echo "Container $NAME up — PinchTab on host port $HOST_PORT (volume=$LEG_PROFILE_VOLUME)"
+
+ start_fixture_server "$NAME" "$FIXTURES_PORT"
+ wait_fixtures_ready "$NAME" "$FIXTURES_URL" "$HOST_FIXTURES_URL"
+
+ echo "Waiting for PinchTab health on :${HOST_PORT}..."
+ wait_for_health "$HOST_PORT" "$TOKEN"
+ echo "Waiting for managed ${provider} instance..."
+ wait_for_instance_running "$HOST_PORT" "$TOKEN"
+
+ local live_profile_name
+ live_profile_name="$(curl -fsS -H "Authorization: Bearer ${TOKEN}" \
+ "http://127.0.0.1:${HOST_PORT}/instances" 2>/dev/null \
+ | jq -r '.[]? | select(.status=="running") | .profileName' | head -1)"
+ [ -n "$live_profile_name" ] || fail "lock-recovery leg: could not discover live profile name from /instances"
+ local profile_subpath="${profile_basedir_rel}/${live_profile_name}"
+ echo "Discovered live profile subpath: ${profile_subpath}"
+
+ assert_lock_recovery_round_trip \
+ "$provider" "$image" "$NAME" "$CONFIG_PATH" \
+ "$FIXTURES_HOST" "$FIXTURES_PORT" \
+ "$FIXTURES_URL" "$HOST_FIXTURES_URL" \
+ "$TOKEN" "$ROOT" "$LEG_PROFILE_VOLUME" "$profile_subpath"
+
+ echo "Leg passed: profile-lock-recovery (provider=${provider})"
+}
+
+# ── Drive the legs ───────────────────────────────────────────────────────────
+
+for p in "${PROVIDERS[@]}"; do
+ case "$p" in
+ chrome) ensure_chrome_image ;;
+ cloak) ensure_cloak_image ;;
+ esac
+done
+if [ "$RUN_MULTI_TARGET" -eq 1 ]; then
+ ensure_cloak_image
+ ensure_multi_target_image_binaries
+fi
+if [ "$RUN_PROFILE_PERSISTENCE" -eq 1 ]; then
+ case "$PERSISTENCE_PROVIDER" in
+ cloak) ensure_cloak_image ;;
+ chrome) ensure_chrome_image ;;
+ esac
+fi
+if [ "$RUN_PROFILE_LOCK_RECOVERY" -eq 1 ]; then
+ case "$LOCK_RECOVERY_PROVIDER" in
+ cloak) ensure_cloak_image ;;
+ chrome) ensure_chrome_image ;;
+ esac
+fi
+if [ "${#PROVIDERS[@]}" -gt 0 ]; then
+ ensure_runner_image
+fi
+
+OVERALL_FAILED=0
+
+for p in "${PROVIDERS[@]}"; do
+ case "$p" in
+ chrome) leg_image="$CHROME_IMAGE" ;;
+ cloak) leg_image="$CLOAK_IMAGE" ;;
+ *) fail "unsupported provider: $p" ;;
+ esac
+
+ # Subshell isolates a leg failure from later legs; its leg_cleanup trap
+ # handles diagnostics + teardown.
+ if (
+ set -e
+ FAILED=0
+ run_leg "$p" "$leg_image"
+ ); then
+ LEG_RESULTS+=("$p:PASS")
+ else
+ leg_status=$?
+ LEG_RESULTS+=("$p:FAIL($leg_status)")
+ OVERALL_FAILED=1
+ echo ""
+ echo "Leg failed: provider=${p} (continuing with remaining legs)"
+ fi
+done
+
+if [ "$RUN_MULTI_TARGET" -eq 1 ]; then
+ if (
+ set -e
+ FAILED=0
+ run_multi_target_leg
+ ); then
+ LEG_RESULTS+=("multi-target:PASS")
+ else
+ leg_status=$?
+ LEG_RESULTS+=("multi-target:FAIL($leg_status)")
+ OVERALL_FAILED=1
+ echo ""
+ echo "Leg failed: multi-target"
+ fi
+fi
+
+if [ "$RUN_PROFILE_PERSISTENCE" -eq 1 ]; then
+ case "$PERSISTENCE_PROVIDER" in
+ cloak) persistence_image="$CLOAK_IMAGE" ;;
+ chrome) persistence_image="$CHROME_IMAGE" ;;
+ *) fail "unsupported persistence provider: $PERSISTENCE_PROVIDER" ;;
+ esac
+ if (
+ set -e
+ FAILED=0
+ run_profile_persistence_leg "$PERSISTENCE_PROVIDER" "$persistence_image"
+ ); then
+ LEG_RESULTS+=("profile-persistence(${PERSISTENCE_PROVIDER}):PASS")
+ else
+ leg_status=$?
+ LEG_RESULTS+=("profile-persistence(${PERSISTENCE_PROVIDER}):FAIL($leg_status)")
+ OVERALL_FAILED=1
+ echo ""
+ echo "Leg failed: profile-persistence (${PERSISTENCE_PROVIDER})"
+ fi
+fi
+
+if [ "$RUN_PROFILE_LOCK_RECOVERY" -eq 1 ]; then
+ case "$LOCK_RECOVERY_PROVIDER" in
+ cloak) lock_recovery_image="$CLOAK_IMAGE" ;;
+ chrome) lock_recovery_image="$CHROME_IMAGE" ;;
+ *) fail "unsupported lock-recovery provider: $LOCK_RECOVERY_PROVIDER" ;;
+ esac
+ if (
+ set -e
+ FAILED=0
+ run_profile_lock_recovery_leg "$LOCK_RECOVERY_PROVIDER" "$lock_recovery_image"
+ ); then
+ LEG_RESULTS+=("profile-lock-recovery(${LOCK_RECOVERY_PROVIDER}):PASS")
+ else
+ leg_status=$?
+ LEG_RESULTS+=("profile-lock-recovery(${LOCK_RECOVERY_PROVIDER}):FAIL($leg_status)")
+ OVERALL_FAILED=1
+ echo ""
+ echo "Leg failed: profile-lock-recovery (${LOCK_RECOVERY_PROVIDER})"
+ fi
+fi
+
+echo ""
+echo "=============================================="
+echo "Browser parity smoke summary"
+for r in "${LEG_RESULTS[@]}"; do
+ echo " - $r"
+done
+echo "=============================================="
+
+if [ "$OVERALL_FAILED" -ne 0 ]; then
+ FAILED=1
+ echo "FAIL: at least one provider leg failed" >&2
+ exit 1
+fi
+
+echo "OK: docker-browser-parity-smoke"
diff --git a/scripts/docker-cdp-attach-smoke.sh b/scripts/docker-cdp-attach-smoke.sh
new file mode 100755
index 00000000..4cb1964e
--- /dev/null
+++ b/scripts/docker-cdp-attach-smoke.sh
@@ -0,0 +1,325 @@
+#!/usr/bin/env bash
+# docker-cdp-attach-smoke.sh — Opt-in smoke for the CDP attach bridge path.
+#
+# Two legs:
+# 1. Chrome CDP attach — starts a Chromium headless container with remote
+# debugging enabled, runs the PinchTab server on the host, POSTs to
+# /instances/attach with provider=chrome, and asserts the bridge wraps it.
+# 2. CloakBrowser CDP attach — same as above but uses the local
+# pinchtab-cloakbrowser:test image. Skipped if the image is unavailable.
+#
+# This smoke is opt-in and is NOT part of default CI.
+#
+# Usage:
+# ./dev smoke cdp-attach # both legs
+# ./dev smoke cdp-attach chrome # Chrome leg only
+# ./dev smoke cdp-attach cloak # CloakBrowser leg only
+#
+# Env overrides:
+# PINCHTAB_BINARY Path to the pinchtab binary (default: ./dist/pinchtab or `go run`)
+# PINCHTAB_CDP_PORT Host port for the external CDP browser (default: 19222)
+# PINCHTAB_SERVER_PORT Host port for PinchTab server (default: 19867)
+# PINCHTAB_CDP_SMOKE_CHROME_IMAGE Chrome image (default: chromedp/headless-shell:stable)
+# PINCHTAB_CDP_SMOKE_CLOAK_IMAGE CloakBrowser image (default: pinchtab-cloakbrowser:test)
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
+
+LEG="${1:-all}"
+
+CHROME_IMAGE="${PINCHTAB_CDP_SMOKE_CHROME_IMAGE:-chromedp/headless-shell:stable}"
+CLOAK_IMAGE="${PINCHTAB_CDP_SMOKE_CLOAK_IMAGE:-pinchtab-cloakbrowser:test}"
+CDP_PORT="${PINCHTAB_CDP_PORT:-19222}"
+SERVER_PORT="${PINCHTAB_SERVER_PORT:-19867}"
+CLOAK_DEVTOOLS_PORT="9222"
+CLOAK_FORWARD_PORT="9223"
+
+TOKEN="cdp-attach-smoke-${RANDOM}${RANDOM}"
+TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/pinchtab-cdp-attach.XXXXXX")"
+CHROME_CONTAINER="pinchtab-cdp-smoke-chrome-${RANDOM}"
+CLOAK_CONTAINER="pinchtab-cdp-smoke-cloak-${RANDOM}"
+PINCHTAB_PID=""
+FAILED=0
+ATTACHED_INSTANCE_ID=""
+
+cleanup() {
+ set +e
+ if [ -n "${PINCHTAB_PID}" ] && kill -0 "${PINCHTAB_PID}" 2>/dev/null; then
+ kill "${PINCHTAB_PID}" 2>/dev/null || true
+ wait "${PINCHTAB_PID}" 2>/dev/null || true
+ fi
+ docker rm -f "${CHROME_CONTAINER}" >/dev/null 2>&1 || true
+ docker rm -f "${CLOAK_CONTAINER}" >/dev/null 2>&1 || true
+ if [ "${FAILED}" -ne 0 ]; then
+ echo ""
+ echo "Artifacts kept at: ${TMP_DIR}"
+ else
+ rm -rf "${TMP_DIR}"
+ fi
+}
+trap cleanup EXIT
+
+fail() {
+ FAILED=1
+ echo "FAIL: $*" >&2
+ exit 1
+}
+
+skip() {
+ echo "SKIP: $*"
+ exit 77
+}
+
+require_cmd() {
+ command -v "$1" >/dev/null 2>&1 || fail "$1 not found in PATH"
+}
+
+require_cmd docker
+require_cmd curl
+require_cmd jq
+
+BIN="${PINCHTAB_BINARY:-}"
+if [ -z "${BIN}" ]; then
+ if [ -x "${ROOT}/dist/pinchtab" ]; then
+ BIN="${ROOT}/dist/pinchtab"
+ else
+ echo "Building pinchtab binary…"
+ (cd "${ROOT}" && go build -o "${TMP_DIR}/pinchtab" ./cmd/pinchtab)
+ BIN="${TMP_DIR}/pinchtab"
+ fi
+fi
+[ -x "${BIN}" ] || fail "pinchtab binary not executable at ${BIN}"
+
+CONFIG_FILE="${TMP_DIR}/config.json"
+write_config() {
+ local provider="$1" binary="${2:-}"
+ cat > "${CONFIG_FILE}" <<EOF
+{
+ "server": { "port": "${SERVER_PORT}", "bind": "127.0.0.1", "token": "${TOKEN}" },
+ "browser": { "provider": "${provider}", "binary": "${binary}" },
+ "security": {
+ "attach": {
+ "enabled": true,
+ "allowHosts": ["127.0.0.1", "localhost", "::1"],
+ "allowSchemes": ["ws", "http"]
+ }
+ }
+}
+EOF
+}
+
+wait_http() {
+ local url="$1" tries="${2:-60}"
+ for _ in $(seq 1 "${tries}"); do
+ if curl -fsS "${url}" >/dev/null 2>&1; then return 0; fi
+ sleep 0.5
+ done
+ return 1
+}
+
+wait_api_http() {
+ local url="$1" tries="${2:-60}"
+ for _ in $(seq 1 "${tries}"); do
+ if curl -fsS -H "Authorization: Bearer ${TOKEN}" "${url}" >/dev/null 2>&1; then return 0; fi
+ sleep 0.5
+ done
+ return 1
+}
+
+api_post() {
+ local path="$1" body="$2"
+ curl -sS -X POST -H "Authorization: Bearer ${TOKEN}" -H "Content-Type: application/json" \
+ -d "${body}" "http://127.0.0.1:${SERVER_PORT}${path}"
+}
+
+api_get() {
+ local path="$1"
+ curl -sS -H "Authorization: Bearer ${TOKEN}" "http://127.0.0.1:${SERVER_PORT}${path}"
+}
+
+start_pinchtab() {
+ echo ">>> Starting PinchTab server on :${SERVER_PORT}"
+ PINCHTAB_TOKEN="${TOKEN}" PINCHTAB_CONFIG="${CONFIG_FILE}" \
+ "${BIN}" server >"${TMP_DIR}/pinchtab.log" 2>&1 &
+ PINCHTAB_PID=$!
+ if ! wait_api_http "http://127.0.0.1:${SERVER_PORT}/health" 60; then
+ cat "${TMP_DIR}/pinchtab.log" || true
+ fail "PinchTab server did not become healthy"
+ fi
+ echo " pinchtab pid=${PINCHTAB_PID}"
+}
+
+stop_pinchtab() {
+ if [ -n "${PINCHTAB_PID}" ] && kill -0 "${PINCHTAB_PID}" 2>/dev/null; then
+ kill "${PINCHTAB_PID}" 2>/dev/null || true
+ wait "${PINCHTAB_PID}" 2>/dev/null || true
+ fi
+ PINCHTAB_PID=""
+}
+
+assert_attached_instance() {
+ local name="$1" provider="$2"
+ local resp http
+ resp="$(api_post /instances/attach "$(jq -nc \
+ --arg name "${name}" \
+ --arg url "http://127.0.0.1:${CDP_PORT}" \
+ --arg provider "${provider}" \
+ '{name:$name, cdpUrl:$url, provider:$provider}')")"
+ echo " /instances/attach response: ${resp}" >&2
+ echo "${resp}" | jq -e '.attached == true' >/dev/null || fail "attached != true"
+ echo "${resp}" | jq -e '.attachType == "cdp-bridge"' >/dev/null || fail "attachType != cdp-bridge"
+ echo "${resp}" | jq -e '.url | startswith("http://")' >/dev/null || fail "url is not http:// bridge URL"
+ local inst_id
+ inst_id="$(echo "${resp}" | jq -r '.id')"
+ [ -n "${inst_id}" ] && [ "${inst_id}" != "null" ] || fail "missing instance id"
+ ATTACHED_INSTANCE_ID="${inst_id}"
+
+ echo ">>> Asserting /instances lists attached instance" >&2
+ api_get /instances | jq -e --arg id "${inst_id}" '.[] | select(.id == $id)' >/dev/null \
+ || fail "/instances does not list the attached instance"
+
+ echo ">>> Asserting /stealth/status reports launchMode=remote-cdp" >&2
+ local status
+ status="$(api_get /stealth/status || true)"
+ echo " /stealth/status: ${status}" >&2
+ echo "${status}" | jq -e --arg p "${provider}" '.provider == $p' >/dev/null \
+ || echo " (warning) provider mismatch in /stealth/status" >&2
+}
+
+stop_attached_instance() {
+ local inst_id="$1"
+ local resp
+ resp="$(api_post "/instances/${inst_id}/stop" '')"
+ echo " /instances/${inst_id}/stop response: ${resp}"
+ echo "${resp}" | jq -e '.status == "stopped"' >/dev/null || fail "attached instance stop did not report stopped"
+}
+
+run_chrome_leg() {
+ echo ""
+ echo "=== Chrome CDP attach leg ==="
+
+ echo ">>> Starting Chromium container on :${CDP_PORT}"
+ local -a docker_args=(
+ docker run -d --rm --name "${CHROME_CONTAINER}"
+ -p "127.0.0.1:${CDP_PORT}:9222" \
+ "${CHROME_IMAGE}"
+ )
+ case "${CHROME_IMAGE}" in
+ chromedp/headless-shell*)
+ # The chromedp image entrypoint starts headless-shell on an internal
+ # DevTools port and forwards container :9222 with socat. Passing our own
+ # --remote-debugging-port=9222 makes headless-shell race that forwarder.
+ ;;
+ *)
+ docker_args+=(
+ --remote-debugging-address=0.0.0.0
+ --remote-debugging-port=9222
+ --no-sandbox
+ --disable-dev-shm-usage
+ --headless
+ )
+ ;;
+ esac
+ "${docker_args[@]}" >/dev/null
+
+ if ! wait_http "http://127.0.0.1:${CDP_PORT}/json/version" 60; then
+ docker logs "${CHROME_CONTAINER}" | tail -50 || true
+ fail "Chromium DevTools not reachable on :${CDP_PORT}"
+ fi
+
+ write_config "chrome"
+ start_pinchtab
+ ATTACHED_INSTANCE_ID=""
+ assert_attached_instance "smoke-chrome" "chrome"
+ local inst_id="${ATTACHED_INSTANCE_ID}"
+
+ echo ">>> Stopping attached PinchTab instance ${inst_id}"
+ stop_attached_instance "${inst_id}"
+
+ echo ">>> Verifying external Chromium container is still running"
+ if ! docker ps --format '{{.Names}}' | grep -Fxq "${CHROME_CONTAINER}"; then
+ fail "external Chromium container was killed by stop (must not happen)"
+ fi
+ echo " OK — external browser process preserved."
+
+ stop_pinchtab
+ docker rm -f "${CHROME_CONTAINER}" >/dev/null 2>&1 || true
+ echo "Chrome leg PASS"
+}
+
+run_cloak_leg() {
+ echo ""
+ echo "=== CloakBrowser CDP attach leg ==="
+ if ! docker image inspect "${CLOAK_IMAGE}" >/dev/null 2>&1; then
+ skip "CloakBrowser image '${CLOAK_IMAGE}' not present — build with tests/tools/docker/cloakbrowser-smoke.Dockerfile to enable"
+ fi
+ if ! docker run --rm --entrypoint /bin/sh "${CLOAK_IMAGE}" -lc 'command -v socat >/dev/null 2>&1'; then
+ fail "CloakBrowser image '${CLOAK_IMAGE}' is missing socat; rebuild with tests/tools/docker/cloakbrowser-smoke.Dockerfile"
+ fi
+
+ echo ">>> Starting CloakBrowser container on :${CDP_PORT}"
+ docker run -d --rm --name "${CLOAK_CONTAINER}" \
+ -p "127.0.0.1:${CDP_PORT}:${CLOAK_FORWARD_PORT}" \
+ -e CLOAK_DEVTOOLS_PORT="${CLOAK_DEVTOOLS_PORT}" \
+ -e CLOAK_FORWARD_PORT="${CLOAK_FORWARD_PORT}" \
+ "${CLOAK_IMAGE}" \
+ /bin/sh -lc '
+ set -e
+ /opt/cloakbrowser/chrome \
+ --remote-debugging-address=127.0.0.1 \
+ --remote-debugging-port="${CLOAK_DEVTOOLS_PORT}" \
+ --no-sandbox \
+ --headless &
+ browser_pid=$!
+ trap "kill ${browser_pid} 2>/dev/null || true" TERM INT EXIT
+ for _ in $(seq 1 120); do
+ if curl -fsS "http://127.0.0.1:${CLOAK_DEVTOOLS_PORT}/json/version" >/dev/null 2>&1; then
+ exec socat "TCP-LISTEN:${CLOAK_FORWARD_PORT},fork,reuseaddr,bind=0.0.0.0" "TCP:127.0.0.1:${CLOAK_DEVTOOLS_PORT}"
+ fi
+ if ! kill -0 "${browser_pid}" 2>/dev/null; then
+ wait "${browser_pid}"
+ exit $?
+ fi
+ sleep 0.25
+ done
+ echo "CloakBrowser DevTools did not become ready on 127.0.0.1:${CLOAK_DEVTOOLS_PORT}" >&2
+ exit 1
+ ' \
+ >/dev/null
+
+ if ! wait_http "http://127.0.0.1:${CDP_PORT}/json/version" 90; then
+ docker logs "${CLOAK_CONTAINER}" | tail -50 || true
+ fail "CloakBrowser DevTools not reachable on :${CDP_PORT}"
+ fi
+
+ write_config "cloak" "/opt/cloakbrowser/chrome"
+ start_pinchtab
+ ATTACHED_INSTANCE_ID=""
+ assert_attached_instance "smoke-cloak" "cloak"
+ local inst_id="${ATTACHED_INSTANCE_ID}"
+
+ echo ">>> Stopping attached PinchTab instance ${inst_id}"
+ stop_attached_instance "${inst_id}"
+
+ echo ">>> Verifying external CloakBrowser container is still running"
+ if ! docker ps --format '{{.Names}}' | grep -Fxq "${CLOAK_CONTAINER}"; then
+ fail "external CloakBrowser container was killed by stop (must not happen)"
+ fi
+ echo " OK — external browser process preserved."
+
+ stop_pinchtab
+ docker rm -f "${CLOAK_CONTAINER}" >/dev/null 2>&1 || true
+ echo "CloakBrowser leg PASS"
+}
+
+case "${LEG}" in
+ all) run_chrome_leg; run_cloak_leg ;;
+ chrome) run_chrome_leg ;;
+ cloak) run_cloak_leg ;;
+ *) fail "unknown leg: ${LEG} (expected: all | chrome | cloak)" ;;
+esac
+
+echo ""
+echo "OK: docker-cdp-attach-smoke"
diff --git a/scripts/docker-cloakbrowser-smoke.sh b/scripts/docker-cloakbrowser-smoke.sh
deleted file mode 100755
index 1043b5ef..00000000
--- a/scripts/docker-cloakbrowser-smoke.sh
+++ /dev/null
@@ -1,439 +0,0 @@
-#!/usr/bin/env bash
-set -euo pipefail
-
-IMAGE="${1:-pinchtab-cloakbrowser:test}"
-RUNNER_IMAGE="${PINCHTAB_CLOAKBROWSER_RUNNER_IMAGE:-pinchtab-e2e-runner-api:cloak-smoke}"
-CLOAK_CONTAINER_BIN="/opt/cloakbrowser/chrome"
-TOKEN="pinchtab-docker-cloak-smoke-${RANDOM}${RANDOM}"
-NAME="pinchtab-docker-cloak-smoke-${RANDOM}${RANDOM}"
-TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/pinchtab-docker-cloak.XXXXXX")"
-FIXTURES_PORT="${PINCHTAB_CLOAKBROWSER_FIXTURES_PORT:-}"
-FIXTURES_HOST="${PINCHTAB_CLOAKBROWSER_FIXTURES_HOST:-cloak-fixtures.local}"
-HOST_FIXTURES_URL=""
-FIXTURES_URL=""
-FAILED=0
-CONTAINER_STARTED=0
-FIXTURES_STARTED=0
-HOST_PORT=""
-API_RESULT=""
-API_STATUS=""
-SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
-CLOAK_DOCKERFILE="${PINCHTAB_CLOAKBROWSER_DOCKERFILE:-tests/tools/docker/cloakbrowser-smoke.Dockerfile}"
-RUNNER_DOCKERFILE="${PINCHTAB_CLOAKBROWSER_RUNNER_DOCKERFILE:-tests/e2e/runner-api/Dockerfile}"
-
-cleanup() {
- set +e
- if [ "$CONTAINER_STARTED" -eq 1 ] && docker ps -a --format '{{.Names}}' | grep -Fxq "$NAME"; then
- if [ "$FAILED" -ne 0 ]; then
- echo ""
- echo "Container logs:"
- docker logs "$NAME" || true
- echo ""
- echo "Process list:"
- docker exec "$NAME" ps -eo pid,user,args || true
- if [ "$FIXTURES_STARTED" -eq 1 ]; then
- echo ""
- echo "Fixture server log:"
- docker exec "$NAME" sh -lc 'cat /tmp/pinchtab-fixtures.log 2>/dev/null || true' || true
- fi
- mkdir -p "$TMP_DIR/data"
- docker cp "$NAME:/data/." "$TMP_DIR/data/" >/dev/null 2>&1 || true
- if [ -n "${HOST_PORT:-}" ]; then
- echo ""
- echo "HTTP diagnostics:"
- echo "/autorestart/status:"
- curl -sS -H "Authorization: Bearer ${TOKEN}" "http://127.0.0.1:${HOST_PORT}/autorestart/status" || true
- echo ""
- echo "/instances:"
- instances_diag="$(curl -sS -H "Authorization: Bearer ${TOKEN}" "http://127.0.0.1:${HOST_PORT}/instances" || true)"
- echo "$instances_diag"
- echo "$instances_diag" | jq -r '.[].id? // empty' 2>/dev/null | while read -r inst_id; do
- [ -n "$inst_id" ] || continue
- echo ""
- echo "/instances/${inst_id}/logs:"
- curl -sS -H "Authorization: Bearer ${TOKEN}" "http://127.0.0.1:${HOST_PORT}/instances/${inst_id}/logs" || true
- echo ""
- done
- fi
- fi
- docker rm -f "$NAME" >/dev/null 2>&1 || true
- fi
- if [ "$FAILED" -ne 0 ]; then
- echo "Artifacts kept at: $TMP_DIR"
- else
- rm -rf "$TMP_DIR"
- fi
-}
-trap cleanup EXIT
-
-skip() {
- echo "SKIP: $*"
- exit 77
-}
-
-fail() {
- FAILED=1
- echo "FAIL: $*" >&2
- exit 1
-}
-
-api_request() {
- local method="$1"
- local path="$2"
- local body="${3:-}"
- local url="http://127.0.0.1:${HOST_PORT}${path}"
- local -a args=(
- -sS
- -w $'\n%{http_code}'
- -X "$method"
- -H "Authorization: Bearer ${TOKEN}"
- )
- if [ "$method" = "POST" ]; then
- args+=(-H "Content-Type: application/json" -d "$body")
- fi
-
- local response
- if ! response="$(curl "${args[@]}" "$url" 2>&1)"; then
- fail "$method $path failed: $response"
- fi
- API_STATUS="${response##*$'\n'}"
- API_RESULT="${response%$'\n'*}"
- if [ "$API_STATUS" -lt 200 ] || [ "$API_STATUS" -ge 300 ]; then
- fail "$method $path failed with HTTP $API_STATUS: $API_RESULT"
- fi
-}
-
-api_get() {
- api_request GET "$1"
-}
-
-api_post() {
- api_request POST "$1" "$2"
-}
-
-assert_api_jq() {
- local expr="$1"
- local label="$2"
- echo "$API_RESULT" | jq -e "$expr" >/dev/null || fail "$label failed: $API_RESULT"
-}
-
-assert_file_min_bytes() {
- local path="$1"
- local min_bytes="$2"
- local label="$3"
- local bytes
- bytes="$(wc -c < "$path" | tr -d '[:space:]')"
- if [ "${bytes:-0}" -lt "$min_bytes" ]; then
- fail "$label too small: ${bytes:-0} bytes"
- fi
-}
-
-assert_screenshot_png() {
- local path="$1"
- local out="$TMP_DIR/screenshot.png"
- local headers="$TMP_DIR/screenshot.headers"
- curl -fsS \
- -D "$headers" \
- -o "$out" \
- -H "Authorization: Bearer ${TOKEN}" \
- "http://127.0.0.1:${HOST_PORT}${path}" || fail "GET $path failed"
- grep -qi '^content-type: image/png' "$headers" || fail "GET $path did not return image/png"
- assert_file_min_bytes "$out" 500 "screenshot"
-}
-
-choose_free_port() {
- python3 - <<'PY'
-import socket
-
-sock = socket.socket()
-sock.bind(("127.0.0.1", 0))
-print(sock.getsockname()[1])
-sock.close()
-PY
-}
-
-run_fixture_endpoint_smoke() {
- echo "Running fixture-backed CloakBrowser endpoint smoke..."
-
- api_post /navigate "{\"url\":\"${FIXTURES_URL}/index.html\",\"waitFor\":\"selector\",\"waitSelector\":\"#welcome\"}"
- assert_api_jq '.title | contains("Home")' "fixture home navigation title"
- assert_api_jq '.url | contains("index.html")' "fixture home navigation URL"
- local tab_id
- tab_id="$(echo "$API_RESULT" | jq -r '.tabId // empty')"
- [ -n "$tab_id" ] || fail "navigate response did not include tabId: $API_RESULT"
-
- api_get /tabs
- echo "$API_RESULT" | jq -e --arg tab "$tab_id" '.tabs | map(.id) | index($tab) != null' >/dev/null \
- || fail "tabs includes fixture tab failed: $API_RESULT"
-
- api_get "/snapshot?tabId=${tab_id}&filter=interactive"
- assert_api_jq '.nodes | length > 0' "snapshot returns nodes"
-
- api_get "/tabs/${tab_id}/text"
- assert_api_jq '.text | contains("Welcome to the E2E test fixtures")' "tab text includes fixture content"
-
- api_get "/tabs/${tab_id}/html?selector=%23welcome"
- assert_api_jq '.html | contains("Welcome to the E2E test fixtures")' "selected html includes fixture content"
-
- api_get "/tabs/${tab_id}/styles?selector=%23welcome&prop=display"
- assert_api_jq '.styles.display == "block"' "selected styles include display"
-
- assert_screenshot_png "/tabs/${tab_id}/screenshot?format=png&raw=true"
-
- api_post "/tabs/${tab_id}/navigate" "{\"url\":\"${FIXTURES_URL}/buttons.html\",\"waitFor\":\"selector\",\"waitSelector\":\"#increment\"}"
- assert_api_jq '.title | contains("Buttons")' "buttons navigation title"
-
- api_post "/tabs/${tab_id}/action" '{"kind":"click","selector":"#increment"}'
- assert_api_jq '.success == true' "click action succeeded"
-
- api_post "/tabs/${tab_id}/evaluate" '{"expression":"document.querySelector(\"#count\").textContent"}'
- assert_api_jq '.result == "1"' "evaluate sees click result"
-
- api_post "/tabs/${tab_id}/navigate" "{\"url\":\"${FIXTURES_URL}/form.html\",\"waitFor\":\"selector\",\"waitSelector\":\"#username\"}"
- assert_api_jq '.title | contains("Form")' "form navigation title"
-
- api_post "/tabs/${tab_id}/actions" '{"stopOnError":true,"actions":[{"kind":"fill","selector":"#username","text":"cloak_user"},{"kind":"check","selector":"#terms"}]}'
- assert_api_jq '.successful == 2 and .failed == 0' "batch actions succeeded"
-
- api_post "/tabs/${tab_id}/evaluate" '{"expression":"({username: document.querySelector(\"#username\").value, terms: document.querySelector(\"#terms\").checked})"}'
- assert_api_jq '.result.username == "cloak_user" and .result.terms == true' "evaluate sees batch action results"
-}
-
-run_e2e_scenarios() {
- local -a default_scenarios=(
- "actions-basic.sh"
- "browser-basic.sh"
- "clipboard-basic.sh"
- "console-basic.sh"
- "emulation-basic.sh"
- "files-basic.sh"
- "inspect-basic.sh"
- "tabs-basic.sh"
- )
- local -a scenarios=()
- local -a scenario_args=()
-
- if [ -n "${PINCHTAB_CLOAKBROWSER_E2E_SCENARIOS:-}" ]; then
- read -r -a scenarios <<< "${PINCHTAB_CLOAKBROWSER_E2E_SCENARIOS}"
- else
- scenarios=("${default_scenarios[@]}")
- fi
-
- for scenario in "${scenarios[@]}"; do
- [ -n "$scenario" ] || continue
- scenario_args+=("scenario=$scenario")
- done
-
- if [ "${#scenario_args[@]}" -eq 0 ]; then
- echo "Skipping API E2E scenarios because PINCHTAB_CLOAKBROWSER_E2E_SCENARIOS is empty."
- return
- fi
-
- echo "Running API E2E scenarios against CloakBrowser in Docker:"
- printf ' - %s\n' "${scenarios[@]}"
-
- docker run --rm \
- --network "container:${NAME}" \
- -v "$ROOT/tests/e2e":/e2e:ro \
- -e "FIXTURES_HOST=${FIXTURES_HOST}" \
- -e "E2E_SERVER=http://127.0.0.1:9867" \
- -e "E2E_SERVER_TOKEN=${TOKEN}" \
- -e "FIXTURES_URL=${FIXTURES_URL}" \
- -e "E2E_HELPER=api" \
- -e "E2E_SCENARIO_DIR=scenarios/api" \
- -e "E2E_REQUIRED_COMMANDS=curl jq" \
- -e "E2E_READY_TARGETS=E2E_SERVER|60|E2E_SERVER_TOKEN" \
- -e "E2E_SUMMARY_TITLE=CloakBrowser API E2E scenarios" \
- "$RUNNER_IMAGE" \
- /bin/sh -lc 'printf "127.0.0.1 %s\n" "$FIXTURES_HOST" >> /etc/hosts; exec /bin/bash /e2e/run.sh "$@"' \
- _ "${scenario_args[@]}" \
- || fail "API E2E scenarios failed"
-}
-
-command -v docker >/dev/null 2>&1 || skip "docker is not installed"
-command -v python3 >/dev/null 2>&1 || fail "python3 is required to write the smoke config"
-command -v jq >/dev/null 2>&1 || fail "jq is required to validate smoke responses"
-command -v curl >/dev/null 2>&1 || fail "curl is required to run smoke requests"
-
-if [ -z "$FIXTURES_PORT" ]; then
- FIXTURES_PORT="$(choose_free_port)"
-fi
-HOST_FIXTURES_URL="http://127.0.0.1:${FIXTURES_PORT}"
-FIXTURES_URL="http://${FIXTURES_HOST}:${FIXTURES_PORT}"
-
-if [ "${SKIP_BUILD:-}" = "1" ]; then
- if docker image inspect "$IMAGE" >/dev/null 2>&1; then
- echo "Using existing Docker image: $IMAGE (SKIP_BUILD=1)"
- else
- skip "Docker image $IMAGE not found and SKIP_BUILD=1 is set"
- fi
-else
- echo "Building PinchTab CloakBrowser Docker image: $IMAGE"
- docker build -f "$ROOT/$CLOAK_DOCKERFILE" -t "$IMAGE" "$ROOT"
-fi
-
-if [ "${SKIP_RUNNER_BUILD:-}" = "1" ]; then
- if docker image inspect "$RUNNER_IMAGE" >/dev/null 2>&1; then
- echo "Using existing E2E runner image: $RUNNER_IMAGE (SKIP_RUNNER_BUILD=1)"
- else
- skip "E2E runner image $RUNNER_IMAGE not found and SKIP_RUNNER_BUILD=1 is set"
- fi
-else
- echo "Building API E2E runner image: $RUNNER_IMAGE"
- docker build -f "$ROOT/$RUNNER_DOCKERFILE" -t "$RUNNER_IMAGE" "$ROOT/tests/e2e/runner-api"
-fi
-
-docker run --rm --entrypoint /bin/sh "$IMAGE" -lc "test -x '$CLOAK_CONTAINER_BIN'" \
- || fail "CloakBrowser binary not found in image at $CLOAK_CONTAINER_BIN; rebuild the dedicated CloakBrowser smoke image"
-
-CONFIG_PATH="$TMP_DIR/pinchtab-cloak.json"
-python3 - "$CONFIG_PATH" "$TOKEN" "$CLOAK_CONTAINER_BIN" "$FIXTURES_HOST" <<'PY'
-import json
-import sys
-
-path, token, cloak_binary, fixtures_host = sys.argv[1:]
-cfg = {
- "server": {
- "bind": "0.0.0.0",
- "port": "9867",
- "token": token,
- "stateDir": "/data",
- },
- "browser": {
- "provider": "cloak",
- "binary": cloak_binary,
- "extensionPaths": [],
- "cloak": {
- "fingerprintSeed": "42069",
- "platform": "linux",
- "locale": "en-US",
- "timezone": "UTC",
- "disableDefaultStealthArgs": True,
- },
- },
- "instanceDefaults": {
- "mode": "headless",
- "humanize": True,
- "maxTabs": 10,
- },
- "security": {
- "allowEvaluate": True,
- "allowDownload": True,
- "allowCookies": True,
- "allowUpload": True,
- "allowClipboard": True,
- "allowStateExport": True,
- "allowedDomains": [fixtures_host, "127.0.0.1", "localhost", "::1"],
- "downloadAllowedDomains": [fixtures_host],
- "trustedResolveCIDRs": ["127.0.0.1/32"],
- },
- "profiles": {
- "baseDir": "/data/profiles",
- "defaultProfile": "cloak-docker-smoke",
- },
-}
-with open(path, "w", encoding="utf-8") as fh:
- json.dump(cfg, fh, indent=2)
-PY
-
-docker run -d \
- --name "$NAME" \
- --user 1000:1000 \
- --shm-size=2g \
- --tmpfs /data:rw,size=1024m,uid=1000,gid=1000,mode=0755 \
- --tmpfs /tmp:rw,size=512m,mode=1777 \
- --add-host "${FIXTURES_HOST}:127.0.0.1" \
- -e PINCHTAB_CONFIG=/config/pinchtab-cloak.json \
- -v "$CONFIG_PATH":/config/pinchtab-cloak.json:ro \
- -v "$ROOT/tests/e2e/fixtures":/fixtures:ro \
- -v "$ROOT/tests/tools/fixtures/static-server.pl":/usr/local/bin/fixture-server.pl:ro \
- --publish 127.0.0.1::9867 \
- --publish "127.0.0.1:${FIXTURES_PORT}:${FIXTURES_PORT}" \
- "$IMAGE" >/dev/null
-CONTAINER_STARTED=1
-
-HOST_PORT="$(docker port "$NAME" 9867/tcp 2>/dev/null | head -1 | awk -F: '{print $NF}' || true)"
-if [ -z "$HOST_PORT" ]; then
- HOST_PORT="$(docker inspect -f '{{with index .NetworkSettings.Ports "9867/tcp"}}{{(index . 0).HostPort}}{{end}}' "$NAME" 2>/dev/null || true)"
-fi
-if [ -z "$HOST_PORT" ]; then
- fail "failed to determine published host port"
-fi
-
-echo "Waiting for PinchTab+CloakBrowser container on port $HOST_PORT..."
-docker exec "$NAME" sh -lc "FIXTURES_ROOT=/fixtures FIXTURES_PORT=${FIXTURES_PORT} /usr/bin/perl /usr/local/bin/fixture-server.pl >/tmp/pinchtab-fixtures.log 2>&1 &"
-FIXTURES_STARTED=1
-
-fixtures_ready=0
-for _ in $(seq 1 30); do
- if curl -fsS "${HOST_FIXTURES_URL}/index.html" >/dev/null 2>&1 &&
- docker exec "$NAME" curl -fsS "${FIXTURES_URL}/index.html" >/dev/null 2>&1; then
- fixtures_ready=1
- break
- fi
- sleep 1
-done
-if [ "$fixtures_ready" -ne 1 ]; then
- fail "fixture server was not reachable from the PinchTab container at ${FIXTURES_URL}"
-fi
-
-health_ready=0
-for _ in $(seq 1 90); do
- if curl -fsS -H "Authorization: Bearer ${TOKEN}" "http://127.0.0.1:${HOST_PORT}/health" >/dev/null 2>&1; then
- health_ready=1
- break
- fi
- sleep 1
-done
-if [ "$health_ready" -ne 1 ]; then
- health_body="$(curl -sS -H "Authorization: Bearer ${TOKEN}" "http://127.0.0.1:${HOST_PORT}/health" 2>&1 || true)"
- fail "health check did not pass: $health_body"
-fi
-
-uid="$(docker exec "$NAME" id -u | tr -d '\r')"
-if [ "$uid" = "0" ]; then
- fail "container is running as root; expected non-root user"
-fi
-
-shm_mb="$(docker exec "$NAME" sh -lc "df -Pm /dev/shm | awk 'NR==2 {print \$2}'" | tr -d '\r')"
-if [ "${shm_mb:-0}" -lt 1024 ]; then
- fail "/dev/shm is too small: ${shm_mb:-unknown} MB"
-fi
-
-docker exec "$NAME" sh -lc 'if command -v fc-list >/dev/null 2>&1; then fc-list | grep -q .; else find /usr/share/fonts -type f 2>/dev/null | head -1 | grep -q .; fi' || fail "no fonts found in container"
-
-echo "Waiting for managed CloakBrowser instance..."
-instance_ready=0
-instances_body="[]"
-autorestart_body="{}"
-for _ in $(seq 1 120); do
- instances_body="$(curl -fsS -H "Authorization: Bearer ${TOKEN}" "http://127.0.0.1:${HOST_PORT}/instances" 2>/dev/null || echo "[]")"
- if echo "$instances_body" | jq -e '.[]? | select(.status == "running")' >/dev/null; then
- instance_ready=1
- break
- fi
- autorestart_body="$(curl -fsS -H "Authorization: Bearer ${TOKEN}" "http://127.0.0.1:${HOST_PORT}/autorestart/status" 2>/dev/null || echo "{}")"
- if echo "$autorestart_body" | jq -e '.status == "crashed"' >/dev/null 2>&1; then
- break
- fi
- sleep 1
-done
-if [ "$instance_ready" -ne 1 ]; then
- fail "managed CloakBrowser instance did not become running: instances=$instances_body autorestart=$autorestart_body"
-fi
-
-if ! status="$(curl -fsS -H "Authorization: Bearer ${TOKEN}" "http://127.0.0.1:${HOST_PORT}/stealth/status" 2>&1)"; then
- fail "stealth status request failed: $status"
-fi
-echo "$status" | jq -e '
- .provider == "cloak" and
- .native == true and
- .pinchtabOverlaysDisabled == true and
- .fingerprintSeed == "42069"
-' >/dev/null || fail "unexpected stealth status: $status"
-
-run_fixture_endpoint_smoke
-run_e2e_scenarios
-
-echo "Docker CloakBrowser smoke passed."
diff --git a/scripts/docker-live-detection-smoke.sh b/scripts/docker-live-detection-smoke.sh
new file mode 100755
index 00000000..e14f6ba3
--- /dev/null
+++ b/scripts/docker-live-detection-smoke.sh
@@ -0,0 +1,404 @@
+#!/usr/bin/env bash
+# docker-live-detection-smoke.sh — opt-in live detection-site probe (P6).
+#
+# Spins up a single PinchTab container (Chrome by default, --provider=cloak for
+# CloakBrowser), drives the managed instance through a small list of public bot
+# detection demo sites, and for each site captures:
+#
+# - a PNG screenshot (GET /tabs/<id>/screenshot)
+# - a summary string (GET /tabs/<id>/text?selector=…) or full-page text
+#
+# All artifacts are written under a per-run output directory plus a top-level
+# report.md summarizing what was visited and any observed detection signal.
+#
+# Strict semantics:
+# * Opt-in — NOT wired into ./dev all or CI; external network calls only
+# happen when this smoke is explicitly invoked.
+# * Output is advisory. The smoke exits 0 if every site was *attempted*
+# successfully (container healthy, request returned). It exits 1 ONLY on
+# infrastructure failure: container fails to start, PinchTab unreachable,
+# or the image is missing while SKIP_BUILD=1.
+# * A site reporting "you are a bot" is NOT a failure — that is the whole
+# point of the advisory capture.
+#
+# Usage:
+# ./dev smoke live-detection # Chrome leg
+# ./dev smoke live-detection --provider=chrome
+# ./dev smoke live-detection --provider=cloak
+#
+# Env overrides:
+# PINCHTAB_PARITY_CHROME_IMAGE Chrome leg image (default: pinchtab-chrome-smoke:test)
+# PINCHTAB_PARITY_CHROME_BASE_IMAGE Base PinchTab image (default: pinchtab-local:test)
+# PINCHTAB_PARITY_CLOAK_IMAGE Cloak leg image (default: pinchtab-cloakbrowser:test)
+# PINCHTAB_LIVE_DETECTION_SITES Override TSV path (default: scripts/lib/live-detection-sites.tsv)
+# PINCHTAB_LIVE_DETECTION_OUTDIR Override output directory (default: tests/e2e/results/live-detection/<provider>-<ts>)
+# PINCHTAB_LIVE_DETECTION_NAV_TIMEOUT_MS Per-site navigate timeout (default: 25000)
+# PINCHTAB_LIVE_DETECTION_ONLY Space-separated list of site names to include
+# SKIP_BUILD=1 Reuse existing provider image; do not docker build
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
+LIB_DIR="$SCRIPT_DIR/lib"
+
+# shellcheck source=lib/smoke-common.sh
+source "$LIB_DIR/smoke-common.sh"
+# shellcheck source=lib/smoke-config.sh
+source "$LIB_DIR/smoke-config.sh"
+# shellcheck source=lib/smoke-container.sh
+source "$LIB_DIR/smoke-container.sh"
+# shellcheck source=lib/smoke-health.sh
+source "$LIB_DIR/smoke-health.sh"
+
+# ── CLI parsing ──────────────────────────────────────────────────────────────
+
+PROVIDER="chrome"
+for arg in "$@"; do
+ case "$arg" in
+ --provider=chrome|--provider=cloak)
+ PROVIDER="${arg#--provider=}"
+ ;;
+ --provider=*)
+ fail "invalid --provider: ${arg#--provider=} (expected chrome|cloak)"
+ ;;
+ --provider)
+ fail "--provider requires =VALUE (e.g. --provider=chrome)"
+ ;;
+ --help|-h)
+ sed -n '2,38p' "$0"
+ exit 0
+ ;;
+ *)
+ fail "unknown arg: $arg"
+ ;;
+ esac
+done
+
+CHROME_BASE_IMAGE="${PINCHTAB_PARITY_CHROME_BASE_IMAGE:-pinchtab-local:test}"
+CHROME_IMAGE="${PINCHTAB_PARITY_CHROME_IMAGE:-pinchtab-chrome-smoke:test}"
+CLOAK_IMAGE="${PINCHTAB_PARITY_CLOAK_IMAGE:-pinchtab-cloakbrowser:test}"
+CLOAK_CONTAINER_BIN="/opt/cloakbrowser/chrome"
+CHROME_DOCKERFILE="${PINCHTAB_PARITY_CHROME_DOCKERFILE:-tests/tools/docker/chrome-smoke.Dockerfile}"
+CLOAK_DOCKERFILE="${PINCHTAB_CLOAKBROWSER_DOCKERFILE:-tests/tools/docker/cloakbrowser-smoke.Dockerfile}"
+
+SITES_FILE="${PINCHTAB_LIVE_DETECTION_SITES:-$LIB_DIR/live-detection-sites.tsv}"
+NAV_TIMEOUT_MS="${PINCHTAB_LIVE_DETECTION_NAV_TIMEOUT_MS:-25000}"
+
+[ -r "$SITES_FILE" ] || fail "site list not readable: $SITES_FILE"
+
+# ── Prereqs ──────────────────────────────────────────────────────────────────
+
+FAILED=0
+command -v docker >/dev/null 2>&1 || skip "docker is not installed"
+require_cmd python3
+require_cmd jq
+require_cmd curl
+
+# ── Output directory ─────────────────────────────────────────────────────────
+
+if [ -n "${PINCHTAB_LIVE_DETECTION_OUTDIR:-}" ]; then
+ ARTIFACT_DIR="$PINCHTAB_LIVE_DETECTION_OUTDIR"
+ mkdir -p "$ARTIFACT_DIR"
+else
+ ts="$(date -u +%Y%m%dT%H%M%SZ)"
+ ARTIFACT_DIR="$ROOT/tests/e2e/results/live-detection/${PROVIDER}-${ts}"
+ mkdir -p "$ARTIFACT_DIR"
+fi
+REPORT="$ARTIFACT_DIR/report.md"
+
+TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/pinchtab-live-detection.XXXXXX")"
+TOKEN="pinchtab-live-detection-${PROVIDER}-${RANDOM}${RANDOM}"
+NAME="pinchtab-live-detection-${PROVIDER}-${RANDOM}${RANDOM}"
+HOST_PORT=""
+CONTAINER_STARTED=0
+API_RESULT=""
+API_STATUS=""
+# Unused at runtime but required by write_provider_config.
+FIXTURES_HOST="live-detection-fixtures.local"
+FIXTURES_PORT="$(choose_free_port)"
+CONFIG_PATH="$TMP_DIR/pinchtab-${PROVIDER}.json"
+
+cleanup() {
+ set +e
+ if [ -n "$NAME" ]; then
+ teardown_container "$NAME"
+ fi
+ rm -rf "$TMP_DIR"
+}
+trap cleanup EXIT
+
+# ── Image builds ─────────────────────────────────────────────────────────────
+
+ensure_chrome_image() {
+ if [ "${SKIP_BUILD:-}" = "1" ]; then
+ if docker image inspect "$CHROME_IMAGE" >/dev/null 2>&1; then
+ echo "Using existing Chrome smoke image: $CHROME_IMAGE (SKIP_BUILD=1)"
+ return
+ fi
+ skip "Chrome smoke image $CHROME_IMAGE not found and SKIP_BUILD=1 is set"
+ fi
+ if ! docker image inspect "$CHROME_BASE_IMAGE" >/dev/null 2>&1; then
+ echo "Building base PinchTab image: $CHROME_BASE_IMAGE"
+ docker build -t "$CHROME_BASE_IMAGE" "$ROOT"
+ else
+ echo "Reusing existing base PinchTab image: $CHROME_BASE_IMAGE"
+ fi
+ if ! docker image inspect "$CHROME_IMAGE" >/dev/null 2>&1; then
+ echo "Building Chrome smoke overlay image: $CHROME_IMAGE"
+ docker build \
+ -f "$ROOT/$CHROME_DOCKERFILE" \
+ --build-arg "BASE_IMAGE=$CHROME_BASE_IMAGE" \
+ -t "$CHROME_IMAGE" \
+ "$ROOT"
+ else
+ echo "Reusing existing Chrome smoke image: $CHROME_IMAGE"
+ fi
+}
+
+ensure_cloak_image() {
+ if [ "${SKIP_BUILD:-}" = "1" ]; then
+ if docker image inspect "$CLOAK_IMAGE" >/dev/null 2>&1; then
+ echo "Using existing Cloak image: $CLOAK_IMAGE (SKIP_BUILD=1)"
+ else
+ skip "Cloak image $CLOAK_IMAGE not found and SKIP_BUILD=1 is set"
+ fi
+ else
+ if ! docker image inspect "$CLOAK_IMAGE" >/dev/null 2>&1; then
+ echo "Building PinchTab CloakBrowser Docker image: $CLOAK_IMAGE"
+ docker build -f "$ROOT/$CLOAK_DOCKERFILE" -t "$CLOAK_IMAGE" "$ROOT"
+ else
+ echo "Reusing existing Cloak image: $CLOAK_IMAGE"
+ fi
+ fi
+ docker run --rm --entrypoint /bin/sh "$CLOAK_IMAGE" -lc "test -x '$CLOAK_CONTAINER_BIN'" \
+ || fail "CloakBrowser binary not found in image at $CLOAK_CONTAINER_BIN"
+}
+
+case "$PROVIDER" in
+ chrome) ensure_chrome_image ; IMAGE="$CHROME_IMAGE" ;;
+ cloak) ensure_cloak_image ; IMAGE="$CLOAK_IMAGE" ;;
+esac
+
+# ── Config + container ───────────────────────────────────────────────────────
+
+if [ "$PROVIDER" = "cloak" ]; then
+ write_provider_config "$PROVIDER" "$CONFIG_PATH" "$TOKEN" "$FIXTURES_HOST" "" "$CLOAK_CONTAINER_BIN"
+else
+ write_provider_config "$PROVIDER" "$CONFIG_PATH" "$TOKEN" "$FIXTURES_HOST" "" ""
+fi
+
+# Clear allowedDomains: this smoke navigates the open internet, so the
+# implicit IDPI allowlist must not constrain it.
+python3 - "$CONFIG_PATH" <<'PY'
+import json, sys
+p = sys.argv[1]
+with open(p) as fh:
+ cfg = json.load(fh)
+cfg.setdefault("security", {})
+cfg["security"]["allowedDomains"] = []
+cfg["security"]["downloadAllowedDomains"] = []
+with open(p, "w") as fh:
+ json.dump(cfg, fh, indent=2)
+PY
+
+echo "Starting PinchTab container (provider=${PROVIDER}, image=${IMAGE})..."
+start_provider_container "$NAME" "$IMAGE" "$CONFIG_PATH" "$FIXTURES_HOST" "$FIXTURES_PORT" "$ROOT"
+HOST_PORT="$(resolve_host_port "$NAME")"
+echo "Container $NAME up — PinchTab on host port $HOST_PORT"
+
+echo "Waiting for PinchTab health on :${HOST_PORT}..."
+wait_for_health "$HOST_PORT" "$TOKEN"
+echo "Waiting for managed ${PROVIDER} instance..."
+wait_for_instance_running "$HOST_PORT" "$TOKEN"
+
+# ── Report header ────────────────────────────────────────────────────────────
+
+{
+ echo "# PinchTab live detection probe — ${PROVIDER}"
+ echo
+ echo "Generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
+ echo "Provider: \`${PROVIDER}\`"
+ echo "Image: \`${IMAGE}\`"
+ echo "Site list: \`${SITES_FILE#$ROOT/}\`"
+ echo
+ echo "> Output is **advisory only**. Detection verdicts here are not"
+ echo "> deterministic pass/fail release gates."
+ echo
+ echo "## Sites visited"
+ echo
+} > "$REPORT"
+
+# ── Per-site probe ───────────────────────────────────────────────────────────
+
+probe_site() {
+ local name="$1" url="$2" wait_for="$3" selector="$4" notes="$5"
+ local site_dir="$ARTIFACT_DIR/$name"
+ mkdir -p "$site_dir"
+
+ echo ""
+ echo "── ${name} — ${url}"
+
+ local nav_payload
+ if [ "$wait_for" = "selector" ] && [ -n "$selector" ] && [ "$selector" != "-" ]; then
+ nav_payload="$(jq -nc \
+ --arg url "$url" \
+ --arg sel "$selector" \
+ --argjson timeout "$NAV_TIMEOUT_MS" \
+ '{url:$url, waitFor:"selector", waitSelector:$sel, timeout:$timeout}')"
+ else
+ nav_payload="$(jq -nc \
+ --arg url "$url" \
+ --argjson timeout "$NAV_TIMEOUT_MS" \
+ '{url:$url, timeout:$timeout}')"
+ fi
+
+ # Tolerant of non-2xx — api_post would call fail() and abort the run.
+ local nav_status nav_body tab_id="" nav_error=""
+ local response
+ if response="$(curl -sS \
+ -w $'\n%{http_code}' \
+ -X POST \
+ -H "Authorization: Bearer ${TOKEN}" \
+ -H "Content-Type: application/json" \
+ -d "$nav_payload" \
+ --max-time $(( NAV_TIMEOUT_MS / 1000 + 10 )) \
+ "http://127.0.0.1:${HOST_PORT}/navigate" 2>&1)"; then
+ nav_status="${response##*$'\n'}"
+ nav_body="${response%$'\n'*}"
+ else
+ nav_status="000"
+ nav_body="$response"
+ fi
+
+ if [ "$nav_status" != "200" ]; then
+ nav_error="navigate HTTP ${nav_status}: $(echo "$nav_body" | head -c 400)"
+ echo " navigate advisory error: $nav_error"
+ printf '%s\n' "$nav_body" > "$site_dir/navigate-error.txt"
+ else
+ tab_id="$(echo "$nav_body" | jq -r '.tabId // empty' 2>/dev/null || true)"
+ if [ -z "$tab_id" ]; then
+ nav_error="navigate succeeded but no tabId in response"
+ echo " $nav_error"
+ printf '%s\n' "$nav_body" > "$site_dir/navigate-error.txt"
+ else
+ echo " navigated; tab=$tab_id"
+ fi
+ fi
+
+ local screenshot_path="$site_dir/screenshot.png"
+ local summary_path="$site_dir/summary.txt"
+ local screenshot_status="skipped" summary_status="skipped" summary_kind="-"
+
+ if [ -n "$tab_id" ]; then
+ if curl -fsS \
+ -o "$screenshot_path" \
+ -H "Authorization: Bearer ${TOKEN}" \
+ --max-time 30 \
+ "http://127.0.0.1:${HOST_PORT}/tabs/${tab_id}/screenshot?format=png&raw=true" 2>/dev/null; then
+ local bytes
+ bytes="$(wc -c < "$screenshot_path" | tr -d '[:space:]')"
+ screenshot_status="ok (${bytes} bytes)"
+ echo " screenshot: ${bytes} bytes"
+ else
+ screenshot_status="failed"
+ rm -f "$screenshot_path"
+ echo " screenshot failed"
+ fi
+
+ local text_url
+ if [ -n "$selector" ] && [ "$selector" != "-" ]; then
+ text_url="http://127.0.0.1:${HOST_PORT}/tabs/${tab_id}/text?selector=$(python3 -c 'import urllib.parse,sys;print(urllib.parse.quote(sys.argv[1]))' "$selector")"
+ summary_kind="selector(${selector})"
+ else
+ text_url="http://127.0.0.1:${HOST_PORT}/tabs/${tab_id}/text"
+ summary_kind="full-page"
+ fi
+ local text_body
+ if text_body="$(curl -fsS \
+ -H "Authorization: Bearer ${TOKEN}" \
+ --max-time 20 \
+ "$text_url" 2>&1)"; then
+ # Endpoint returns JSON when selector is used, plain text otherwise.
+ local extracted
+ extracted="$(echo "$text_body" | jq -r '.text // empty' 2>/dev/null)"
+ if [ -z "$extracted" ]; then
+ extracted="$text_body"
+ fi
+ printf '%s\n' "$extracted" > "$summary_path"
+ summary_status="ok ($(wc -c < "$summary_path" | tr -d '[:space:]') bytes)"
+ echo " summary: ${summary_status}"
+ else
+ summary_status="failed"
+ echo " summary failed"
+ fi
+ fi
+
+ local signal="(no hint)"
+ if [ -r "$summary_path" ]; then
+ if grep -Eiq 'cloudflare|attention required|just a moment' "$summary_path"; then
+ signal="cloudflare-challenge"
+ elif grep -Eiq 'you are a bot|bot detected|access denied' "$summary_path"; then
+ signal="bot-flagged"
+ elif grep -Eiq 'pass|human|not a robot|verified' "$summary_path"; then
+ signal="possibly-passing"
+ fi
+ fi
+
+ {
+ echo "### ${name}"
+ echo
+ echo "- URL: <${url}>"
+ echo "- Notes: ${notes}"
+ echo "- Wait/extract: \`${summary_kind}\`"
+ echo "- Navigate: $( [ -z "$nav_error" ] && echo "ok (tab=${tab_id})" || echo "advisory error — ${nav_error}" )"
+ echo "- Screenshot: ${screenshot_status} — \`${name}/screenshot.png\`"
+ echo "- Summary: ${summary_status} — \`${name}/summary.txt\`"
+ echo "- Heuristic signal: \`${signal}\`"
+ echo
+ } >> "$REPORT"
+}
+
+declare -A SITE_FILTER=()
+HAS_FILTER=0
+if [ -n "${PINCHTAB_LIVE_DETECTION_ONLY:-}" ]; then
+ HAS_FILTER=1
+ for s in $PINCHTAB_LIVE_DETECTION_ONLY; do
+ SITE_FILTER[$s]=1
+ done
+fi
+
+SITES_VISITED=0
+while IFS=$'\t' read -r name url wait_for selector notes; do
+ case "$name" in
+ ""|"#"*) continue ;;
+ esac
+ if [ "$HAS_FILTER" -eq 1 ] && [ -z "${SITE_FILTER[$name]:-}" ]; then
+ continue
+ fi
+ probe_site "$name" "$url" "$wait_for" "$selector" "$notes" || true
+ SITES_VISITED=$(( SITES_VISITED + 1 ))
+done < "$SITES_FILE"
+
+if [ "$SITES_VISITED" -eq 0 ]; then
+ fail "no sites matched filter (PINCHTAB_LIVE_DETECTION_ONLY=${PINCHTAB_LIVE_DETECTION_ONLY:-})"
+fi
+
+# ── Wrap up ──────────────────────────────────────────────────────────────────
+
+{
+ echo "---"
+ echo
+ echo "Sites attempted: ${SITES_VISITED}"
+} >> "$REPORT"
+
+echo ""
+echo "=============================================="
+echo "Live detection smoke complete"
+echo " provider: ${PROVIDER}"
+echo " sites: ${SITES_VISITED}"
+echo " artifacts: ${ARTIFACT_DIR}"
+echo " report: ${REPORT}"
+echo "=============================================="
+
+exit 0
diff --git a/scripts/docker-zombie-soak-smoke.sh b/scripts/docker-zombie-soak-smoke.sh
index 27fcf801..005c8403 100755
--- a/scripts/docker-zombie-soak-smoke.sh
+++ b/scripts/docker-zombie-soak-smoke.sh
@@ -180,6 +180,36 @@ count_chrome() {
' 2>/dev/null || echo 0
}
+# Count chrome-family processes reparented to PID 1 (dumb-init) — orphan
+# helpers whose original launcher exited without reaping them. crashpad_handler
+# is excluded because Chrome intentionally daemonizes it under PID 1.
+count_orphan_chrome_helpers() {
+ docker exec "$NAME" sh -c '
+ o=0
+ for d in /proc/[0-9]*; do
+ [ -f "$d/status" ] || continue
+ [ -f "$d/cmdline" ] || continue
+ cmdline=$(tr "\0" " " < "$d/cmdline" 2>/dev/null)
+ [ -z "$cmdline" ] && continue
+ printf "%s" "$cmdline" | grep -qiE "chrom|cloakbrowser" || continue
+ printf "%s" "$cmdline" | grep -q "chrome_crashpad_handler" && continue
+ name=$(awk "/^Name:/ {print \$2; exit}" "$d/status" 2>/dev/null)
+ [ "$name" = "chrome_crashpad" ] && continue
+ state=$(awk "/^State:/ {print \$2; exit}" "$d/status" 2>/dev/null)
+ ppid=$(awk "/^PPid:/ {print \$2; exit}" "$d/status" 2>/dev/null)
+ [ "$state" = "Z" ] && continue
+ [ "$ppid" = "1" ] && o=$((o + 1))
+ done
+ echo "$o"
+ ' 2>/dev/null || echo 0
+}
+
+count_active_instances() {
+ local body
+ body=$(pt_get /instances 2>/dev/null) || { echo ""; return 0; }
+ echo "$body" | jq -r '[.[]? | select(.status=="running")] | length' 2>/dev/null || echo ""
+}
+
snapshot_processes() {
local label="${1:-snapshot}"
local outfile="${RESULTS_DIR}/ps_$(date +%s)_${label}.txt"
@@ -212,6 +242,28 @@ check_zombies() {
return 0
}
+BASELINE_ORPHANS=0
+
+# Asserts orphan-helper count hasn't grown beyond the post-warmup baseline.
+# A non-zero baseline is normal: Chrome legitimately reparents some renderers/
+# zygotes to init by design — we only flag growth, not steady state.
+check_orphan_chrome() {
+ local label="$1"
+ local o
+ o=$(count_orphan_chrome_helpers)
+ local delta=$((o - BASELINE_ORPHANS))
+ if [ "$delta" -gt 0 ]; then
+ echo "FAIL [$label]: orphan chrome helpers grew +${delta} (baseline=$BASELINE_ORPHANS, current=$o)"
+ snapshot_processes "orphan_${label}" >/dev/null
+ record_fail "orphans: $label (+${delta})" "orphan chrome detected"
+ FAILED=1
+ return 1
+ fi
+ echo "OK [$label]: orphan chrome helpers $o (baseline=$BASELINE_ORPHANS)"
+ record_pass
+ return 0
+}
+
check_drift() {
local label="$1" baseline="$2" tolerance="${3:-5}"
local current
@@ -453,7 +505,9 @@ log_phase "Phase A: Baseline capture"
echo "Expectations: healthy container, zero zombies, responsive browser, stable baseline process tree."
snapshot_processes "baseline"
BASELINE_CHROME=$(count_chrome)
+BASELINE_ORPHANS=$(count_orphan_chrome_helpers)
echo "Baseline chrome process count: $BASELINE_CHROME"
+echo "Baseline orphan helpers (chrome PPID=1, excl. crashpad): $BASELINE_ORPHANS"
check_zombies "baseline" || true
run_step "baseline navigate" navigate_url "$(fixture_url "form.html")" || true
sleep 1
@@ -524,10 +578,12 @@ for i in $(seq 1 "$INSTANCE_CYCLES"); do
snapshot_processes "instance_churn_${i}" >/dev/null || true
check_zombies "instance_churn_${i}" || true
+ check_orphan_chrome "instance_churn_${i}" || true
done
snapshot_processes "post_instance_churn" >/dev/null
check_drift "post_instance_churn" "$BASELINE_CHROME" "$DRIFT_MID" || true
+check_orphan_chrome "post_instance_churn" || true
phase_summary "Phase C: Instance churn" "$DRIFT_MID"
# ── Phase D: Restart / recovery churn ───────────────────────────
@@ -538,7 +594,8 @@ for i in $(seq 1 "$RESTART_CYCLES"); do
echo " Restart cycle $i/$RESTART_CYCLES"
restart_container
BASELINE_CHROME=$(count_chrome)
- echo " Re-baselined chrome count: $BASELINE_CHROME"
+ BASELINE_ORPHANS=$(count_orphan_chrome_helpers)
+ echo " Re-baselined chrome count: $BASELINE_CHROME (orphans baseline: $BASELINE_ORPHANS)"
post_restart_probe "restart_${i}"
run_fixture_workload "restart_${i}"
@@ -571,9 +628,11 @@ log_phase "Phase F: Final verification"
echo "Expectations: final zombie count zero, chrome drift bounded, service still healthy and controllable."
FINAL_CHROME=$(count_chrome)
FINAL_ZOMBIES=$(count_zombies)
+FINAL_ORPHANS=$(count_orphan_chrome_helpers)
echo "Final chrome processes: $FINAL_CHROME (baseline: $BASELINE_CHROME)"
echo "Final zombie count: $FINAL_ZOMBIES"
+echo "Final orphan helpers (chrome PPID=1, non-zombie): $FINAL_ORPHANS"
if [ "$FINAL_ZOMBIES" -gt 0 ]; then
echo "FAIL [final]: zombie count $FINAL_ZOMBIES (must be 0)"
@@ -584,6 +643,8 @@ else
record_pass
fi
+check_orphan_chrome "final" || true
+
CHROME_DELTA=$((FINAL_CHROME - BASELINE_CHROME))
if [ "$CHROME_DELTA" -gt "$DRIFT_FINAL" ]; then
echo "FAIL [final]: chrome process drift +${CHROME_DELTA} above baseline"
@@ -607,6 +668,7 @@ echo "╠═══════════════════════
printf "║ %-20s %28s ║\n" "Assertions passed:" "$PASS_COUNT"
printf "║ %-20s %28s ║\n" "Assertions failed:" "$FAIL_COUNT"
printf "║ %-20s %28s ║\n" "Final zombie count:" "$FINAL_ZOMBIES"
+printf "║ %-20s %28s ║\n" "Final orphan helpers:" "$FINAL_ORPHANS"
printf "║ %-20s %28s ║\n" "Chrome baseline:" "$BASELINE_CHROME"
printf "║ %-20s %28s ║\n" "Chrome final:" "$FINAL_CHROME"
printf "║ %-20s %28s ║\n" "Chrome drift:" "${CHROME_DELTA}"
diff --git a/scripts/install-skills.sh b/scripts/install-skills.sh
index 425bd1fd..7afd3c55 100755
--- a/scripts/install-skills.sh
+++ b/scripts/install-skills.sh
@@ -1,15 +1,17 @@
#!/usr/bin/env bash
-# Symlink every skill under ./skills into ~/.claude/skills so Claude Code
-# picks them up globally. Editing files under ./skills/<name>/ is reflected
-# immediately because we use symlinks.
+# Symlink every skill under ./skills into ./.claude/skills so Claude Code
+# picks them up as repo-local skills (loaded only when CWD is inside this
+# repo). Editing files under ./skills/<name>/ is reflected immediately
+# because we use symlinks.
#
# Override the target directory with CLAUDE_SKILLS_DIR=<path> if you want
-# to install into a different Claude home (e.g. a project-local one).
+# to install into a different Claude home (e.g. ~/.claude/skills for a
+# global install).
set -euo pipefail
cd "$(dirname "$0")/.."
-TARGET_DIR="${CLAUDE_SKILLS_DIR:-$HOME/.claude/skills}"
+TARGET_DIR="${CLAUDE_SKILLS_DIR:-$(pwd)/.claude/skills}"
SOURCE_DIR="$(pwd)/skills"
if [[ ! -d "$SOURCE_DIR" ]]; then
diff --git a/scripts/lib/live-detection-sites.tsv b/scripts/lib/live-detection-sites.tsv
new file mode 100644
index 00000000..27943874
--- /dev/null
+++ b/scripts/lib/live-detection-sites.tsv
@@ -0,0 +1,23 @@
+# Live-detection probe site list.
+# Tab-separated columns:
+# name slug used for the per-site artifact directory
+# url page to navigate to
+# wait_for "selector" (waitFor selector) or "load" (skip wait)
+# selector CSS/XPath used both as waitSelector (when wait_for=selector)
+# and as the text-extract selector. "-" to skip text extract
+# and fall back to the full-page body text.
+# notes free-form description, displayed in report.md
+#
+# Lines starting with '#' or empty are ignored.
+#
+# NOTE on omitted sites:
+# * reCAPTCHA v3 — requires our own site key and an iframe-aware harness;
+# keep a placeholder until P6 follow-up.
+#
+# Extend by appending a new row. Selectors should target a small, stable
+# element whose innerText carries the detection verdict.
+browserscan https://www.browserscan.net/bot-detection selector #botStatus BrowserScan bot-detection page; #botStatus reflects PASS/FAIL.
+fingerprintjs-demo https://fingerprint.com/demo/ selector .visitorId FingerprintJS demo; visitorId text shows the stable visitor identifier.
+deviceandbrowserinfo https://deviceandbrowserinfo.com/ load - Device + browser info dump. Full-page text snapshot only.
+cloudflare-turnstile https://nopecha.com/demo/turnstile selector .cf-turnstile Cloudflare Turnstile interactive challenge widget.
+pixelscan https://pixelscan.net/ load body Pixelscan fingerprint/consistency check (replaces the old Cloudflare demo page).
diff --git a/scripts/lib/smoke-assertions.sh b/scripts/lib/smoke-assertions.sh
new file mode 100644
index 00000000..7cffa899
--- /dev/null
+++ b/scripts/lib/smoke-assertions.sh
@@ -0,0 +1,29 @@
+# shellcheck shell=bash
+# Provider-specific /stealth/status assertions.
+
+assert_stealth_status() {
+ local provider="$1"
+ local status
+ if ! status="$(curl -fsS -H "Authorization: Bearer ${TOKEN}" "http://127.0.0.1:${HOST_PORT}/stealth/status" 2>&1)"; then
+ fail "stealth status request failed: $status"
+ fi
+ echo " /stealth/status: $status"
+
+ case "$provider" in
+ chrome)
+ echo "$status" | jq -e '.provider == "chrome"' >/dev/null \
+ || fail "expected /stealth/status.provider=chrome: $status"
+ ;;
+ cloak)
+ echo "$status" | jq -e '
+ .provider == "cloak" and
+ .native == true and
+ .pinchtabOverlaysDisabled == true and
+ .fingerprintSeed == "42069"
+ ' >/dev/null || fail "unexpected cloak stealth status: $status"
+ ;;
+ *)
+ fail "assert_stealth_status: unknown provider: $provider"
+ ;;
+ esac
+}
diff --git a/scripts/lib/smoke-common.sh b/scripts/lib/smoke-common.sh
new file mode 100644
index 00000000..0c87e717
--- /dev/null
+++ b/scripts/lib/smoke-common.sh
@@ -0,0 +1,93 @@
+# shellcheck shell=bash
+# Shared primitives for smoke harnesses. Callers must export:
+# HOST_PORT, TOKEN, TMP_DIR, FAILED, API_RESULT, API_STATUS.
+
+skip() {
+ echo "SKIP: $*"
+ exit 77
+}
+
+fail() {
+ FAILED=1
+ echo "FAIL: $*" >&2
+ exit 1
+}
+
+require_cmd() {
+ command -v "$1" >/dev/null 2>&1 || fail "$1 not found in PATH"
+}
+
+choose_free_port() {
+ python3 - <<'PY'
+import socket
+
+sock = socket.socket()
+sock.bind(("127.0.0.1", 0))
+print(sock.getsockname()[1])
+sock.close()
+PY
+}
+
+api_request() {
+ local method="$1"
+ local path="$2"
+ local body="${3:-}"
+ local url="http://127.0.0.1:${HOST_PORT}${path}"
+ local -a args=(
+ -sS
+ -w $'\n%{http_code}'
+ -X "$method"
+ -H "Authorization: Bearer ${TOKEN}"
+ )
+ if [ "$method" = "POST" ]; then
+ args+=(-H "Content-Type: application/json" -d "$body")
+ fi
+
+ local response
+ if ! response="$(curl "${args[@]}" "$url" 2>&1)"; then
+ fail "$method $path failed: $response"
+ fi
+ API_STATUS="${response##*$'\n'}"
+ API_RESULT="${response%$'\n'*}"
+ if [ "$API_STATUS" -lt 200 ] || [ "$API_STATUS" -ge 300 ]; then
+ fail "$method $path failed with HTTP $API_STATUS: $API_RESULT"
+ fi
+}
+
+api_get() {
+ api_request GET "$1"
+}
+
+api_post() {
+ api_request POST "$1" "$2"
+}
+
+assert_api_jq() {
+ local expr="$1"
+ local label="$2"
+ echo "$API_RESULT" | jq -e "$expr" >/dev/null || fail "$label failed: $API_RESULT"
+}
+
+assert_file_min_bytes() {
+ local path="$1"
+ local min_bytes="$2"
+ local label="$3"
+ local bytes
+ bytes="$(wc -c < "$path" | tr -d '[:space:]')"
+ if [ "${bytes:-0}" -lt "$min_bytes" ]; then
+ fail "$label too small: ${bytes:-0} bytes"
+ fi
+}
+
+assert_screenshot_png() {
+ local path="$1"
+ local out="$TMP_DIR/screenshot.png"
+ local headers="$TMP_DIR/screenshot.headers"
+ curl -fsS \
+ -D "$headers" \
+ -o "$out" \
+ -H "Authorization: Bearer ${TOKEN}" \
+ "http://127.0.0.1:${HOST_PORT}${path}" || fail "GET $path failed"
+ grep -qi '^content-type: image/png' "$headers" || fail "GET $path did not return image/png"
+ assert_file_min_bytes "$out" 500 "screenshot"
+}
diff --git a/scripts/lib/smoke-config.sh b/scripts/lib/smoke-config.sh
new file mode 100644
index 00000000..0a3400f2
--- /dev/null
+++ b/scripts/lib/smoke-config.sh
@@ -0,0 +1,150 @@
+# shellcheck shell=bash
+# Generates runtime config JSON for the smoke harnesses.
+# write_provider_config <provider> <path> <token> <fixtures_host> [chrome_bin] [cloak_bin]
+# write_multi_target_config <path> <token> <fixtures_host> <chrome_bin> <cloak_bin> [primary_bin]
+# When primary_bin is set, the chrome target points there instead of chrome_bin
+# — used by the multi-target fallback assertion.
+
+write_provider_config() {
+ local provider="$1"
+ local config_path="$2"
+ local token="$3"
+ local fixtures_host="$4"
+ local chrome_binary="${5:-}"
+ local cloak_binary="${6:-}"
+
+ python3 - "$config_path" "$provider" "$token" "$fixtures_host" "$chrome_binary" "$cloak_binary" <<'PY'
+import json
+import sys
+
+path, provider, token, fixtures_host, chrome_binary, cloak_binary = sys.argv[1:7]
+
+browser = {
+ "provider": provider,
+ "extensionPaths": [],
+}
+if provider == "cloak":
+ if not cloak_binary:
+ raise SystemExit("cloak provider requires cloak_binary path")
+ browser["binary"] = cloak_binary
+ browser["cloak"] = {
+ "fingerprintSeed": "42069",
+ "platform": "linux",
+ "locale": "en-US",
+ "timezone": "UTC",
+ "disableDefaultStealthArgs": True,
+ }
+elif provider == "chrome":
+ if chrome_binary:
+ browser["binary"] = chrome_binary
+else:
+ raise SystemExit(f"unknown provider: {provider}")
+
+cfg = {
+ "server": {
+ "bind": "0.0.0.0",
+ "port": "9867",
+ "token": token,
+ "stateDir": "/data",
+ },
+ "browser": browser,
+ "instanceDefaults": {
+ "mode": "headless",
+ "humanize": True,
+ "maxTabs": 10,
+ },
+ "security": {
+ "allowEvaluate": True,
+ "allowDownload": True,
+ "allowCookies": True,
+ "allowUpload": True,
+ "allowClipboard": True,
+ "allowStateExport": True,
+ "allowedDomains": [fixtures_host, "127.0.0.1", "localhost", "::1"],
+ "downloadAllowedDomains": [fixtures_host],
+ "trustedResolveCIDRs": ["127.0.0.1/32"],
+ },
+ "profiles": {
+ "baseDir": "/data/profiles",
+ "defaultProfile": f"{provider}-docker-smoke",
+ },
+}
+with open(path, "w", encoding="utf-8") as fh:
+ json.dump(cfg, fh, indent=2)
+PY
+}
+
+write_multi_target_config() {
+ local config_path="$1"
+ local token="$2"
+ local fixtures_host="$3"
+ local chrome_binary="$4"
+ local cloak_binary="$5"
+ local primary_binary="${6:-}"
+
+ if [ -z "$chrome_binary" ] || [ -z "$cloak_binary" ]; then
+ fail "write_multi_target_config: chrome_binary and cloak_binary are required"
+ fi
+
+ python3 - "$config_path" "$token" "$fixtures_host" "$chrome_binary" "$cloak_binary" "$primary_binary" <<'PY'
+import json
+import sys
+
+path, token, fixtures_host, chrome_binary, cloak_binary, primary_binary = sys.argv[1:7]
+
+chrome_target_binary = primary_binary if primary_binary else chrome_binary
+
+cfg = {
+ "server": {
+ "bind": "0.0.0.0",
+ "port": "9867",
+ "token": token,
+ "stateDir": "/data",
+ },
+ "browser": {
+ "extensionPaths": [],
+ "targets": {
+ "chrome": {
+ "provider": "chrome",
+ "binary": chrome_target_binary,
+ },
+ "cloak": {
+ "provider": "cloak",
+ "binary": cloak_binary,
+ "cloak": {
+ "fingerprintSeed": "42069",
+ "platform": "linux",
+ "locale": "en-US",
+ "timezone": "UTC",
+ "disableDefaultStealthArgs": True,
+ },
+ },
+ },
+ "defaultTarget": "chrome",
+ "fallbackOrder": ["chrome", "cloak"],
+ },
+ "instanceDefaults": {
+ "mode": "headless",
+ "humanize": True,
+ "maxTabs": 10,
+ },
+ "security": {
+ "allowEvaluate": True,
+ "allowDownload": True,
+ "allowCookies": True,
+ "allowUpload": True,
+ "allowClipboard": True,
+ "allowStateExport": True,
+ "allowedDomains": [fixtures_host, "127.0.0.1", "localhost", "::1"],
+ "downloadAllowedDomains": [fixtures_host],
+ "trustedResolveCIDRs": ["127.0.0.1/32"],
+ },
+ "profiles": {
+ "baseDir": "/data/profiles",
+ "defaultProfile": "multi-target-docker-smoke",
+ },
+}
+with open(path, "w", encoding="utf-8") as fh:
+ json.dump(cfg, fh, indent=2)
+PY
+}
diff --git a/scripts/lib/smoke-container.sh b/scripts/lib/smoke-container.sh
new file mode 100644
index 00000000..ceb600a6
--- /dev/null
+++ b/scripts/lib/smoke-container.sh
@@ -0,0 +1,60 @@
+# shellcheck shell=bash
+# Container lifecycle helpers.
+# start_provider_container <name> <image> <config_path> <fixtures_host> <fixtures_port> <root>
+# resolve_host_port <name> — echoes host port mapped to container :9867
+# teardown_container <name> — idempotent force-remove
+#
+# Env: PROFILE_VOLUME=<name> swaps /data from tmpfs to a persistent Docker
+# named volume (used by the profile-persistence leg).
+
+start_provider_container() {
+ local name="$1"
+ local image="$2"
+ local config_path="$3"
+ local fixtures_host="$4"
+ local fixtures_port="$5"
+ local root="$6"
+
+ local -a data_mount
+ if [ -n "${PROFILE_VOLUME:-}" ]; then
+ data_mount=(-v "${PROFILE_VOLUME}:/data:rw")
+ else
+ data_mount=(--tmpfs "/data:rw,size=1024m,uid=1000,gid=1000,mode=0755")
+ fi
+
+ docker run -d \
+ --name "$name" \
+ --user 1000:1000 \
+ --shm-size=2g \
+ "${data_mount[@]}" \
+ --tmpfs /tmp:rw,size=512m,mode=1777 \
+ --add-host "${fixtures_host}:127.0.0.1" \
+ -e "PINCHTAB_CONFIG=/config/pinchtab.json" \
+ -v "${config_path}:/config/pinchtab.json:ro" \
+ -v "${root}/tests/e2e/fixtures:/fixtures:ro" \
+ -v "${root}/tests/tools/fixtures/static-server.pl:/usr/local/bin/fixture-server.pl:ro" \
+ --publish "127.0.0.1::9867" \
+ --publish "127.0.0.1:${fixtures_port}:${fixtures_port}" \
+ "$image" >/dev/null
+ CONTAINER_STARTED=1
+}
+
+resolve_host_port() {
+ local name="$1"
+ local port
+ port="$(docker port "$name" 9867/tcp 2>/dev/null | head -1 | awk -F: '{print $NF}' || true)"
+ if [ -z "$port" ]; then
+ port="$(docker inspect -f '{{with index .NetworkSettings.Ports "9867/tcp"}}{{(index . 0).HostPort}}{{end}}' "$name" 2>/dev/null || true)"
+ fi
+ if [ -z "$port" ]; then
+ fail "failed to determine published host port for $name"
+ fi
+ echo "$port"
+}
+
+teardown_container() {
+ local name="$1"
+ if docker ps -a --format '{{.Names}}' | grep -Fxq "$name"; then
+ docker rm -f "$name" >/dev/null 2>&1 || true
+ fi
+}
diff --git a/scripts/lib/smoke-diagnostics.sh b/scripts/lib/smoke-diagnostics.sh
new file mode 100644
index 00000000..8e01eea9
--- /dev/null
+++ b/scripts/lib/smoke-diagnostics.sh
@@ -0,0 +1,73 @@
+# shellcheck shell=bash
+# On-failure inline dump: container logs, process list, fixture log, HTTP
+# diagnostics, rendered config, plus a copy of /data into TMP_DIR.
+# Idempotent and tolerates missing state.
+
+dump_diagnostics() {
+ local provider="$1"
+ local name="$2"
+ local host_port="$3"
+ local token="$4"
+ local config_path="$5"
+ local fixtures_started="${6:-0}"
+
+ echo ""
+ echo "===== Diagnostics (provider=${provider}, container=${name}) ====="
+
+ echo ""
+ echo "--- Provider config (${config_path}) ---"
+ if [ -f "$config_path" ]; then
+ cat "$config_path" || true
+ else
+ echo "(config file missing)"
+ fi
+
+ if [ -n "$name" ] && docker ps -a --format '{{.Names}}' | grep -Fxq "$name"; then
+ echo ""
+ echo "--- Container logs (last 200) ---"
+ docker logs --tail 200 "$name" 2>&1 || true
+
+ echo ""
+ echo "--- Process list ---"
+ docker exec "$name" ps -eo pid,user,args 2>&1 || true
+
+ if [ "$fixtures_started" = "1" ]; then
+ echo ""
+ echo "--- Fixture server log ---"
+ docker exec "$name" sh -lc 'cat /tmp/pinchtab-fixtures.log 2>/dev/null || true' || true
+ fi
+
+ mkdir -p "$TMP_DIR/${provider}/data"
+ docker cp "${name}:/data/." "$TMP_DIR/${provider}/data/" >/dev/null 2>&1 || true
+ else
+ echo "(container ${name} not found; skipping container-level diagnostics)"
+ fi
+
+ if [ -n "${host_port:-}" ]; then
+ echo ""
+ echo "--- HTTP /stealth/status ---"
+ curl -sS -H "Authorization: Bearer ${token}" "http://127.0.0.1:${host_port}/stealth/status" 2>&1 || true
+ echo ""
+
+ echo ""
+ echo "--- HTTP /autorestart/status ---"
+ curl -sS -H "Authorization: Bearer ${token}" "http://127.0.0.1:${host_port}/autorestart/status" 2>&1 || true
+ echo ""
+
+ echo ""
+ echo "--- HTTP /instances ---"
+ local instances_diag
+ instances_diag="$(curl -sS -H "Authorization: Bearer ${token}" "http://127.0.0.1:${host_port}/instances" 2>/dev/null || true)"
+ echo "$instances_diag"
+ echo "$instances_diag" | jq -r '.[].id? // empty' 2>/dev/null | while read -r inst_id; do
+ [ -n "$inst_id" ] || continue
+ echo ""
+ echo "--- HTTP /instances/${inst_id}/logs ---"
+ curl -sS -H "Authorization: Bearer ${token}" "http://127.0.0.1:${host_port}/instances/${inst_id}/logs" 2>&1 || true
+ echo ""
+ done
+ fi
+
+ echo ""
+ echo "===== End diagnostics (${provider}) ====="
+}
diff --git a/scripts/lib/smoke-endpoints.sh b/scripts/lib/smoke-endpoints.sh
new file mode 100644
index 00000000..26aaa5d2
--- /dev/null
+++ b/scripts/lib/smoke-endpoints.sh
@@ -0,0 +1,50 @@
+# shellcheck shell=bash
+# Provider-agnostic fixture-backed endpoint smoke. Requires globals
+# HOST_PORT, TOKEN, FIXTURES_URL, TMP_DIR.
+
+run_fixture_endpoint_smoke() {
+ echo "Running fixture-backed endpoint smoke (provider-agnostic)..."
+
+ api_post /navigate "{\"url\":\"${FIXTURES_URL}/index.html\",\"waitFor\":\"selector\",\"waitSelector\":\"#welcome\"}"
+ assert_api_jq '.title | contains("Home")' "fixture home navigation title"
+ assert_api_jq '.url | contains("index.html")' "fixture home navigation URL"
+ local tab_id
+ tab_id="$(echo "$API_RESULT" | jq -r '.tabId // empty')"
+ [ -n "$tab_id" ] || fail "navigate response did not include tabId: $API_RESULT"
+
+ api_get /tabs
+ echo "$API_RESULT" | jq -e --arg tab "$tab_id" '.tabs | map(.id) | index($tab) != null' >/dev/null \
+ || fail "tabs includes fixture tab failed: $API_RESULT"
+
+ api_get "/snapshot?tabId=${tab_id}&filter=interactive"
+ assert_api_jq '.nodes | length > 0' "snapshot returns nodes"
+
+ api_get "/tabs/${tab_id}/text"
+ assert_api_jq '.text | contains("Welcome to the E2E test fixtures")' "tab text includes fixture content"
+
+ api_get "/tabs/${tab_id}/html?selector=%23welcome"
+ assert_api_jq '.html | contains("Welcome to the E2E test fixtures")' "selected html includes fixture content"
+
+ api_get "/tabs/${tab_id}/styles?selector=%23welcome&prop=display"
+ assert_api_jq '.styles.display == "block"' "selected styles include display"
+
+ assert_screenshot_png "/tabs/${tab_id}/screenshot?format=png&raw=true"
+
+ api_post "/tabs/${tab_id}/navigate" "{\"url\":\"${FIXTURES_URL}/buttons.html\",\"waitFor\":\"selector\",\"waitSelector\":\"#increment\"}"
+ assert_api_jq '.title | contains("Buttons")' "buttons navigation title"
+
+ api_post "/tabs/${tab_id}/action" '{"kind":"click","selector":"#increment"}'
+ assert_api_jq '.success == true' "click action succeeded"
+
+ api_post "/tabs/${tab_id}/evaluate" '{"expression":"document.querySelector(\"#count\").textContent"}'
+ assert_api_jq '.result == "1"' "evaluate sees click result"
+
+ api_post "/tabs/${tab_id}/navigate" "{\"url\":\"${FIXTURES_URL}/form.html\",\"waitFor\":\"selector\",\"waitSelector\":\"#username\"}"
+ assert_api_jq '.title | contains("Form")' "form navigation title"
+
+ api_post "/tabs/${tab_id}/actions" '{"stopOnError":true,"actions":[{"kind":"fill","selector":"#username","text":"parity_user"},{"kind":"check","selector":"#terms"}]}'
+ assert_api_jq '.successful == 2 and .failed == 0' "batch actions succeeded"
+
+ api_post "/tabs/${tab_id}/evaluate" '{"expression":"({username: document.querySelector(\"#username\").value, terms: document.querySelector(\"#terms\").checked})"}'
+ assert_api_jq '.result.username == "parity_user" and .result.terms == true' "evaluate sees batch action results"
+}
diff --git a/scripts/lib/smoke-fixtures.sh b/scripts/lib/smoke-fixtures.sh
new file mode 100644
index 00000000..4aec9aaf
--- /dev/null
+++ b/scripts/lib/smoke-fixtures.sh
@@ -0,0 +1,27 @@
+# shellcheck shell=bash
+# Fixture HTTP server startup inside the leg container.
+# start_fixture_server <name> <fixtures_port> — backgrounds the perl static server
+# wait_fixtures_ready <name> <fixtures_url> <host_fixtures_url> [tries=30]
+
+start_fixture_server() {
+ local name="$1"
+ local fixtures_port="$2"
+ docker exec "$name" sh -lc \
+ "FIXTURES_ROOT=/fixtures FIXTURES_PORT=${fixtures_port} /usr/bin/perl /usr/local/bin/fixture-server.pl >/tmp/pinchtab-fixtures.log 2>&1 &"
+ FIXTURES_STARTED=1
+}
+
+wait_fixtures_ready() {
+ local name="$1"
+ local fixtures_url="$2"
+ local host_fixtures_url="$3"
+ local tries="${4:-30}"
+ for _ in $(seq 1 "$tries"); do
+ if curl -fsS "${host_fixtures_url}/index.html" >/dev/null 2>&1 &&
+ docker exec "$name" curl -fsS "${fixtures_url}/index.html" >/dev/null 2>&1; then
+ return 0
+ fi
+ sleep 1
+ done
+ fail "fixture server was not reachable from the PinchTab container at ${fixtures_url}"
+}
diff --git a/scripts/lib/smoke-health.sh b/scripts/lib/smoke-health.sh
new file mode 100644
index 00000000..3da55004
--- /dev/null
+++ b/scripts/lib/smoke-health.sh
@@ -0,0 +1,40 @@
+# shellcheck shell=bash
+# HTTP readiness polling helpers.
+# wait_for_health <host_port> <token> [tries=90]
+# wait_for_instance_running <host_port> <token> [tries=120]
+# — aborts early if /autorestart/status reports status=crashed.
+
+wait_for_health() {
+ local host_port="$1"
+ local token="$2"
+ local tries="${3:-90}"
+ local health_body=""
+ for _ in $(seq 1 "$tries"); do
+ if curl -fsS -H "Authorization: Bearer ${token}" "http://127.0.0.1:${host_port}/health" >/dev/null 2>&1; then
+ return 0
+ fi
+ sleep 1
+ done
+ health_body="$(curl -sS -H "Authorization: Bearer ${token}" "http://127.0.0.1:${host_port}/health" 2>&1 || true)"
+ fail "health check did not pass: $health_body"
+}
+
+wait_for_instance_running() {
+ local host_port="$1"
+ local token="$2"
+ local tries="${3:-120}"
+ local instances_body="[]"
+ local autorestart_body="{}"
+ for _ in $(seq 1 "$tries"); do
+ instances_body="$(curl -fsS -H "Authorization: Bearer ${token}" "http://127.0.0.1:${host_port}/instances" 2>/dev/null || echo "[]")"
+ if echo "$instances_body" | jq -e '.[]? | select(.status == "running")' >/dev/null; then
+ return 0
+ fi
+ autorestart_body="$(curl -fsS -H "Authorization: Bearer ${token}" "http://127.0.0.1:${host_port}/autorestart/status" 2>/dev/null || echo "{}")"
+ if echo "$autorestart_body" | jq -e '.status == "crashed"' >/dev/null 2>&1; then
+ break
+ fi
+ sleep 1
+ done
+ fail "managed browser instance did not become running: instances=$instances_body autorestart=$autorestart_body"
+}
diff --git a/scripts/lib/smoke-multi-target.sh b/scripts/lib/smoke-multi-target.sh
new file mode 100644
index 00000000..d25c68ee
--- /dev/null
+++ b/scripts/lib/smoke-multi-target.sh
@@ -0,0 +1,175 @@
+# shellcheck shell=bash
+# Assertions for the multi-target parity leg: request-level target selection,
+# default-target resolution, and primary-failure fallback.
+
+# Writes a stub binary that exits 1. Bind-mounted from host so the non-root
+# container user can exec it.
+setup_broken_binary() {
+ local path="$1"
+ cat >"$path" <<'SH'
+#!/bin/sh
+echo "broken-binary stub: refusing to start" >&2
+exit 1
+SH
+ chmod +x "$path"
+ echo "$path"
+}
+
+_wait_for_instance_status() {
+ local host_port="$1"
+ local token="$2"
+ local id="$3"
+ local target="$4"
+ local tries="${5:-120}"
+ local body=""
+ for _ in $(seq 1 "$tries"); do
+ body="$(curl -fsS -H "Authorization: Bearer ${token}" "http://127.0.0.1:${host_port}/instances/${id}" 2>/dev/null || echo "{}")"
+ local status
+ status="$(echo "$body" | jq -r '.status // empty')"
+ if [ "$status" = "$target" ]; then
+ echo "$body"
+ return 0
+ fi
+ if [ "$status" = "error" ]; then
+ fail "instance $id entered status=error while waiting for $target: $body"
+ fi
+ sleep 1
+ done
+ fail "instance $id did not reach status=$target within ${tries}s: $body"
+}
+
+# Best-effort stop; never fails the leg.
+_stop_instance() {
+ local host_port="$1"
+ local token="$2"
+ local id="$3"
+ [ -n "$id" ] || return 0
+ curl -fsS -X POST -H "Authorization: Bearer ${token}" \
+ "http://127.0.0.1:${host_port}/instances/${id}/stop" >/dev/null 2>&1 || true
+}
+
+# Uses the Instance response (not /stealth/status) as the authoritative
+# provider signal — /stealth/status is process-scoped and unreliable in
+# multi-instance setups.
+assert_target_selection() {
+ local host_port="$1"
+ local token="$2"
+ local target="$3"
+ local expected_provider="$4"
+
+ echo " → target selection: browserTarget=${target} (expecting provider=${expected_provider})"
+
+ local body
+ body="$(curl -fsS -X POST \
+ -H "Authorization: Bearer ${token}" \
+ -H "Content-Type: application/json" \
+ -d "{\"browserTarget\":\"${target}\"}" \
+ "http://127.0.0.1:${host_port}/instances/start" 2>&1)" \
+ || fail "POST /instances/start (target=${target}) failed: $body"
+
+ local instance_id resolved_target launch_provider
+ instance_id="$(echo "$body" | jq -r '.id // empty')"
+ resolved_target="$(echo "$body" | jq -r '.browserTarget // empty')"
+ launch_provider="$(echo "$body" | jq -r '.browserProvider // empty')"
+ [ -n "$instance_id" ] || fail "instances/start (target=${target}) returned no id: $body"
+ if [ "$resolved_target" != "$target" ]; then
+ fail "instances/start (target=${target}) returned browserTarget=${resolved_target}: $body"
+ fi
+ if [ "$launch_provider" != "$expected_provider" ]; then
+ fail "instances/start (target=${target}) returned browserProvider=${launch_provider}, expected ${expected_provider}: $body"
+ fi
+
+ local running_body
+ running_body="$(_wait_for_instance_status "$host_port" "$token" "$instance_id" "running")"
+
+ local got_target got_provider
+ got_target="$(echo "$running_body" | jq -r '.browserTarget // empty')"
+ got_provider="$(echo "$running_body" | jq -r '.browserProvider // empty')"
+ echo " running instance: browserTarget=${got_target} browserProvider=${got_provider}"
+ if [ "$got_provider" != "$expected_provider" ]; then
+ fail "running instance for target=${target} reports browserProvider=${got_provider}, expected ${expected_provider}: $running_body"
+ fi
+
+ _stop_instance "$host_port" "$token" "$instance_id"
+}
+
+assert_default_target() {
+ local host_port="$1"
+ local token="$2"
+ local expected="$3"
+
+ echo " → default target (expecting browserTarget=${expected})"
+
+ local body
+ body="$(curl -fsS -X POST \
+ -H "Authorization: Bearer ${token}" \
+ -H "Content-Type: application/json" \
+ -d '{}' \
+ "http://127.0.0.1:${host_port}/instances/start" 2>&1)" \
+ || fail "POST /instances/start (default) failed: $body"
+
+ local instance_id resolved
+ instance_id="$(echo "$body" | jq -r '.id // empty')"
+ resolved="$(echo "$body" | jq -r '.browserTarget // empty')"
+ [ -n "$instance_id" ] || fail "instances/start (default) returned no id: $body"
+ echo " response browserTarget: ${resolved}"
+ if [ "$resolved" != "$expected" ]; then
+ _stop_instance "$host_port" "$token" "$instance_id"
+ fail "expected default browserTarget=${expected}, got ${resolved}: $body"
+ fi
+
+ _wait_for_instance_status "$host_port" "$token" "$instance_id" "running" >/dev/null
+ _stop_instance "$host_port" "$token" "$instance_id"
+}
+
+assert_fallback() {
+ local host_port="$1"
+ local token="$2"
+ local broken="$3"
+ local healthy="$4"
+ local expected_provider="$5"
+
+ echo " → fallback: primary=${broken} (broken) → ${healthy} (healthy)"
+
+ local body
+ body="$(curl -fsS -X POST \
+ -H "Authorization: Bearer ${token}" \
+ -H "Content-Type: application/json" \
+ -d "{\"browserTarget\":\"${broken}\",\"fallbackTargets\":[\"${healthy}\"]}" \
+ "http://127.0.0.1:${host_port}/instances/start" 2>&1)" \
+ || fail "POST /instances/start (fallback) failed: $body"
+
+ local instance_id resolved fallback_from fallback_reason
+ instance_id="$(echo "$body" | jq -r '.id // empty')"
+ resolved="$(echo "$body" | jq -r '.browserTarget // empty')"
+ fallback_from="$(echo "$body" | jq -r '.fallbackFrom // empty')"
+ fallback_reason="$(echo "$body" | jq -r '.fallbackReason // empty')"
+
+ [ -n "$instance_id" ] || fail "fallback launch returned no id: $body"
+ echo " response: browserTarget=${resolved} fallbackFrom=${fallback_from} fallbackReason=${fallback_reason}"
+
+ if [ -z "$fallback_from" ] || [ -z "$fallback_reason" ]; then
+ _stop_instance "$host_port" "$token" "$instance_id"
+ fail "expected non-empty fallbackFrom + fallbackReason on response: $body"
+ fi
+ if [ "$fallback_from" != "$broken" ]; then
+ _stop_instance "$host_port" "$token" "$instance_id"
+ fail "expected fallbackFrom=${broken}, got ${fallback_from}: $body"
+ fi
+ if [ "$resolved" != "$healthy" ]; then
+ _stop_instance "$host_port" "$token" "$instance_id"
+ fail "expected resolved browserTarget=${healthy}, got ${resolved}: $body"
+ fi
+
+ local running_body
+ running_body="$(_wait_for_instance_status "$host_port" "$token" "$instance_id" "running")"
+ local got_provider
+ got_provider="$(echo "$running_body" | jq -r '.browserProvider // empty')"
+ echo " running instance: browserProvider=${got_provider}"
+ if [ "$got_provider" != "$expected_provider" ]; then
+ _stop_instance "$host_port" "$token" "$instance_id"
+ fail "fallback instance reports browserProvider=${got_provider}, expected ${expected_provider}: $running_body"
+ fi
+
+ _stop_instance "$host_port" "$token" "$instance_id"
+}
diff --git a/scripts/lib/smoke-persistence.sh b/scripts/lib/smoke-persistence.sh
new file mode 100644
index 00000000..397f5cc1
--- /dev/null
+++ b/scripts/lib/smoke-persistence.sh
@@ -0,0 +1,325 @@
+# shellcheck shell=bash
+# Profile-persistence round-trip helpers (P3a). Verifies localStorage + cookie
+# survive a container stop/restart when /data is backed by a Docker volume.
+# Mutates globals: CONTAINER_STARTED, FIXTURES_STARTED, HOST_PORT.
+
+setup_profile_volume() {
+ local name="$1"
+ [ -n "$name" ] || fail "setup_profile_volume: name required"
+ # Remove any stale volume so we start from an empty profile.
+ if docker volume inspect "$name" >/dev/null 2>&1; then
+ docker volume rm "$name" >/dev/null 2>&1 || true
+ fi
+ docker volume create "$name" >/dev/null || fail "failed to create docker volume $name"
+ echo "$name"
+}
+
+cleanup_profile_volume() {
+ local name="$1"
+ [ -n "$name" ] || return 0
+ if ! docker volume inspect "$name" >/dev/null 2>&1; then
+ return 0
+ fi
+ # Tolerate "volume in use" so a failed leg doesn't mask the original error.
+ if ! docker volume rm "$name" >/dev/null 2>&1; then
+ echo " warn: docker volume rm $name failed (likely still in use); leaving for manual cleanup" >&2
+ fi
+}
+
+_read_marker_from_managed_instance() {
+ local host_port="$1"
+ local token="$2"
+ local fixtures_url="$3"
+
+ local nav_body
+ nav_body="$(curl -fsS -X POST \
+ -H "Authorization: Bearer ${token}" \
+ -H "Content-Type: application/json" \
+ -d "{\"url\":\"${fixtures_url}/persistence-marker.html\",\"waitFor\":\"selector\",\"waitSelector\":\"#marker\"}" \
+ "http://127.0.0.1:${host_port}/navigate" 2>&1)" \
+ || fail "navigate to persistence-marker.html failed: $nav_body"
+
+ local tab_id
+ tab_id="$(echo "$nav_body" | jq -r '.tabId // empty')"
+ [ -n "$tab_id" ] || fail "navigate response missing tabId: $nav_body"
+
+ local html_body
+ html_body="$(curl -fsS \
+ -H "Authorization: Bearer ${token}" \
+ "http://127.0.0.1:${host_port}/tabs/${tab_id}/html?selector=%23marker" 2>&1)" \
+ || fail "GET /tabs/${tab_id}/html for #marker failed: $html_body"
+
+ local raw_html
+ raw_html="$(echo "$html_body" | jq -r '.html // empty')"
+ [ -n "$raw_html" ] || fail "marker html was empty: $html_body"
+
+ local marker
+ marker="$(printf '%s' "$raw_html" | sed -E 's/<[^>]+>//g' | tr -d '[:space:]')"
+ [ -n "$marker" ] || fail "marker text was empty after strip: $raw_html"
+ [ "$marker" != "pending" ] || fail "marker text was still 'pending' (fixture JS did not run): $raw_html"
+
+ echo "$marker"
+}
+
+assert_persistence_round_trip() {
+ local provider="$1"
+ local image="$2"
+ local name="$3"
+ local config_path="$4"
+ local fixtures_host="$5"
+ local fixtures_port="$6"
+ local fixtures_url="$7"
+ local host_fixtures_url="$8"
+ local token="$9"
+ local root="${10}"
+ local profile_volume="${11}"
+
+ [ -n "$profile_volume" ] || fail "assert_persistence_round_trip requires a profile volume"
+
+ echo "→ Phase 1: capture marker (fresh volume, first boot)"
+ local first_marker
+ first_marker="$(_read_marker_from_managed_instance "$HOST_PORT" "$token" "$fixtures_url")"
+ echo " first-boot marker: $first_marker"
+
+ echo "→ Phase 2: stop container (graceful) to flush profile to volume $profile_volume"
+ # Must stop the managed instance via the API first: only the full graceful
+ # path (Browser.close + wait-for-exit) makes Chrome flush localStorage to
+ # leveldb. `docker stop` alone is too fast.
+ local inst_id
+ inst_id="$(curl -fsS -H "Authorization: Bearer ${token}" \
+ "http://127.0.0.1:${HOST_PORT}/instances" 2>/dev/null \
+ | jq -r '.[]? | select(.status=="running") | .id' | head -1)"
+ if [ -n "$inst_id" ]; then
+ echo " stopping managed instance $inst_id"
+ curl -fsS -X POST -H "Authorization: Bearer ${token}" \
+ "http://127.0.0.1:${HOST_PORT}/instances/${inst_id}/stop" >/dev/null 2>&1 || true
+ local i
+ for i in $(seq 1 30); do
+ local still
+ still="$(curl -fsS -H "Authorization: Bearer ${token}" \
+ "http://127.0.0.1:${HOST_PORT}/instances/${inst_id}" 2>/dev/null \
+ | jq -r '.status // "gone"')"
+ if [ "$still" != "running" ]; then
+ break
+ fi
+ sleep 1
+ done
+ fi
+ # Extend grace period beyond the 10s default in case I/O is still in flight.
+ docker stop --time 30 "$name" >/dev/null || fail "docker stop $name failed"
+ teardown_container "$name"
+ CONTAINER_STARTED=0
+ FIXTURES_STARTED=0
+
+ echo "→ Phase 3: restart container with identical name + config + token + volume"
+ PROFILE_VOLUME="$profile_volume" start_provider_container \
+ "$name" "$image" "$config_path" "$fixtures_host" "$fixtures_port" "$root"
+ HOST_PORT="$(resolve_host_port "$name")"
+ echo " Container $name restarted — PinchTab on host port $HOST_PORT"
+
+ start_fixture_server "$name" "$fixtures_port"
+ wait_fixtures_ready "$name" "$fixtures_url" "$host_fixtures_url"
+
+ echo " Waiting for PinchTab health on :${HOST_PORT}..."
+ wait_for_health "$HOST_PORT" "$token"
+ echo " Waiting for managed ${provider} instance (post-restart)..."
+ wait_for_instance_running "$HOST_PORT" "$token"
+
+ echo "→ Phase 4: re-read marker and assert equality"
+ local second_marker
+ second_marker="$(_read_marker_from_managed_instance "$HOST_PORT" "$token" "$fixtures_url")"
+ echo " post-restart marker: $second_marker"
+
+ if [ "$first_marker" != "$second_marker" ]; then
+ fail "profile persistence round-trip failed: first=${first_marker} second=${second_marker}"
+ fi
+ echo " marker matches across restart — localStorage + cookie persisted via $profile_volume"
+}
+
+# Stale profile-lock recovery (P3b) helpers. After the P3a round-trip,
+# plants SingletonLock/Socket/Cookie referencing an unused PID and asserts
+# PinchTab recovers. Plant container chowns to 1000:1000 so the non-root
+# pinchtab user can later read+delete the files.
+
+_pick_unused_pid() {
+ local pid=99999
+ local guard=0
+ while kill -0 "$pid" 2>/dev/null; do
+ pid=$((RANDOM + 10000))
+ guard=$((guard + 1))
+ if [ "$guard" -gt 100 ]; then
+ fail "could not find an unused PID after 100 attempts"
+ fi
+ done
+ echo "$pid"
+}
+
+# Plants the three Singleton* files inside the volume. profile_subpath is
+# volume-relative (no leading slash), e.g. "profiles/cloak-docker-smoke".
+plant_stale_lock() {
+ local volume_name="$1"
+ local profile_subpath="$2"
+ local fake_pid="$3"
+
+ [ -n "$volume_name" ] || fail "plant_stale_lock: volume_name required"
+ [ -n "$profile_subpath" ] || fail "plant_stale_lock: profile_subpath required"
+ [ -n "$fake_pid" ] || fail "plant_stale_lock: fake_pid required"
+
+ # Short-lived root container so we can chown to 1000:1000; the PinchTab
+ # container itself never runs as root.
+ docker run --rm \
+ --user 0:0 \
+ -v "${volume_name}:/data:rw" \
+ -e "PROFILE_SUBPATH=${profile_subpath}" \
+ -e "FAKE_PID=${fake_pid}" \
+ alpine:3.20 sh -lc '
+ set -eu
+ profile_dir="/data/${PROFILE_SUBPATH}"
+ if [ ! -d "$profile_dir" ]; then
+ echo "plant_stale_lock: profile dir $profile_dir does not exist; current /data layout:" >&2
+ find /data -maxdepth 3 -type d -printf "%p\n" 2>/dev/null | sed -n "1,40p" >&2
+ exit 1
+ fi
+ # Sentinel "STALE_PLANT_" lets assert_lock_files_gone distinguish
+ # planted files from fresh ones Chrome re-creates after recovery.
+ content="STALE_PLANT_${FAKE_PID}_$(date +%s)"
+ for f in SingletonLock SingletonSocket SingletonCookie; do
+ printf "%s" "$content" > "$profile_dir/$f"
+ done
+ chown -R 1000:1000 "$profile_dir"
+ echo "planted stale lock files in $profile_dir (pid=$FAKE_PID)"
+ ls -la "$profile_dir" | sed -n "1,20p"
+ ' >&2 || fail "plant_stale_lock: helper container failed"
+}
+
+# Asserts no planted sentinel files remain. Chrome may re-create fresh
+# Singleton* files post-recovery; only those still carrying the
+# "STALE_PLANT_" sentinel indicate recovery missed them.
+assert_lock_files_gone() {
+ local volume_name="$1"
+ local profile_subpath="$2"
+
+ [ -n "$volume_name" ] || fail "assert_lock_files_gone: volume_name required"
+ [ -n "$profile_subpath" ] || fail "assert_lock_files_gone: profile_subpath required"
+
+ local out
+ out="$(docker run --rm \
+ -v "${volume_name}:/data:ro" \
+ -e "PROFILE_SUBPATH=${profile_subpath}" \
+ alpine:3.20 sh -lc '
+ set -eu
+ profile_dir="/data/${PROFILE_SUBPATH}"
+ if [ ! -d "$profile_dir" ]; then
+ echo "MISSING_DIR"
+ exit 0
+ fi
+ survivors=""
+ for f in SingletonLock SingletonSocket SingletonCookie; do
+ if [ -e "$profile_dir/$f" ] || [ -L "$profile_dir/$f" ]; then
+ # Skip symlinks: Chrome re-creates SingletonLock as a symlink to
+ # its own live PID — healthy state, not a stale plant.
+ if [ -L "$profile_dir/$f" ]; then
+ continue
+ fi
+ if grep -q "STALE_PLANT_" "$profile_dir/$f" 2>/dev/null; then
+ survivors="${survivors}${f} "
+ fi
+ fi
+ done
+ if [ -n "$survivors" ]; then
+ echo "SURVIVORS: $survivors"
+ ls -la "$profile_dir" | sed -n "1,40p"
+ exit 1
+ fi
+ echo "OK"
+ ' 2>&1)" || fail "assert_lock_files_gone: stale singleton files remain in ${profile_subpath}: $out"
+
+ echo " $out"
+}
+
+# Full lock-recovery round-trip on top of P3a: stops the container, plants
+# stale Singleton* files, restarts, and asserts health, preserved marker,
+# and that the planted sentinel files were cleared.
+assert_lock_recovery_round_trip() {
+ local provider="$1"
+ local image="$2"
+ local name="$3"
+ local config_path="$4"
+ local fixtures_host="$5"
+ local fixtures_port="$6"
+ local fixtures_url="$7"
+ local host_fixtures_url="$8"
+ local token="$9"
+ local root="${10}"
+ local profile_volume="${11}"
+ local profile_subpath="${12}"
+
+ [ -n "$profile_volume" ] || fail "assert_lock_recovery_round_trip requires a profile volume"
+ [ -n "$profile_subpath" ] || fail "assert_lock_recovery_round_trip requires a profile subpath"
+
+ assert_persistence_round_trip \
+ "$provider" "$image" "$name" "$config_path" \
+ "$fixtures_host" "$fixtures_port" \
+ "$fixtures_url" "$host_fixtures_url" \
+ "$token" "$root" "$profile_volume"
+
+ local seeded_marker
+ seeded_marker="$(_read_marker_from_managed_instance "$HOST_PORT" "$token" "$fixtures_url")"
+ echo "→ Phase L1: captured post-P3a marker for recovery leg: $seeded_marker"
+
+ echo "→ Phase L2: stop container to plant stale lock on volume ${profile_volume}"
+ local inst_id
+ inst_id="$(curl -fsS -H "Authorization: Bearer ${token}" \
+ "http://127.0.0.1:${HOST_PORT}/instances" 2>/dev/null \
+ | jq -r '.[]? | select(.status=="running") | .id' | head -1)"
+ if [ -n "$inst_id" ]; then
+ curl -fsS -X POST -H "Authorization: Bearer ${token}" \
+ "http://127.0.0.1:${HOST_PORT}/instances/${inst_id}/stop" >/dev/null 2>&1 || true
+ local i
+ for i in $(seq 1 30); do
+ local still
+ still="$(curl -fsS -H "Authorization: Bearer ${token}" \
+ "http://127.0.0.1:${HOST_PORT}/instances/${inst_id}" 2>/dev/null \
+ | jq -r '.status // "gone"')"
+ [ "$still" != "running" ] && break
+ sleep 1
+ done
+ fi
+ docker stop --time 30 "$name" >/dev/null || fail "docker stop $name failed"
+ teardown_container "$name"
+ CONTAINER_STARTED=0
+ FIXTURES_STARTED=0
+
+ echo "→ Phase L3: plant stale singleton files in ${profile_subpath}"
+ local fake_pid
+ fake_pid="$(_pick_unused_pid)"
+ echo " using fake pid=${fake_pid} (verified not alive on host)"
+ plant_stale_lock "$profile_volume" "$profile_subpath" "$fake_pid"
+
+ echo "→ Phase L4: restart container — PinchTab must detect + clear stale lock"
+ PROFILE_VOLUME="$profile_volume" start_provider_container \
+ "$name" "$image" "$config_path" "$fixtures_host" "$fixtures_port" "$root"
+ HOST_PORT="$(resolve_host_port "$name")"
+ echo " Container $name restarted — PinchTab on host port $HOST_PORT"
+
+ start_fixture_server "$name" "$fixtures_port"
+ wait_fixtures_ready "$name" "$fixtures_url" "$host_fixtures_url"
+
+ echo " Waiting for PinchTab health on :${HOST_PORT} (post stale-lock plant)..."
+ wait_for_health "$HOST_PORT" "$token"
+ echo " Waiting for managed ${provider} instance (post-recovery)..."
+ wait_for_instance_running "$HOST_PORT" "$token"
+
+ echo "→ Phase L5: re-read marker and assert it still matches seeded UUID"
+ local post_recovery_marker
+ post_recovery_marker="$(_read_marker_from_managed_instance "$HOST_PORT" "$token" "$fixtures_url")"
+ echo " post-recovery marker: $post_recovery_marker"
+ if [ "$seeded_marker" != "$post_recovery_marker" ]; then
+ fail "lock-recovery round-trip failed: seeded=${seeded_marker} post=${post_recovery_marker}"
+ fi
+ echo " marker survives stale-lock recovery — user state intact"
+
+ echo "→ Phase L6: assert all three singleton files cleared by recovery"
+ assert_lock_files_gone "$profile_volume" "$profile_subpath"
+ echo " recovery confirmed: SingletonLock/SingletonSocket/SingletonCookie removed"
+}
diff --git a/scripts/lib/smoke-scenarios.sh b/scripts/lib/smoke-scenarios.sh
new file mode 100644
index 00000000..539599ab
--- /dev/null
+++ b/scripts/lib/smoke-scenarios.sh
@@ -0,0 +1,65 @@
+# shellcheck shell=bash
+# Runs the API basic E2E suite inside a leg's container. Overrides via
+# PINCHTAB_PARITY_E2E_SCENARIOS (or PINCHTAB_CLOAKBROWSER_E2E_SCENARIOS on
+# the cloak leg, for backwards compat).
+# Requires globals: ROOT, RUNNER_IMAGE, TOKEN, FIXTURES_HOST, FIXTURES_URL.
+
+run_e2e_scenarios() {
+ local provider="$1"
+ local name="$2"
+
+ local -a default_scenarios=(
+ "actions-basic.sh"
+ "browser-basic.sh"
+ "clipboard-basic.sh"
+ "console-basic.sh"
+ "emulation-basic.sh"
+ "files-basic.sh"
+ "inspect-basic.sh"
+ "tabs-basic.sh"
+ )
+ local -a scenarios=()
+ local -a scenario_args=()
+
+ local override="${PINCHTAB_PARITY_E2E_SCENARIOS:-}"
+ if [ -z "$override" ] && [ "$provider" = "cloak" ]; then
+ override="${PINCHTAB_CLOAKBROWSER_E2E_SCENARIOS:-}"
+ fi
+
+ if [ -n "$override" ]; then
+ # shellcheck disable=SC2206
+ scenarios=($override)
+ else
+ scenarios=("${default_scenarios[@]}")
+ fi
+
+ for scenario in "${scenarios[@]}"; do
+ [ -n "$scenario" ] || continue
+ scenario_args+=("scenario=$scenario")
+ done
+
+ if [ "${#scenario_args[@]}" -eq 0 ]; then
+ echo "Skipping API E2E scenarios (empty scenario list for provider=${provider})."
+ return
+ fi
+
+ echo "Running API E2E scenarios against provider=${provider} in Docker:"
+ printf ' - %s\n' "${scenarios[@]}"
+
+ docker run --rm \
+ --network "container:${name}" \
+ -v "$ROOT/tests/e2e":/e2e:ro \
+ -e "FIXTURES_HOST=${FIXTURES_HOST}" \
+ -e "E2E_SERVER=http://127.0.0.1:9867" \
+ -e "E2E_SERVER_TOKEN=${TOKEN}" \
+ -e "FIXTURES_URL=${FIXTURES_URL}" \
+ -e "E2E_HELPER=api" \
+ -e "E2E_SCENARIO_DIR=scenarios/api" \
+ -e "E2E_REQUIRED_COMMANDS=curl jq" \
+ -e "E2E_READY_TARGETS=E2E_SERVER|60|E2E_SERVER_TOKEN" \
+ -e "E2E_SUMMARY_TITLE=Browser parity (${provider}) API E2E scenarios" \
+ "$RUNNER_IMAGE" \
+ /bin/sh -lc 'printf "127.0.0.1 %s\n" "$FIXTURES_HOST" >> /etc/hosts; exec /bin/bash /e2e/run.sh "$@"' \
+ _ "${scenario_args[@]}" \
+ || fail "API E2E scenarios failed for provider=${provider}"
+}
diff --git a/skills/pinchtab-todo/SKILL.md b/skills/pinchtab-todo/SKILL.md
new file mode 100644
index 00000000..40fb3f18
--- /dev/null
+++ b/skills/pinchtab-todo/SKILL.md
@@ -0,0 +1,142 @@
+---
+name: pinchtab-todo
+description: "Process the next task from the todo pipeline. Prepares or executes one task per cycle using todo.md (backlog) and todo-next.md (current task). Use when asked to 'run todo', 'process todo', 'next task', or 'work on the next todo'."
+---
+
+# PinchTab Todo Runner
+
+Two-phase pipeline: **prepare** a task (research + write up), then **execute** it next cycle. One action per invocation.
+
+## Path Resolution
+
+```bash
+PROJECT_ROOT=$(git rev-parse --show-toplevel)
+TODO_FILE="$PROJECT_ROOT/todo.md"
+TODO_NEXT="$PROJECT_ROOT/todo-next.md"
+```
+
+## Execution
+
+### 0. Ensure recurring schedule exists
+
+Before doing any work, check whether a schedule (routine) is already active for this skill:
+
+1. Use `CronList` to list existing routines.
+2. Look for one whose name or prompt references `pinchtab-todo`.
+3. **If a matching schedule exists** — continue to step 1.
+4. **If no matching schedule exists** — create one using `CronCreate` that runs every 30 minutes with the prompt `/pinchtab-todo`. Then continue to step 1.
+
+### 1. Check for `todo-next.md`
+
+- **If `todo-next.md` does NOT exist** → go to **Phase A** (prepare).
+- **If `todo-next.md` EXISTS** → go to **Phase B** (execute).
+
+---
+
+## Phase A — Prepare the next task
+
+Goal: pick the first incomplete task from `todo.md`, research it, and write a detailed `todo-next.md`. Do NOT implement anything.
+
+### A1. Read `todo.md`
+
+If the file does not exist, is empty, or every task is marked `[x]`, report that the backlog is clear and stop.
+
+### A2. Pick the first `- [ ]` task
+
+Take the first incomplete item from the list.
+
+### A3. Research the task
+
+Investigate the current codebase to understand:
+- What files/packages are involved
+- How similar features are implemented
+- What the right approach is
+- Any edge cases or risks
+
+### A4. Write `todo-next.md`
+
+Create `todo-next.md` with this structure:
+
+```markdown
+# <task title>
+
+> **Source:** `todo.md` line N
+> **Status:** ready
+
+## User Story
+
+As an [agent/user/developer], I want [what] so that [why].
+
+## TLDR
+
+One paragraph summary of what needs to happen and the approach.
+
+## Details
+
+- Files to change: ...
+- Approach: ...
+- Edge cases: ...
+- Tests needed: ...
+
+## Acceptance Criteria
+
+- [ ] Criterion 1
+- [ ] Criterion 2
+- [ ] `./dev all` passes
+```
+
+### A5. Stop
+
+Report that the next task has been prepared. Do not start implementation — that happens in Phase B on the next cycle.
+
+---
+
+## Phase B — Execute the current task
+
+Goal: implement the task described in `todo-next.md`, verify the build, then prepare the next one.
+
+### B1. Read `todo-next.md`
+
+Understand the task, user story, approach, and acceptance criteria.
+
+### B2. Implement the task
+
+Spawn a subagent to perform the work. Replace `{PROJECT_ROOT}` and `{TASK_DETAILS}` with actual values:
+
+```
+You are working on the PinchTab project at {PROJECT_ROOT}.
+
+Your task is described below:
+{TASK_DETAILS}
+
+Start by reading the development skill for context:
+1. Read `{PROJECT_ROOT}/skills/pinchtab-dev/SKILL.md` — dev commands, architecture, and workflow.
+2. Read `{PROJECT_ROOT}/skills/pinchtab/SKILL.md` — PinchTab command reference (if needed).
+
+Then implement the task following the approach and acceptance criteria.
+When done, report what you changed.
+```
+
+Wait for the subagent to complete and review its output.
+
+### B3. Verify the build
+
+```bash
+cd "$PROJECT_ROOT" && ./dev all
+```
+
+- **If `./dev all` passes**: continue to B4.
+- **If `./dev all` fails**: read the failure, fix the issues, re-run. Up to 3 attempts. If still failing after 3 attempts, report the failure and stop — leave `todo-next.md` in place for the next cycle.
+
+### B4. Mark done and clean up
+
+1. Mark the corresponding task as `[x]` in `todo.md`.
+2. Delete `todo-next.md`.
+
+### B5. Prepare the next task
+
+Now run **Phase A** (steps A1–A5) to prepare the next `todo-next.md` from the backlog. This way the next cycle can jump straight into execution.
+
+### B6. Stop
+
+Report what was completed and what was prepared for next cycle.
diff --git a/tests/e2e/README.md b/tests/e2e/README.md
index 6afc318f..cff88f22 100644
--- a/tests/e2e/README.md
+++ b/tests/e2e/README.md
@@ -10,8 +10,10 @@ End-to-end tests for PinchTab that exercise the full stack including browser aut
./dev e2e # Run the extended suite quietly by default
./dev e2e basic # Run the basic suite (api + cli + infra basic tests)
./dev e2e extended # Run the extended suite
-./dev e2e smoke # Run smoke scenarios plus host Docker smoke checks
-./dev smoke cloakbrowser # Run opt-in CloakBrowser Docker smoke image
+./dev smoke ci # Run the CI-backed smoke subset
+./dev smoke # Run all local smoke categories
+./dev smoke --provider=cloak # Run all local smoke categories for CloakBrowser
+./dev smoke cdp-attach # Run only the CDP attach smoke
./dev e2e api # Run API basic tests
./dev e2e cli # Run CLI basic tests
./dev e2e infra # Run infra basic tests
@@ -63,12 +65,12 @@ By default, tier comes from the filename suffix: `*-basic.sh` is `basic`, `*-smo
- `basic` is the PR happy path: fast, representative coverage with small setup. `./dev e2e basic` runs the API, CLI, and Infra basic suites.
- `extended` is deeper coverage: edge cases, detailed interaction checks, and tests that are useful before release. Extended suites include the matching `basic` scenarios plus `extended` scenarios for that group.
-- `smoke` is independent high-setup coverage: lifecycle, multi-instance, host Docker, and production-like checks that do not belong in PR flow. `./dev e2e smoke` runs only `*-smoke.sh` scenarios plus host Docker smoke checks; it does not include `basic` or `extended`.
+- `smoke` is independent high-setup coverage: lifecycle, multi-instance, host Docker, and production-like checks that do not belong in PR flow. `./dev smoke ci` runs only the CI-backed `*-smoke.sh` scenarios plus host Docker smoke checks; it does not include `basic`, `extended`, or opt-in provider/live-detection smokes. `./dev smoke` is the local full-smoke entrypoint and also runs provider parity, CDP attach, and live-detection categories unless filtered.
CloakBrowser smoke checks need a Linux CloakBrowser binary and a compatible
-PinchTab image, so they are exposed as the manual Docker smoke command
-`./dev smoke cloakbrowser` instead of being included in the CI-backed
-`./dev e2e smoke` suite. By default, the command builds
+PinchTab image, so they are exposed through local `./dev smoke` filters
+instead of being included in the CI-backed `./dev smoke ci` subset. The
+`./dev smoke cloakbrowser` filter builds
`tests/tools/docker/cloakbrowser-smoke.Dockerfile` into
`pinchtab-cloakbrowser:test` and uses tmpfs mounts for browser profile and
socket paths. The smoke reuses `tests/e2e/fixtures`, checks a representative
@@ -92,12 +94,17 @@ go run ./tests/tools/runner e2e --suite extended --filter feature --dry-run
go run ./tests/tools/runner e2e --suite smoke --filter feature --dry-run
```
-### Filtering
+ ### Filtering
`--filter TEXT` selects scenario files before compose planning. It is a case-sensitive substring match against the scenario file name, manifest key, group, tier, helper, and tags. Suites with no matching scenarios are skipped, and the runner only starts services required by the remaining scenarios.
For host Docker smoke checks, `--filter` matches the smoke step name or tags; required image build steps are included automatically when a filtered step depends on them.
+At the `./dev smoke` layer, positional names such as `cdp-attach`,
+`live-detection`, and `cloakbrowser` select those local smoke categories.
+Unknown names are passed to the CI-backed E2E smoke runner as `--filter`, so
+`./dev smoke orchestrator` maps to the orchestrator smoke scenario.
+
`--test TEXT` is different: it does not select scenario files or compose services. It passes `E2E_TEST_FILTER` into the container so `run.sh` can run one matching `start_test` block inside the already-selected scenarios.
### CI Path
diff --git a/tests/e2e/fixtures/persistence-marker.html b/tests/e2e/fixtures/persistence-marker.html
new file mode 100644
index 00000000..47ef6511
--- /dev/null
+++ b/tests/e2e/fixtures/persistence-marker.html
@@ -0,0 +1,83 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <title>Persistence Marker</title>
+</head>
+<body>
+ <!--
+ Deterministic profile-persistence probe used by the
+ docker-browser-parity-smoke `--profile-persistence` leg.
+
+ On load:
+ 1. Read localStorage['pinchtab-marker'] and the document cookie
+ `pinchtab-marker`.
+ 2. If either is missing, generate a UUID (crypto.randomUUID with a
+ non-crypto fallback for older Chromium builds) and write BOTH:
+ - localStorage['pinchtab-marker'] = <uuid>
+ - document.cookie = "pinchtab-marker=<uuid>; path=/; SameSite=Lax"
+ 3. Render the final value inside <div id="marker" role="status">.
+
+ Scope notes:
+ - localStorage and the cookie are tested across container restarts
+ (Docker named volume mounted at /data).
+ - sessionStorage is NOT persisted across restarts and is therefore
+ NOT exercised here — the page intentionally never touches it.
+ - No external resources, no async work; the rendered text is the
+ authoritative round-trip value.
+ -->
+ <h1>Persistence Marker</h1>
+ <div id="marker" role="status">pending</div>
+ <script>
+ (function () {
+ function readCookie(name) {
+ var parts = document.cookie ? document.cookie.split(';') : [];
+ for (var i = 0; i < parts.length; i++) {
+ var kv = parts[i].trim().split('=');
+ if (kv[0] === name) return kv.slice(1).join('=');
+ }
+ return '';
+ }
+
+ function makeUUID() {
+ if (window.crypto && typeof window.crypto.randomUUID === 'function') {
+ return window.crypto.randomUUID();
+ }
+ // Fallback (RFC4122 v4-ish; sufficient for a smoke marker).
+ var hex = '0123456789abcdef';
+ var out = '';
+ for (var i = 0; i < 32; i++) {
+ var r = Math.floor(Math.random() * 16);
+ if (i === 12) r = 4;
+ if (i === 16) r = (r & 0x3) | 0x8;
+ out += hex.charAt(r);
+ if (i === 7 || i === 11 || i === 15 || i === 19) out += '-';
+ }
+ return out;
+ }
+
+ var existingLS = '';
+ try { existingLS = window.localStorage.getItem('pinchtab-marker') || ''; }
+ catch (_) { existingLS = ''; }
+ var existingCK = readCookie('pinchtab-marker');
+
+ var value;
+ if (existingLS && existingCK && existingLS === existingCK) {
+ value = existingLS;
+ } else if (existingLS) {
+ value = existingLS;
+ } else if (existingCK) {
+ value = existingCK;
+ } else {
+ value = makeUUID();
+ }
+
+ try { window.localStorage.setItem('pinchtab-marker', value); }
+ catch (_) { /* localStorage may be unavailable; render anyway */ }
+ document.cookie = 'pinchtab-marker=' + value + '; path=/; SameSite=Lax';
+
+ document.getElementById('marker').textContent = value;
+ })();
+ </script>
+</body>
+</html>
diff --git a/tests/e2e/helpers/autosolver.sh b/tests/e2e/helpers/autosolver.sh
index 4db86694..69a797b4 100644
--- a/tests/e2e/helpers/autosolver.sh
+++ b/tests/e2e/helpers/autosolver.sh
@@ -132,6 +132,56 @@ assert_autosolver_score() {
fi
}
+assert_autosolver_score_allowing_failed_signals() {
+ local score_json="$1"
+ local details_json="$2"
+ local label="$3"
+ shift 3
+ local -a allowed=("$@")
+
+ local critical critical_total warnings warnings_total
+ critical=$(echo "$score_json" | jq -r '.critical // 0')
+ critical_total=$(echo "$score_json" | jq -r '.criticalTotal // 0')
+ warnings=$(echo "$score_json" | jq -r '.warnings // 0')
+ warnings_total=$(echo "$score_json" | jq -r '.warningsTotal // 0')
+ autosolver_log "$label" "score: critical=${critical}/${critical_total} warnings=${warnings}/${warnings_total} allowed-failures=${allowed[*]:-none}"
+
+ local unexpected="" allowed_seen="" signal permitted allowed_signal failed_count=0
+ while IFS= read -r signal; do
+ [ -n "$signal" ] || continue
+ failed_count=$((failed_count + 1))
+ permitted=0
+ for allowed_signal in "${allowed[@]}"; do
+ if [ "$signal" = "$allowed_signal" ]; then
+ permitted=1
+ break
+ fi
+ done
+ if [ "$permitted" -eq 1 ]; then
+ allowed_seen="${allowed_seen}${allowed_seen:+, }${signal}"
+ else
+ unexpected="${unexpected}${unexpected:+, }${signal}"
+ fi
+ done < <(echo "$details_json" | jq -r 'to_entries[] | select((.value.severity // "critical") == "critical" and ((.value.passed // false) | not)) | .key')
+
+ if [ "$critical" -lt "$critical_total" ] && [ "$failed_count" -eq 0 ]; then
+ fail_assert "[autosolver:${label}] failed but details did not identify critical signal(s)"
+ dump_autosolver_debug "$label"
+ return
+ fi
+
+ if [ -z "$unexpected" ]; then
+ if [ -n "$allowed_seen" ]; then
+ pass_assert "[autosolver:${label}] passed with provider-allowed signal gap(s): ${allowed_seen}"
+ else
+ pass_assert "[autosolver:${label}] passed (critical ${critical}/${critical_total})"
+ fi
+ else
+ fail_assert "[autosolver:${label}] failed unexpected critical signal(s): ${unexpected}"
+ dump_autosolver_debug "$label"
+ fi
+}
+
autosolver_null_result() {
[ "$AUTOSOLVER_RESULT" = "null" ] || [ -z "$AUTOSOLVER_RESULT" ]
}
@@ -183,6 +233,45 @@ autosolver_run_score_case() {
end_test
}
+autosolver_run_score_case_allowing_failures() {
+ local test_name="$1"
+ local label="$2"
+ local fixture="$3"
+ local score_expr="$4"
+ local details_expr="$5"
+ local allowed_csv="$6"
+ shift 6
+ local -a allowed_failures=()
+ IFS=',' read -r -a allowed_failures <<< "$allowed_csv"
+
+ start_test "$test_name"
+
+ if run_autosolver_and_extract "$label" "$fixture" "$score_expr" 1; then
+ if autosolver_null_result; then
+ fail_assert "[autosolver:${label}] score not populated"
+ echo -e " ${MUTED}page text: ${AUTOSOLVER_PAGE_TEXT:0:300}${NC}"
+ else
+ local score_json="$AUTOSOLVER_RESULT"
+ local details_json=""
+ if run_autosolver_and_extract "${label}-details" "$fixture" "$details_expr" 0; then
+ details_json="$AUTOSOLVER_RESULT"
+ fi
+ if autosolver_null_result || [ -z "$details_json" ]; then
+ fail_assert "[autosolver:${label}] details not populated"
+ else
+ assert_autosolver_score_allowing_failed_signals "$score_json" "$details_json" "$label" "${allowed_failures[@]}"
+ if [ "$#" -gt 0 ]; then
+ autosolver_log_signal_flags "$label" "$details_json" "$@"
+ fi
+ fi
+ fi
+ else
+ fail_assert "[autosolver:${label}] evaluation failed"
+ fi
+
+ end_test
+}
+
autosolver_title_has_challenge() {
local title_lower
title_lower=$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')
diff --git a/tests/e2e/helpers/base.sh b/tests/e2e/helpers/base.sh
index 8ef59dcd..91bc451a 100644
--- a/tests/e2e/helpers/base.sh
+++ b/tests/e2e/helpers/base.sh
@@ -146,6 +146,15 @@ skip_assert() {
((ASSERTIONS_SKIPPED++)) || true
}
+# skip_test marks the current test as skipped with a reason; it does not
+# increment failures. Must be paired with end_test as usual. The recorded
+# duration counts only the time up to the skip call.
+skip_test() {
+ local reason="${1:-skipped}"
+ echo -e " ${YELLOW}⚠ skipped:${NC} ${reason}"
+ ((ASSERTIONS_SKIPPED++)) || true
+}
+
soft_pass_assert() {
echo -e " ${YELLOW}~${NC} ${1:-}"
((ASSERTIONS_PASSED++)) || true
diff --git a/tests/e2e/scenarios/api/actions-basic.sh b/tests/e2e/scenarios/api/actions-basic.sh
index 43064fe7..f32bcd60 100644
--- a/tests/e2e/scenarios/api/actions-basic.sh
+++ b/tests/e2e/scenarios/api/actions-basic.sh
@@ -4,39 +4,95 @@
GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${GROUP_DIR}/../../helpers/api.sh"
+ACTIONS_TAB_ID=""
+
+actions_navigate() {
+ local url="$1"
+ local body
+ if [ -n "$ACTIONS_TAB_ID" ]; then
+ body=$(jq -nc --arg url "$url" --arg tabId "$ACTIONS_TAB_ID" '{url:$url, tabId:$tabId}')
+ else
+ body=$(jq -nc --arg url "$url" '{url:$url}')
+ fi
+
+ pt_post /navigate -d "$body"
+ assert_ok "navigate"
+
+ local tab_id
+ tab_id=$(echo "$RESULT" | jq -r '.tabId // empty')
+ if [ -n "$tab_id" ] && [ "$tab_id" != "null" ]; then
+ ACTIONS_TAB_ID="$tab_id"
+ fi
+}
+
+actions_snapshot() {
+ local query="${1:-}"
+ if [ -n "$query" ]; then
+ pt_get "/snapshot?tabId=${ACTIONS_TAB_ID}&${query}"
+ else
+ pt_get "/snapshot?tabId=${ACTIONS_TAB_ID}"
+ fi
+}
+
+actions_post_action() {
+ local body="$1"
+ local with_tab
+ with_tab=$(echo "$body" | jq -c --arg tabId "$ACTIONS_TAB_ID" '. + {tabId:$tabId}')
+ pt_post /action "$with_tab"
+}
+
+actions_evaluate() {
+ local expression="$1"
+ local body
+ body=$(jq -nc --arg tabId "$ACTIONS_TAB_ID" --arg expression "$expression" '{tabId:$tabId, expression:$expression}')
+ pt_post /evaluate "$body"
+}
+
# ─────────────────────────────────────────────────────────────────
start_test "pinchtab click <button>"
-pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/buttons.html\"}"
+actions_navigate "${FIXTURES_URL}/buttons.html"
-pt_get /snapshot
-click_button "Increment"
+actions_snapshot
+REF=$(find_ref_by_name "Increment")
+if assert_ref_found "$REF" "button Increment"; then
+ actions_post_action "{\"kind\":\"click\",\"ref\":\"${REF}\"}"
+ assert_ok "click button by ref"
+fi
end_test
# ─────────────────────────────────────────────────────────────────
start_test "pinchtab type <field> <text>"
-pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/form.html\"}"
+actions_navigate "${FIXTURES_URL}/form.html"
-pt_get /snapshot
-type_into "Username" "testuser123"
+actions_snapshot
+REF=$(find_ref_by_name "Username")
+if [ -z "$REF" ] || [ "$REF" = "null" ]; then
+ REF=$(find_ref_by_role "textbox")
+fi
+if assert_ref_found "$REF" "Username textbox"; then
+ actions_post_action "{\"kind\":\"type\",\"ref\":\"${REF}\",\"text\":\"testuser123\"}"
+ assert_ok "type text by ref"
+fi
end_test
# ─────────────────────────────────────────────────────────────────
start_test "pinchtab press <key>"
-press_key "Escape"
+actions_post_action '{"kind":"press","key":"Escape"}'
+assert_ok "press Escape"
end_test
# ─────────────────────────────────────────────────────────────────
start_test "pinchtab click (CSS selector)"
-pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/buttons.html\"}"
+actions_navigate "${FIXTURES_URL}/buttons.html"
-pt_post /action -d '{"kind":"click","selector":"#increment"}'
+actions_post_action '{"kind":"click","selector":"#increment"}'
assert_ok "click by selector"
end_test
@@ -44,9 +100,9 @@ end_test
# ─────────────────────────────────────────────────────────────────
start_test "pinchtab type (CSS selector)"
-pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/form.html\"}"
+actions_navigate "${FIXTURES_URL}/form.html"
-pt_post /action -d '{"kind":"type","selector":"#username","text":"selectortest"}'
+actions_post_action '{"kind":"type","selector":"#username","text":"selectortest"}'
assert_ok "type by selector"
end_test
@@ -54,9 +110,9 @@ end_test
# ─────────────────────────────────────────────────────────────────
start_test "pinchtab snapshot (CSS selector filter)"
-pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/form.html\"}"
+actions_navigate "${FIXTURES_URL}/form.html"
-pt_get "/snapshot?selector=#username"
+actions_snapshot "selector=%23username"
assert_ok "snapshot with selector"
end_test
@@ -64,10 +120,9 @@ end_test
# ─────────────────────────────────────────────────────────────────
start_test "pinchtab scroll (down)"
-pt_post /navigate "{\"url\":\"${FIXTURES_URL}/table.html\"}"
-assert_ok "navigate"
+actions_navigate "${FIXTURES_URL}/table.html"
-pt_post /action '{"kind":"scroll","direction":"down"}'
+actions_post_action '{"kind":"scroll","direction":"down"}'
assert_ok "scroll down"
end_test
@@ -75,71 +130,67 @@ end_test
# ─────────────────────────────────────────────────────────────────
start_test "pinchtab focus (ref)"
-pt_post /navigate "{\"url\":\"${FIXTURES_URL}/form.html\"}"
-assert_ok "navigate"
+actions_navigate "${FIXTURES_URL}/form.html"
-pt_get /snapshot
+actions_snapshot
REF=$(find_ref_by_role "textbox")
-assert_ref_found "$REF" "textbox ref"
-
-pt_post /action "{\"kind\":\"focus\",\"ref\":\"${REF}\"}"
-assert_ok "focus on input"
+if assert_ref_found "$REF" "textbox ref"; then
+ actions_post_action "{\"kind\":\"focus\",\"ref\":\"${REF}\"}"
+ assert_ok "focus on input"
+fi
end_test
# ─────────────────────────────────────────────────────────────────
start_test "pinchtab select (combobox)"
-pt_post /navigate "{\"url\":\"${FIXTURES_URL}/form.html\"}"
-assert_ok "navigate"
+actions_navigate "${FIXTURES_URL}/form.html"
-pt_get /snapshot
+actions_snapshot
REF=$(find_ref_by_role "combobox")
-assert_ref_found "$REF" "combobox ref"
-
-pt_post /action "{\"kind\":\"select\",\"ref\":\"${REF}\",\"value\":\"uk\"}"
-assert_ok "select option"
+if assert_ref_found "$REF" "combobox ref"; then
+ actions_post_action "{\"kind\":\"select\",\"ref\":\"${REF}\",\"value\":\"uk\"}"
+ assert_ok "select option"
+fi
end_test
# ─────────────────────────────────────────────────────────────────
start_test "pinchtab fill (sets value + verifiable)"
-pt_post /navigate "{\"url\":\"${FIXTURES_URL}/form.html\"}"
-assert_ok "navigate"
+actions_navigate "${FIXTURES_URL}/form.html"
-pt_get /snapshot
+actions_snapshot
REF=$(find_ref_by_role "textbox")
-assert_ref_found "$REF" "textbox ref"
-
-pt_post /action "{\"kind\":\"fill\",\"ref\":\"${REF}\",\"text\":\"e2e_fill_test\"}"
-assert_ok "fill input"
+if assert_ref_found "$REF" "textbox ref"; then
+ actions_post_action "{\"kind\":\"fill\",\"ref\":\"${REF}\",\"text\":\"e2e_fill_test\"}"
+ assert_ok "fill input"
-pt_post /evaluate '{"expression":"document.querySelector(\"#username\").value"}'
-assert_ok "evaluate"
-assert_json_contains "$RESULT" '.result' 'e2e_fill_test' "fill value persisted"
+ actions_evaluate 'document.querySelector("#username").value'
+ assert_ok "evaluate"
+ assert_json_contains "$RESULT" '.result' 'e2e_fill_test' "fill value persisted"
+fi
end_test
# ─────────────────────────────────────────────────────────────────
start_test "pinchtab check/uncheck (CSS selector)"
-pt_post /navigate "{\"url\":\"${FIXTURES_URL}/form.html\"}"
-assert_ok "navigate"
+actions_navigate "${FIXTURES_URL}/form.html"
-pt_post /action '{"kind":"check","selector":"#terms"}'
+actions_post_action '{"kind":"check","selector":"#terms"}'
assert_ok "check checkbox"
assert_json_eq "$RESULT" '.result.checked' 'true' "check response reports checked"
-pt_post /evaluate '{"expression":"document.querySelector(\"#terms\").checked"}'
+actions_evaluate 'document.querySelector("#terms").checked'
assert_ok "evaluate checked state"
assert_json_eq "$RESULT" '.result' 'true' "checkbox is checked in DOM"
-pt_post /action '{"kind":"uncheck","selector":"#terms"}'
+actions_post_action '{"kind":"uncheck","selector":"#terms"}'
assert_ok "uncheck checkbox"
assert_json_eq "$RESULT" '.result.checked' 'false' "uncheck response reports unchecked"
-pt_post /evaluate '{"expression":"document.querySelector(\"#terms\").checked"}'
+actions_evaluate 'document.querySelector("#terms").checked'
assert_ok "evaluate unchecked state"
assert_json_eq "$RESULT" '.result' 'false' "checkbox is unchecked in DOM"
diff --git a/tests/e2e/scenarios/api/screenshot-annotate-basic.sh b/tests/e2e/scenarios/api/screenshot-annotate-basic.sh
index 7f85b394..76cd0a01 100755
--- a/tests/e2e/scenarios/api/screenshot-annotate-basic.sh
+++ b/tests/e2e/scenarios/api/screenshot-annotate-basic.sh
@@ -29,7 +29,12 @@ end_test
# ─────────────────────────────────────────────────────────────────
start_test "screenshot annotate: annotation fields"
-# Re-use the form fixture from the previous step.
+# Load the fixture directly so this check is independent from the previous
+# annotated capture. Some browser providers can defer compositor work after a
+# capture; this test only owns the annotation-field contract.
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/form.html\"}"
+assert_ok "navigate to form fixture for field check"
+
pt_get "/screenshot?annotate=true&format=png"
assert_ok "annotated screenshot for field check"
diff --git a/tests/e2e/scenarios/cli/stealth-basic.sh b/tests/e2e/scenarios/cli/stealth-basic.sh
index e89749a3..1c91513f 100644
--- a/tests/e2e/scenarios/cli/stealth-basic.sh
+++ b/tests/e2e/scenarios/cli/stealth-basic.sh
@@ -42,7 +42,11 @@ end_test
start_test "bot-detect-cli: chrome.runtime exists"
pt_ok eval "!!(window.chrome && window.chrome.runtime)"
-assert_output_contains "true" "chrome.runtime"
+if [ "${PINCHTAB_E2E_PROVIDER:-chrome}" = "cloak" ]; then
+ assert_output_contains "false" "chrome.runtime stripped by cloak native stealth"
+else
+ assert_output_contains "true" "chrome.runtime"
+fi
end_test
diff --git a/tests/e2e/scenarios/infra/autosolver-smoke.sh b/tests/e2e/scenarios/infra/autosolver-smoke.sh
index 5a4abfad..ff648983 100644
--- a/tests/e2e/scenarios/infra/autosolver-smoke.sh
+++ b/tests/e2e/scenarios/infra/autosolver-smoke.sh
@@ -6,17 +6,34 @@ source "${GROUP_DIR}/../../helpers/autosolver.sh"
autosolver_use_medium_server
-autosolver_run_score_case \
- "autosolver: bot-detect baseline" \
- "bot-detect" \
- "bot-detect.html" \
- "JSON.stringify(window.__botDetectScore || null)" \
- "JSON.stringify(window.__botDetectResults || {})" \
- "webdriver_value" \
- "plugins_present" \
- "chrome_runtime" \
- "no_cdp_traces" \
- "ua_not_headless"
+if [ "${PINCHTAB_E2E_PROVIDER:-chrome}" = "cloak" ]; then
+ autosolver_run_score_case_allowing_failures \
+ "autosolver: bot-detect baseline" \
+ "bot-detect" \
+ "bot-detect.html" \
+ "JSON.stringify(window.__botDetectScore || null)" \
+ "JSON.stringify(window.__botDetectResults || {})" \
+ "chrome_runtime,useragentdata_exists,useragentdata_highentropy" \
+ "webdriver_value" \
+ "plugins_present" \
+ "chrome_runtime" \
+ "useragentdata_exists" \
+ "useragentdata_highentropy" \
+ "no_cdp_traces" \
+ "ua_not_headless"
+else
+ autosolver_run_score_case \
+ "autosolver: bot-detect baseline" \
+ "bot-detect" \
+ "bot-detect.html" \
+ "JSON.stringify(window.__botDetectScore || null)" \
+ "JSON.stringify(window.__botDetectResults || {})" \
+ "webdriver_value" \
+ "plugins_present" \
+ "chrome_runtime" \
+ "no_cdp_traces" \
+ "ua_not_headless"
+fi
autosolver_run_score_case \
"autosolver: cdp-detect baseline" \
diff --git a/tests/e2e/scenarios/infra/dashboard-smoke.sh b/tests/e2e/scenarios/infra/dashboard-smoke.sh
index 3b7f513c..835caa4c 100644
--- a/tests/e2e/scenarios/infra/dashboard-smoke.sh
+++ b/tests/e2e/scenarios/infra/dashboard-smoke.sh
@@ -42,13 +42,18 @@ dashboard_cleanup_screencast() {
}
dashboard_assert_instance_found() {
- pt_get /instances
- DASHBOARD_INST_ID=$(echo "$RESULT" | jq -r '.[0].id // empty')
+ pt_get "/instances/tabs?fresh=1"
+ assert_ok "list tabs for screencast proxy"
+ DASHBOARD_INST_ID=$(echo "$RESULT" | jq -r --arg tab "$DASHBOARD_TAB_ID" '.[] | select(.id == $tab) | .instanceId // empty' | head -n 1)
+ if [ -z "${DASHBOARD_INST_ID}" ]; then
+ DASHBOARD_INST_ID=$(echo "$RESULT" | jq -r '.[] | select((.url // "") | contains("evaluate.html")) | .instanceId // empty' | head -n 1)
+ fi
if [ -n "${DASHBOARD_INST_ID}" ]; then
- echo -e " ${GREEN}✓${NC} found instance for screencast proxy: ${DASHBOARD_INST_ID}"
+ echo -e " ${GREEN}✓${NC} found tab owner for screencast proxy: ${DASHBOARD_INST_ID}"
((ASSERTIONS_PASSED++)) || true
else
- echo -e " ${RED}✗${NC} could not find instance for screencast proxy"
+ echo -e " ${RED}✗${NC} could not find tab owner for screencast proxy"
+ echo "$RESULT" | jq '.' 2>/dev/null || echo "$RESULT"
((ASSERTIONS_FAILED++)) || true
fi
}
@@ -67,7 +72,7 @@ dashboard_start_screencast_stream() {
-H "Upgrade: websocket" \
-H "Sec-WebSocket-Version: 13" \
-H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
- --max-time 5 >/dev/null 2>&1 || true
+ --max-time 30 >/dev/null 2>&1 || true
) &
DASHBOARD_WS_PID=$!
diff --git a/tests/e2e/scenarios/infra/engine-modes-extended.sh b/tests/e2e/scenarios/infra/engine-modes-extended.sh
index e7b89cbd..dd5f4b46 100755
--- a/tests/e2e/scenarios/infra/engine-modes-extended.sh
+++ b/tests/e2e/scenarios/infra/engine-modes-extended.sh
@@ -217,7 +217,7 @@ end_test
# ─────────────────────────────────────────────────────────────────
start_test "safe-lite: redirects to internal targets are blocked"
-ATTACKER_URL="https://httpbin.org/redirect-to?url=http%3A%2F%2F169.254.169.254%2Flatest%2Fmeta-data%2F"
+ATTACKER_URL="${FIXTURES_URL}/redirect-to-internal"
lite_post /navigate "{\"url\":\"${ATTACKER_URL}\"}"
assert_http_status 403 "lite redirect to internal blocked"
assert_contains "$RESULT" "blocked\|private\|internal" "lite SSRF block message returned"
diff --git a/tests/e2e/scenarios/infra/idpi-extended.sh b/tests/e2e/scenarios/infra/idpi-extended.sh
index 87e06325..f6c4cf1f 100644
--- a/tests/e2e/scenarios/infra/idpi-extended.sh
+++ b/tests/e2e/scenarios/infra/idpi-extended.sh
@@ -38,9 +38,10 @@ start_test "idpi-off: hidden injection passes through without IDPI"
# Navigate to the hidden injection fixture (permissive server, IDPI warn only)
pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/idpi-hidden-injection.html\"}"
assert_ok "navigate to hidden injection page"
+TAB_ID=$(echo "$RESULT" | jq -r '.tabId // empty')
# Get snapshot — visible content should be present, IDPI warning should be set
-pt_get "/snapshot?format=json"
+pt_get "/snapshot?tabId=${TAB_ID}&format=json"
assert_ok "snapshot succeeds"
assert_contains "$RESULT" "Safe Button" "visible content present"
assert_contains "$RESULT" "Learn more" "normal link present"
diff --git a/tests/e2e/scenarios/infra/stealth-basic.sh b/tests/e2e/scenarios/infra/stealth-basic.sh
index 303a8b7c..d711be3a 100644
--- a/tests/e2e/scenarios/infra/stealth-basic.sh
+++ b/tests/e2e/scenarios/infra/stealth-basic.sh
@@ -13,20 +13,28 @@ assert_ok "navigate"
start_test "stealth: status endpoint available"
pt_get /stealth/status
-assert_json_eq "$RESULT" '.level' 'light' "default level is light"
-assert_json_exists "$RESULT" '.scriptHash' "status includes script hash"
-assert_json_eq "$RESULT" '.capabilities.webdriverNotTrue' 'true' "status reports webdriver-not-true capability"
-assert_json_eq "$RESULT" '.capabilities.webdriverNativeStrategy' 'true' "status reports native webdriver strategy"
-assert_json_eq "$RESULT" '.capabilities.downlinkMax' 'true' "status reports downlinkMax capability"
-assert_json_eq "$RESULT" '.flags.globalUserAgent' 'true' "status reports global launch UA is pinned (default headless config or custom UA)"
-assert_json_eq "$RESULT" '.flags.downlinkMaxFlag' 'true' "status reports downlinkMax launch flag"
-assert_json_eq "$RESULT" '.capabilities.iframeIsolation' 'false' "light status keeps iframe isolation disabled"
-assert_json_eq "$RESULT" '.capabilities.errorStackSanitized' 'false' "light status keeps stack sanitization disabled"
-assert_json_eq "$RESULT" '.capabilities.functionToStringMasked' 'false' "light status keeps toString masking disabled"
-assert_json_eq "$RESULT" '.capabilities.functionToStringNative' 'true' "light status keeps Function.prototype.toString native"
-assert_json_eq "$RESULT" '.capabilities.intlLocaleCoherent' 'true' "light status keeps Intl locale coherence"
-assert_json_eq "$RESULT" '.capabilities.errorPrepareStackTraceNative' 'true' "light status keeps Error.prepareStackTrace native"
-assert_json_eq "$RESULT" '.capabilities.navigatorOverridesAbsent' 'true' "light status avoids navigator own-property overrides"
+if [ "${PINCHTAB_E2E_PROVIDER:-chrome}" = "cloak" ]; then
+ assert_json_eq "$RESULT" '.provider' 'cloak' "status reports cloak provider"
+ assert_json_eq "$RESULT" '.native' 'true' "status reports cloak native stealth"
+ assert_json_eq "$RESULT" '.pinchtabOverlaysDisabled' 'true' "status reports PinchTab overlays disabled"
+ assert_json_eq "$RESULT" '.fingerprintSeed' '42069' "status reports cloak fingerprint seed"
+ assert_json_eq "$RESULT" '.level' 'light' "status reports light cloak level"
+else
+ assert_json_eq "$RESULT" '.level' 'light' "default level is light"
+ assert_json_exists "$RESULT" '.scriptHash' "status includes script hash"
+ assert_json_eq "$RESULT" '.capabilities.webdriverNotTrue' 'true' "status reports webdriver-not-true capability"
+ assert_json_eq "$RESULT" '.capabilities.webdriverNativeStrategy' 'true' "status reports native webdriver strategy"
+ assert_json_eq "$RESULT" '.capabilities.downlinkMax' 'true' "status reports downlinkMax capability"
+ assert_json_eq "$RESULT" '.flags.globalUserAgent' 'true' "status reports global launch UA is pinned (default headless config or custom UA)"
+ assert_json_eq "$RESULT" '.flags.downlinkMaxFlag' 'true' "status reports downlinkMax launch flag"
+ assert_json_eq "$RESULT" '.capabilities.iframeIsolation' 'false' "light status keeps iframe isolation disabled"
+ assert_json_eq "$RESULT" '.capabilities.errorStackSanitized' 'false' "light status keeps stack sanitization disabled"
+ assert_json_eq "$RESULT" '.capabilities.functionToStringMasked' 'false' "light status keeps toString masking disabled"
+ assert_json_eq "$RESULT" '.capabilities.functionToStringNative' 'true' "light status keeps Function.prototype.toString native"
+ assert_json_eq "$RESULT" '.capabilities.intlLocaleCoherent' 'true' "light status keeps Intl locale coherence"
+ assert_json_eq "$RESULT" '.capabilities.errorPrepareStackTraceNative' 'true' "light status keeps Error.prepareStackTrace native"
+ assert_json_eq "$RESULT" '.capabilities.navigatorOverridesAbsent' 'true' "light status avoids navigator own-property overrides"
+fi
end_test
@@ -47,7 +55,11 @@ end_test
# ─────────────────────────────────────────────────────────────────
start_test "stealth: chrome.runtime present"
-assert_eval_poll "!!window.chrome && !!window.chrome.runtime" "true" "window.chrome.runtime present"
+if [ "${PINCHTAB_E2E_PROVIDER:-chrome}" = "cloak" ]; then
+ assert_eval_poll "!!(window.chrome && window.chrome.runtime)" "false" "chrome.runtime stripped by cloak native stealth"
+else
+ assert_eval_poll "!!window.chrome && !!window.chrome.runtime" "true" "window.chrome.runtime present"
+fi
end_test
@@ -182,7 +194,11 @@ end_test
start_test "bot-detect: chrome.runtime present"
-assert_eval_poll "!!(window.chrome && window.chrome.runtime)" "true" "chrome.runtime exists"
+if [ "${PINCHTAB_E2E_PROVIDER:-chrome}" = "cloak" ]; then
+ assert_eval_poll "!!(window.chrome && window.chrome.runtime)" "false" "chrome.runtime stripped by cloak native stealth"
+else
+ assert_eval_poll "!!(window.chrome && window.chrome.runtime)" "true" "chrome.runtime exists"
+fi
end_test
@@ -220,7 +236,11 @@ end_test
start_test "bot-detect: battery API exists"
-assert_eval_poll "typeof navigator.getBattery === 'function'" "true" "getBattery exists"
+if [ "${PINCHTAB_E2E_PROVIDER:-chrome}" = "cloak" ]; then
+ assert_eval_poll "typeof navigator.getBattery === 'undefined'" "true" "battery API absent under cloak"
+else
+ assert_eval_poll "typeof navigator.getBattery === 'function'" "true" "getBattery exists"
+fi
end_test
@@ -239,7 +259,11 @@ end_test
start_test "stealth-capabilities: outer dimensions available"
-assert_eval_poll "window.__stealthCapabilities.outerDimensions" "true" "outer dimensions exist"
+if [ "${PINCHTAB_E2E_PROVIDER:-chrome}" = "cloak" ]; then
+ assert_eval_poll "window.outerWidth === 0 && window.outerHeight === 0" "true" "cloak zeroes outer dimensions"
+else
+ assert_eval_poll "window.__stealthCapabilities.outerDimensions" "true" "outer dimensions exist"
+fi
end_test
@@ -258,13 +282,24 @@ end_test
start_test "stealth-capabilities: battery API reported"
-assert_eval_poll "window.__stealthCapabilities.batteryApi" "true" "battery API reported by capability fixture"
+if [ "${PINCHTAB_E2E_PROVIDER:-chrome}" = "cloak" ]; then
+ assert_eval_poll "typeof navigator.getBattery === 'undefined'" "true" "battery API absent under cloak"
+else
+ assert_eval_poll "window.__stealthCapabilities.batteryApi" "true" "battery API reported by capability fixture"
+fi
end_test
start_test "stealth-capabilities: downlinkMax reported"
-assert_eval_poll "window.__stealthCapabilities.downlinkMaxPresent" "true" "downlinkMax reported by capability fixture"
+if [ "${PINCHTAB_E2E_PROVIDER:-chrome}" = "cloak" ]; then
+ # Cloak's native stealth removes downlinkMax from the NetworkInformation
+ # interface (own and prototype) — verify it stays absent so PinchTab's
+ # overlay is not silently re-adding it.
+ assert_eval_poll "window.__stealthCapabilities.downlinkMaxPresent" "false" "downlinkMax absent under cloak native stealth"
+else
+ assert_eval_poll "window.__stealthCapabilities.downlinkMaxPresent" "true" "downlinkMax reported by capability fixture"
+fi
end_test
diff --git a/tests/e2e/scenarios/infra/stealth-extended.sh b/tests/e2e/scenarios/infra/stealth-extended.sh
index 9b06f5be..a601e800 100644
--- a/tests/e2e/scenarios/infra/stealth-extended.sh
+++ b/tests/e2e/scenarios/infra/stealth-extended.sh
@@ -428,8 +428,13 @@ end_test
start_test "bot-detect-full: outer window dimensions exist"
-pt_post /evaluate '{"expression":"window.outerWidth > 0 && window.outerHeight > 0"}'
-assert_json_eq "$RESULT" '.result' 'true' "outerWidth/outerHeight > 0"
+if [ "${PINCHTAB_E2E_PROVIDER:-chrome}" = "cloak" ]; then
+ pt_post /evaluate '{"expression":"window.outerWidth === 0 && window.outerHeight === 0"}'
+ assert_json_eq "$RESULT" '.result' 'true' "cloak zeroes outerWidth/outerHeight"
+else
+ pt_post /evaluate '{"expression":"window.outerWidth > 0 && window.outerHeight > 0"}'
+ assert_json_eq "$RESULT" '.result' 'true' "outerWidth/outerHeight > 0"
+fi
end_test
@@ -527,19 +532,23 @@ if [ -n "$FULL_URL" ]; then
start_test "bot-detect-full: permissive full score check"
- pt_post /evaluate '{"expression":"JSON.stringify(window.__botDetectScore || {})"}'
- score_json=$(echo "$RESULT" | jq -r '.result // "{}"')
- critical_passed=$(echo "$score_json" | jq -r '.critical // 0')
- critical_total=$(echo "$score_json" | jq -r '.criticalTotal // 0')
+ if [ "${PINCHTAB_E2E_PROVIDER:-chrome}" = "cloak" ]; then
+ skip_test "cloak removes surfaces this composite score rewards (chrome.runtime/battery/outer dims)"
+ else
+ pt_post /evaluate '{"expression":"JSON.stringify(window.__botDetectScore || {})"}'
+ score_json=$(echo "$RESULT" | jq -r '.result // "{}"')
+ critical_passed=$(echo "$score_json" | jq -r '.critical // 0')
+ critical_total=$(echo "$score_json" | jq -r '.criticalTotal // 0')
- echo -e " ${MUTED}Score: critical ${critical_passed}/${critical_total} (full)${NC}"
+ echo -e " ${MUTED}Score: critical ${critical_passed}/${critical_total} (full)${NC}"
- if [ "$critical_passed" -ge "$critical_total" ]; then
- echo -e " ${GREEN}✓${NC} score meets full expectations"
- ((ASSERTIONS_PASSED++)) || true
- else
- echo -e " ${RED}✗${NC} score below full expectations (${critical_passed}/${critical_total})"
- ((ASSERTIONS_FAILED++)) || true
+ if [ "$critical_passed" -ge "$critical_total" ]; then
+ echo -e " ${GREEN}✓${NC} score meets full expectations"
+ ((ASSERTIONS_PASSED++)) || true
+ else
+ echo -e " ${RED}✗${NC} score below full expectations (${critical_passed}/${critical_total})"
+ ((ASSERTIONS_FAILED++)) || true
+ fi
fi
end_test
diff --git a/tests/e2e/scenarios/infra/system-basic.sh b/tests/e2e/scenarios/infra/system-basic.sh
index e55606ca..99a6ddb6 100644
--- a/tests/e2e/scenarios/infra/system-basic.sh
+++ b/tests/e2e/scenarios/infra/system-basic.sh
@@ -33,40 +33,44 @@ end_test
start_test "config: fingerprint rotation preserves Chrome version"
-pt_post /navigate "{\"url\":\"${FIXTURES_URL}/index.html\"}"
-assert_ok "navigate"
-TAB_ID=$(echo "$RESULT" | jq -r '.tabId')
-
-pt_post /evaluate "{\"tabId\":\"$TAB_ID\",\"expression\":\"navigator.userAgent\"}"
-assert_ok "initial UA"
-INITIAL_UA=$(echo "$RESULT" | jq -r '.result')
-INITIAL_VERSION=$(echo "$INITIAL_UA" | grep -oE 'Chrome/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | head -1)
-
-if [ -z "$INITIAL_VERSION" ]; then
- echo -e " ${RED}✗${NC} initial UA missing Chrome version"
- ((ASSERTIONS_FAILED++)) || true
+if [ "${PINCHTAB_E2E_PROVIDER:-chrome}" = "cloak" ]; then
+ skip_test "fingerprint rotation is a PinchTab-overlay feature; cloak owns its own fingerprint engine"
else
- echo -e " ${GREEN}✓${NC} initial version: $INITIAL_VERSION"
- ((ASSERTIONS_PASSED++)) || true
-fi
+ pt_post /navigate "{\"url\":\"${FIXTURES_URL}/index.html\"}"
+ assert_ok "navigate"
+ TAB_ID=$(echo "$RESULT" | jq -r '.tabId')
+
+ pt_post /evaluate "{\"tabId\":\"$TAB_ID\",\"expression\":\"navigator.userAgent\"}"
+ assert_ok "initial UA"
+ INITIAL_UA=$(echo "$RESULT" | jq -r '.result')
+ INITIAL_VERSION=$(echo "$INITIAL_UA" | grep -oE 'Chrome/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | head -1)
+
+ if [ -z "$INITIAL_VERSION" ]; then
+ echo -e " ${RED}✗${NC} initial UA missing Chrome version"
+ ((ASSERTIONS_FAILED++)) || true
+ else
+ echo -e " ${GREEN}✓${NC} initial version: $INITIAL_VERSION"
+ ((ASSERTIONS_PASSED++)) || true
+ fi
-pt_post /fingerprint/rotate "{\"os\":\"mac\",\"tabId\":\"$TAB_ID\"}"
-assert_ok "fingerprint rotate"
+ pt_post /fingerprint/rotate "{\"os\":\"mac\",\"tabId\":\"$TAB_ID\"}"
+ assert_ok "fingerprint rotate"
-pt_post /evaluate "{\"tabId\":\"$TAB_ID\",\"expression\":\"navigator.userAgent\"}"
-assert_ok "rotated UA"
-ROTATED_UA=$(echo "$RESULT" | jq -r '.result')
-ROTATED_VERSION=$(echo "$ROTATED_UA" | grep -oE 'Chrome/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | head -1)
+ pt_post /evaluate "{\"tabId\":\"$TAB_ID\",\"expression\":\"navigator.userAgent\"}"
+ assert_ok "rotated UA"
+ ROTATED_UA=$(echo "$RESULT" | jq -r '.result')
+ ROTATED_VERSION=$(echo "$ROTATED_UA" | grep -oE 'Chrome/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | head -1)
-if [ "$INITIAL_VERSION" = "$ROTATED_VERSION" ]; then
- echo -e " ${GREEN}✓${NC} Chrome version preserved after rotation: $ROTATED_VERSION"
- ((ASSERTIONS_PASSED++)) || true
-else
- echo -e " ${RED}✗${NC} Chrome version changed: $INITIAL_VERSION → $ROTATED_VERSION"
- ((ASSERTIONS_FAILED++)) || true
-fi
+ if [ "$INITIAL_VERSION" = "$ROTATED_VERSION" ]; then
+ echo -e " ${GREEN}✓${NC} Chrome version preserved after rotation: $ROTATED_VERSION"
+ ((ASSERTIONS_PASSED++)) || true
+ else
+ echo -e " ${RED}✗${NC} Chrome version changed: $INITIAL_VERSION → $ROTATED_VERSION"
+ ((ASSERTIONS_FAILED++)) || true
+ fi
-pt_post /close "{\"tabId\":\"$TAB_ID\"}" >/dev/null 2>&1
+ pt_post /close "{\"tabId\":\"$TAB_ID\"}" >/dev/null 2>&1
+fi
end_test
diff --git a/tests/tools/docker/chrome-smoke.Dockerfile b/tests/tools/docker/chrome-smoke.Dockerfile
new file mode 100644
index 00000000..8d280d3d
--- /dev/null
+++ b/tests/tools/docker/chrome-smoke.Dockerfile
@@ -0,0 +1,19 @@
+# Local-only Chrome smoke image for the browser parity harness.
+#
+# Extends the standard PinchTab image with the helper utilities required by
+# the in-container fixture server (perl) and HTTP probes (curl). These are
+# intentionally NOT in the default runtime image because they are only needed
+# by the opt-in parity smoke.
+#
+# Usage:
+# docker build -f tests/tools/docker/chrome-smoke.Dockerfile \
+# -t pinchtab-chrome-smoke:test .
+#
+# Built automatically by scripts/docker-browser-parity-smoke.sh.
+
+ARG BASE_IMAGE=pinchtab-local:test
+FROM ${BASE_IMAGE}
+
+USER root
+RUN apk add --no-cache perl curl
+USER pinchtab
diff --git a/tests/tools/docker/cloakbrowser-smoke.Dockerfile b/tests/tools/docker/cloakbrowser-smoke.Dockerfile
index b425a2b2..c168f783 100644
--- a/tests/tools/docker/cloakbrowser-smoke.Dockerfile
+++ b/tests/tools/docker/cloakbrowser-smoke.Dockerfile
@@ -63,6 +63,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
fonts-liberation \
fonts-noto-color-emoji \
procps \
+ socat \
&& rm -rf /var/lib/apt/lists/*
# Non-root user; /data is the persistent volume mount point.
diff --git a/tests/tools/fixtures/static-server.pl b/tests/tools/fixtures/static-server.pl
index 3f1115c1..100a8354 100644
--- a/tests/tools/fixtures/static-server.pl
+++ b/tests/tools/fixtures/static-server.pl
@@ -2,6 +2,7 @@
use strict;
use warnings;
use IO::Socket::INET;
+use POSIX ":sys_wait_h";
my $root = $ENV{FIXTURES_ROOT} || '/fixtures';
my $port = $ENV{FIXTURES_PORT} || 8080;
@@ -9,14 +10,56 @@ my $port = $ENV{FIXTURES_PORT} || 8080;
my $server = IO::Socket::INET->new(
LocalAddr => '0.0.0.0',
LocalPort => $port,
- Listen => 20,
+ Listen => 64,
ReuseAddr => 1,
) or die "listen on $port: $!";
$| = 1;
print "fixture server listening on $port\n";
-while (my $client = $server->accept) {
+# Reap forked children eagerly so they don't pile up as zombies. POSIX::SIGCHLD
+# is delivered to the parent after fork; the default Perl handler does not
+# auto-restart syscalls, so accept() can return undef with $!=EINTR and our
+# loop would exit. Use a sigaction with SA_RESTART semantics by setting the
+# handler before the loop and explicitly retrying accept on EINTR below.
+$SIG{CHLD} = sub { local ($!, $?); while (waitpid(-1, WNOHANG) > 0) {} };
+$SIG{PIPE} = 'IGNORE';
+
+use Errno qw(EINTR);
+
+while (1) {
+ my $client = $server->accept;
+ if (!$client) {
+ next if $!{EINTR};
+ last;
+ }
+ # Fork per connection so a slow/half-open client cannot block the loop.
+ # The parent goes back to accept(); the child handles this one request
+ # with a per-client wall-clock timeout via alarm().
+ my $pid = fork();
+ if (!defined $pid) {
+ # fork() failed — handle in-process so the connection isn't dropped.
+ handle_client($client);
+ next;
+ }
+ if ($pid) {
+ # Parent: close our copy of the client socket and accept more.
+ close $client;
+ next;
+ }
+ # Child:
+ close $server;
+ eval {
+ local $SIG{ALRM} = sub { die "client_timeout\n" };
+ alarm(10);
+ handle_client($client);
+ alarm(0);
+ };
+ exit 0;
+}
+
+sub handle_client {
+ my ($client) = @_;
$client->autoflush(1);
my $request = <$client> || '';
while (my $header = <$client>) {
@@ -25,7 +68,7 @@ while (my $client = $server->accept) {
if ($request !~ m{^GET\s+([^ ]+)\s+HTTP/}i) {
respond($client, 405, 'text/plain; charset=utf-8', 'method not allowed');
- next;
+ return;
}
my $path = $1;
@@ -35,25 +78,25 @@ while (my $client = $server->accept) {
if ($path eq '/redirect-to-internal') {
redirect($client, 'http://127.0.0.1:9999/health');
- next;
+ return;
}
if ($path =~ /\0/ || $path =~ m{(^|/)\.\.(/|\z)}) {
respond($client, 403, 'text/plain; charset=utf-8', 'forbidden');
- next;
+ return;
}
$path =~ s{^/+}{};
my $file = "$root/$path";
if (!-f $file) {
respond($client, 404, 'text/plain; charset=utf-8', 'not found');
- next;
+ return;
}
my $fh;
if (!open $fh, '<:raw', $file) {
respond($client, 500, 'text/plain; charset=utf-8', 'open failed');
- next;
+ return;
}
local $/;
my $body = <$fh>;
diff --git a/tests/tools/runner/internal/e2e/e2e.go b/tests/tools/runner/internal/e2e/e2e.go
index af88f5a3..28126deb 100644
--- a/tests/tools/runner/internal/e2e/e2e.go
+++ b/tests/tools/runner/internal/e2e/e2e.go
@@ -10,12 +10,13 @@ import (
)
type Args struct {
- Suite string
- Filter string
- Test string
- Extra string
- Logs string
- DryRun bool
+ Suite string
+ Filter string
+ Test string
+ Extra string
+ Logs string
+ Provider string
+ DryRun bool
}
var errHelp = errors.New("help requested")
@@ -29,12 +30,15 @@ const usageText = `Usage:
Options:
--suite basic|extended|smoke|api|cli|infra|plugin|api-extended|cli-extended|infra-extended
smoke-orchestrator|smoke-security|smoke-lifecycle
- --filter TEXT Filter scenario file names, groups, tiers, helpers, or tags
- --test TEXT Run one start_test block by name
- --extra FILES Add extra scenario files, space-separated
- --logs show|hide Control compose build/runner output
- --dry-run Print the compose plan without running it
- --help, -h Show this help
+ --filter TEXT Filter scenario file names, groups, tiers, helpers, or tags
+ --test TEXT Run one start_test block by name
+ --extra FILES Add extra scenario files, space-separated
+ --logs show|hide Control compose build/runner output
+ --provider chrome|cloak
+ Select browser provider (default: chrome). Cloak requires
+ the prebuilt pinchtab-cloakbrowser:test image.
+ --dry-run Print the compose plan without running it
+ --help, -h Show this help
`
func Run(argv []string, stdout, stderr io.Writer) int {
@@ -70,6 +74,14 @@ func ParseArgs(argv []string) (Args, error) {
for i := 0; i < len(argv); i++ {
arg := argv[i]
+ // Normalize --flag=value into --flag value so each case below
+ // keeps a single shape.
+ if idx := strings.Index(arg, "="); idx > 2 && strings.HasPrefix(arg, "--") {
+ value := arg[idx+1:]
+ arg = arg[:idx]
+ argv = append(argv[:i+1], append([]string{value}, argv[i+1:]...)...)
+ argv[i] = arg
+ }
switch arg {
case "--help", "-h":
return args, errHelp
@@ -103,6 +115,12 @@ func ParseArgs(argv []string) (Args, error) {
return args, err
}
args.Logs = v
+ case "--provider":
+ v, err := next(&i, arg)
+ if err != nil {
+ return args, err
+ }
+ args.Provider = v
case "--dry-run":
args.DryRun = true
default:
@@ -121,6 +139,14 @@ func ParseArgs(argv []string) (Args, error) {
return args, fmt.Errorf("--logs must be show or hide")
}
}
+ if args.Provider == "" {
+ args.Provider = "chrome"
+ }
+ switch args.Provider {
+ case "chrome", "cloak":
+ default:
+ return args, fmt.Errorf("--provider must be chrome or cloak (got %q)", args.Provider)
+ }
return args, nil
}
diff --git a/tests/tools/runner/internal/e2e/e2e_test.go b/tests/tools/runner/internal/e2e/e2e_test.go
index dfe08c56..5d9b6f70 100644
--- a/tests/tools/runner/internal/e2e/e2e_test.go
+++ b/tests/tools/runner/internal/e2e/e2e_test.go
@@ -588,6 +588,66 @@ exit 23
}
}
+func TestBringUpSharedStackCloakBuildsSupportImagesOnly(t *testing.T) {
+ var stdout, stderr bytes.Buffer
+ r := &Runner{
+ args: Args{DryRun: true},
+ stdout: &stdout,
+ stderr: &stderr,
+ compose: []string{"docker", "compose"},
+ logsMode: "hide",
+ overrides: &providerOverrides{
+ provider: "cloak",
+ composeFiles: []string{"/tmp/docker-compose.cloak.yml"},
+ },
+ }
+
+ if code := r.bringUpSharedStack("compose.yml", []string{"pinchtab", "fixtures"}); code != 0 {
+ t.Fatalf("bringUpSharedStack returned %d, stderr: %s", code, stderr.String())
+ }
+
+ out := stdout.String()
+ for _, want := range []string{
+ "docker compose -f compose.yml -f /tmp/docker-compose.cloak.yml build fixtures runner-api runner-cli",
+ "docker compose -f compose.yml -f /tmp/docker-compose.cloak.yml up -d --no-build pinchtab fixtures",
+ } {
+ if !strings.Contains(out, want) {
+ t.Fatalf("dry-run output missing %q:\n%s", want, out)
+ }
+ }
+ for _, line := range strings.Split(out, "\n") {
+ if strings.Contains(line, " build ") && strings.Contains(line, " pinchtab") {
+ t.Fatalf("cloak provider must not rebuild pinchtab services:\n%s", out)
+ }
+ }
+}
+
+func TestDryRunCloakProviderDoesNotRequireImage(t *testing.T) {
+ t.Setenv("E2E_LOGS", "")
+ var stdout, stderr bytes.Buffer
+
+ code := Run([]string{"--suite", "api", "--provider", "cloak", "--dry-run"}, &stdout, &stderr)
+ if code != 0 {
+ t.Fatalf("Run returned %d, stderr: %s", code, stderr.String())
+ }
+
+ out := stdout.String()
+ quotedOverride := "'" + dryRunCloakComposeOverride + "'"
+ for _, want := range []string{
+ "provider: cloak",
+ "docker compose -f tests/e2e/docker-compose.yml -f " + quotedOverride + " build fixtures runner-api runner-cli",
+ "docker compose -f tests/e2e/docker-compose.yml -f " + quotedOverride + " up -d --no-build pinchtab fixtures",
+ "PINCHTAB_E2E_PROVIDER=cloak",
+ } {
+ if !strings.Contains(out, want) {
+ t.Fatalf("dry-run output missing %q:\n%s", want, out)
+ }
+ }
+ if strings.Contains(stderr.String(), "image not found") {
+ t.Fatalf("dry-run should not inspect the cloak image, stderr:\n%s", stderr.String())
+ }
+}
+
func TestStructuredEventTeeFiltersHumanOutputOnly(t *testing.T) {
var human, log bytes.Buffer
tee := &structuredEventTee{human: &human, log: &log}
diff --git a/tests/tools/runner/internal/e2e/provider.go b/tests/tools/runner/internal/e2e/provider.go
new file mode 100644
index 00000000..fd2c9988
--- /dev/null
+++ b/tests/tools/runner/internal/e2e/provider.go
@@ -0,0 +1,367 @@
+package e2e
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "time"
+)
+
+// cloakImage is the prebuilt image the cloak provider expects to find locally.
+// It is built by tests/tools/docker/cloakbrowser-smoke.Dockerfile and is
+// intentionally never auto-built by the e2e runner — it is too heavy and the
+// Cloak binary license requires explicit opt-in.
+const cloakImage = "pinchtab-cloakbrowser:test"
+const dryRunCloakComposeOverride = "<generated-cloak-compose-override>"
+
+// pinchtabServices enumerates every pinchtab variant present in the e2e
+// compose files. Anything not listed here is left untouched by the cloak
+// override (notably the runner-* services and fixtures).
+var pinchtabServices = []string{
+ "pinchtab",
+ "pinchtab-secure",
+ "pinchtab-autoclose",
+ "pinchtab-medium",
+ "pinchtab-full",
+ "pinchtab-lite",
+ "pinchtab-bridge",
+}
+
+// providerOverrides bundles the override compose file + any generated cloak
+// configs the runner mounts in place of the chrome configs.
+type providerOverrides struct {
+ provider string
+ tmpDir string
+ composeFiles []string
+}
+
+// preparePoviderOverrides creates a temp directory with cloak-flavoured copies
+// of every tests/e2e/config/*.json the suite mounts, plus a compose override
+// file that swaps each pinchtab service's image and config bind mount.
+//
+// For provider=chrome it is a no-op and returns nil; the runner runs the suite
+// byte-identical to today.
+func (r *Runner) prepareProviderOverrides() (*providerOverrides, error) {
+ if r.args.Provider == "" || r.args.Provider == "chrome" {
+ return nil, nil
+ }
+ if r.args.Provider != "cloak" {
+ return nil, fmt.Errorf("unsupported provider: %s", r.args.Provider)
+ }
+
+ if r.args.DryRun {
+ return &providerOverrides{
+ provider: "cloak",
+ composeFiles: []string{dryRunCloakComposeOverride},
+ }, nil
+ }
+
+ if err := assertCloakImagePresent(); err != nil {
+ return nil, err
+ }
+
+ tmp, err := os.MkdirTemp("", "pinchtab-e2e-cloak-*")
+ if err != nil {
+ return nil, fmt.Errorf("create cloak tmp dir: %w", err)
+ }
+
+ configDir := filepath.Join(r.repoRoot, "tests/e2e/config")
+ entries, err := os.ReadDir(configDir)
+ if err != nil {
+ _ = os.RemoveAll(tmp)
+ return nil, fmt.Errorf("read e2e config dir: %w", err)
+ }
+
+ cloakConfigs := map[string]string{}
+ for _, entry := range entries {
+ name := entry.Name()
+ if entry.IsDir() || !strings.HasSuffix(name, ".json") {
+ continue
+ }
+ src := filepath.Join(configDir, name)
+ dst := filepath.Join(tmp, name)
+ if err := writeCloakConfig(src, dst); err != nil {
+ _ = os.RemoveAll(tmp)
+ return nil, fmt.Errorf("rewrite config %s: %w", name, err)
+ }
+ cloakConfigs[name] = dst
+ }
+
+ overridePath := filepath.Join(tmp, "docker-compose.cloak.yml")
+ fixturesDir := filepath.Join(r.repoRoot, "tests/e2e/fixtures")
+ if err := writeCloakComposeOverride(overridePath, cloakConfigs, fixturesDir); err != nil {
+ _ = os.RemoveAll(tmp)
+ return nil, fmt.Errorf("write cloak compose override: %w", err)
+ }
+
+ return &providerOverrides{
+ provider: "cloak",
+ tmpDir: tmp,
+ composeFiles: []string{overridePath},
+ }, nil
+}
+
+func (o *providerOverrides) cleanup() {
+ if o == nil || o.tmpDir == "" {
+ return
+ }
+ _ = os.RemoveAll(o.tmpDir)
+}
+
+func assertCloakImagePresent() error {
+ cmd := exec.Command("docker", "image", "inspect", cloakImage)
+ cmd.Stdout = nil
+ cmd.Stderr = nil
+ if err := cmd.Run(); err != nil {
+ return fmt.Errorf(
+ "%s image not found; build via tests/tools/docker/cloakbrowser-smoke.Dockerfile or `./dev smoke cloakbrowser` first",
+ cloakImage,
+ )
+ }
+ return nil
+}
+
+// writeCloakConfig reads a chrome-flavoured pinchtab config and writes a
+// cloak-flavoured copy: it preserves every other field and injects the
+// browser.provider + browser.binary + browser.cloak block. The fingerprint
+// seed mirrors scripts/lib/smoke-config.sh for consistency.
+func writeCloakConfig(src, dst string) error {
+ raw, err := os.ReadFile(src) // #nosec G304 -- src is constrained to tests/e2e/config/*.json.
+ if err != nil {
+ return err
+ }
+ var cfg map[string]any
+ if err := json.Unmarshal(raw, &cfg); err != nil {
+ return fmt.Errorf("parse: %w", err)
+ }
+
+ browser, _ := cfg["browser"].(map[string]any)
+ if browser == nil {
+ browser = map[string]any{}
+ }
+ browser["provider"] = "cloak"
+ browser["binary"] = "/opt/cloakbrowser/chrome"
+ browser["cloak"] = map[string]any{
+ "fingerprintSeed": "42069",
+ "platform": "linux",
+ "locale": "en-US",
+ "timezone": "UTC",
+ "disableDefaultStealthArgs": true,
+ }
+ cfg["browser"] = browser
+
+ out, err := json.MarshalIndent(cfg, "", " ")
+ if err != nil {
+ return fmt.Errorf("marshal: %w", err)
+ }
+ return os.WriteFile(dst, append(out, '\n'), 0o644) // #nosec G306 -- read-only config fixture.
+}
+
+// writeCloakComposeOverride writes a compose file that targets each pinchtab
+// service: swaps the image to the prebuilt cloak image, drops the build
+// directive (via image-only + pull_policy:never), remaps the config bind mount
+// onto the cloak-flavoured copy we just generated, and preserves extension
+// fixture mounts needed by extension-parity E2E tests.
+//
+// The override is intentionally written as YAML by hand (no third-party deps)
+// since the structure is small and stable.
+func writeCloakComposeOverride(path string, cloakConfigs map[string]string, fixturesDir string) error {
+ type extensionMount struct {
+ sourceDir string
+ target string
+ }
+ type serviceOverrideConfig struct {
+ configName string
+ extensionMounts []extensionMount
+ }
+
+ // Map service name to original config basename and extension bind mounts.
+ // The config bind-mount target inside the container is
+ // /fixture-config/<basename>:ro, which the entrypoint command copies into
+ // /data/e2e-config/<basename>.
+ serviceConfig := map[string]serviceOverrideConfig{
+ "pinchtab": {
+ configName: "pinchtab.json",
+ extensionMounts: []extensionMount{
+ {sourceDir: "test-extension", target: "/extensions/test-extension"},
+ {sourceDir: "test-extension-api", target: "/extensions/test-extension-api"},
+ },
+ },
+ "pinchtab-secure": {
+ configName: "pinchtab-secure.json",
+ },
+ "pinchtab-autoclose": {
+ configName: "pinchtab-autoclose.json",
+ extensionMounts: []extensionMount{
+ {sourceDir: "test-extension", target: "/extensions/test-extension"},
+ },
+ },
+ "pinchtab-medium": {
+ configName: "pinchtab-medium-permissive.json",
+ extensionMounts: []extensionMount{
+ {sourceDir: "test-extension", target: "/extensions/test-extension"},
+ },
+ },
+ "pinchtab-full": {
+ configName: "pinchtab-full-permissive.json",
+ extensionMounts: []extensionMount{
+ {sourceDir: "test-extension", target: "/extensions/test-extension"},
+ },
+ },
+ "pinchtab-lite": {
+ configName: "pinchtab-lite.json",
+ },
+ "pinchtab-bridge": {
+ configName: "pinchtab-bridge.json",
+ },
+ }
+
+ var b strings.Builder
+ b.WriteString("# Generated by tests/tools/runner — provider=cloak override.\n")
+ b.WriteString("# Swaps every pinchtab* service onto the prebuilt cloak image and\n")
+ b.WriteString("# mounts the cloak-flavoured runtime config in place of the chrome one.\n")
+ b.WriteString("services:\n")
+
+ for _, svc := range pinchtabServices {
+ cfg, ok := serviceConfig[svc]
+ if !ok {
+ continue
+ }
+ baseName := cfg.configName
+ cloakPath, ok := cloakConfigs[baseName]
+ if !ok {
+ // No config generated (probably renamed); skip silently — the
+ // service will fail at startup and surface a clear error.
+ continue
+ }
+ fmt.Fprintf(&b, " %s:\n", svc)
+ fmt.Fprintf(&b, " image: %s\n", cloakImage)
+ fmt.Fprintf(&b, " pull_policy: never\n")
+ // Keep the override self-contained: every provider=cloak service gets
+ // the rewritten config plus the same extension fixtures its Chrome
+ // counterpart exposes in the base compose files.
+ b.WriteString(" volumes:\n")
+ fmt.Fprintf(&b, " - %s:/fixture-config/%s:ro\n", cloakPath, baseName)
+ for _, mount := range cfg.extensionMounts {
+ source := filepath.Join(fixturesDir, mount.sourceDir)
+ fmt.Fprintf(&b, " - %s:%s:ro\n", source, mount.target)
+ }
+ }
+
+ return os.WriteFile(path, []byte(b.String()), 0o644) // #nosec G306 -- consumed read-only by docker compose.
+}
+
+// assertStealthStatus runs the one-shot pre-suite check against the running
+// PinchTab container. We hit /stealth/status on the host-exposed port (9999)
+// with the well-known e2e token; for cloak we assert the full claim set; for
+// chrome we sanity-check the provider field only.
+func (r *Runner) assertStealthStatus(composeFile string) error {
+ if r.args.DryRun {
+ return nil
+ }
+ host, port, err := r.resolvePinchtabHostPort(composeFile)
+ if err != nil {
+ return err
+ }
+ url := fmt.Sprintf("http://%s:%s/stealth/status", host, port)
+ req, err := http.NewRequest(http.MethodGet, url, nil)
+ if err != nil {
+ return fmt.Errorf("build stealth status request: %w", err)
+ }
+ req.Header.Set("Authorization", "Bearer e2e-token")
+
+ client := &http.Client{Timeout: 15 * time.Second}
+
+ var resp *http.Response
+ deadline := time.Now().Add(45 * time.Second)
+ for {
+ resp, err = client.Do(req)
+ if err == nil && resp.StatusCode == http.StatusOK {
+ break
+ }
+ if resp != nil {
+ _ = resp.Body.Close()
+ }
+ if time.Now().After(deadline) {
+ if err != nil {
+ return fmt.Errorf("stealth status check failed: %w", err)
+ }
+ return fmt.Errorf("stealth status check returned %d", resp.StatusCode)
+ }
+ time.Sleep(500 * time.Millisecond)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var status map[string]any
+ if err := json.NewDecoder(resp.Body).Decode(&status); err != nil {
+ return fmt.Errorf("decode stealth status: %w", err)
+ }
+
+ provider, _ := status["provider"].(string)
+
+ switch r.args.Provider {
+ case "cloak":
+ native, _ := status["native"].(bool)
+ overlays, _ := status["pinchtabOverlaysDisabled"].(bool)
+ seed, _ := status["fingerprintSeed"].(string)
+ if provider != "cloak" || !native || !overlays || seed != "42069" {
+ return fmt.Errorf(
+ "cloak stealth assertion failed (want provider=cloak, native=true, pinchtabOverlaysDisabled=true, fingerprintSeed=42069); got: %s",
+ formatStealthStatus(status),
+ )
+ }
+ _, _ = fmt.Fprintf(
+ r.stdout,
+ " /stealth/status: provider=cloak native=true overlaysDisabled=true seed=%s\n",
+ seed,
+ )
+ default:
+ // chrome — sanity check only.
+ if provider != "chrome" {
+ return fmt.Errorf("chrome stealth assertion failed (want provider=chrome); got: %s", formatStealthStatus(status))
+ }
+ _, _ = fmt.Fprintln(r.stdout, " /stealth/status: provider=chrome")
+ }
+ return nil
+}
+
+func formatStealthStatus(status map[string]any) string {
+ pretty, err := json.MarshalIndent(status, " ", " ")
+ if err != nil {
+ return fmt.Sprintf("%v", status)
+ }
+ return string(pretty)
+}
+
+// resolvePinchtabHostPort returns the host-side bind address+port that maps to
+// the `pinchtab` service inside the compose project. We prefer the published
+// fixed port (9999 in both compose files) but fall back to `compose port` for
+// resilience against ephemeral port mappings.
+func (r *Runner) resolvePinchtabHostPort(composeFile string) (string, string, error) {
+ args := r.composeArgs(composeFile, "port", "pinchtab", "9999")
+ cmd := exec.Command(args[0], args[1:]...) // #nosec G204 -- compose args are runner-controlled.
+ cmd.Dir = r.repoRoot
+ out, err := cmd.Output()
+ if err != nil {
+ return "127.0.0.1", "9999", nil
+ }
+ line := strings.TrimSpace(string(out))
+ if line == "" {
+ return "127.0.0.1", "9999", nil
+ }
+ // `compose port` prints e.g. "0.0.0.0:9999" — split on last colon.
+ idx := strings.LastIndex(line, ":")
+ if idx <= 0 || idx == len(line)-1 {
+ return "127.0.0.1", "9999", nil
+ }
+ host := line[:idx]
+ port := line[idx+1:]
+ if host == "0.0.0.0" || host == "::" {
+ host = "127.0.0.1"
+ }
+ return host, port, nil
+}
diff --git a/tests/tools/runner/internal/e2e/provider_test.go b/tests/tools/runner/internal/e2e/provider_test.go
new file mode 100644
index 00000000..335fddc2
--- /dev/null
+++ b/tests/tools/runner/internal/e2e/provider_test.go
@@ -0,0 +1,135 @@
+package e2e
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestWriteCloakComposeOverrideMountsExtensionFixtures(t *testing.T) {
+ tmp := t.TempDir()
+ fixturesDir := filepath.Join(tmp, "fixtures")
+ outPath := filepath.Join(tmp, "docker-compose.cloak.yml")
+
+ configs := map[string]string{
+ "pinchtab.json": filepath.Join(tmp, "pinchtab.json"),
+ "pinchtab-secure.json": filepath.Join(tmp, "pinchtab-secure.json"),
+ "pinchtab-autoclose.json": filepath.Join(tmp, "pinchtab-autoclose.json"),
+ "pinchtab-medium-permissive.json": filepath.Join(tmp, "pinchtab-medium-permissive.json"),
+ "pinchtab-full-permissive.json": filepath.Join(tmp, "pinchtab-full-permissive.json"),
+ "pinchtab-lite.json": filepath.Join(tmp, "pinchtab-lite.json"),
+ "pinchtab-bridge.json": filepath.Join(tmp, "pinchtab-bridge.json"),
+ }
+
+ if err := writeCloakComposeOverride(outPath, configs, fixturesDir); err != nil {
+ t.Fatal(err)
+ }
+
+ raw, err := os.ReadFile(outPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ compose := string(raw)
+
+ for _, svc := range []string{"pinchtab", "pinchtab-autoclose", "pinchtab-medium", "pinchtab-full"} {
+ block := serviceBlock(t, compose, svc)
+ want := filepath.Join(fixturesDir, "test-extension") + ":/extensions/test-extension:ro"
+ if !strings.Contains(block, want) {
+ t.Fatalf("%s override missing extension mount %q:\n%s", svc, want, block)
+ }
+ }
+
+ pinchtabBlock := serviceBlock(t, compose, "pinchtab")
+ wantAPIExtension := filepath.Join(fixturesDir, "test-extension-api") + ":/extensions/test-extension-api:ro"
+ if !strings.Contains(pinchtabBlock, wantAPIExtension) {
+ t.Fatalf("pinchtab override missing extension API mount %q:\n%s", wantAPIExtension, pinchtabBlock)
+ }
+
+ for _, svc := range []string{"pinchtab-secure", "pinchtab-lite", "pinchtab-bridge"} {
+ block := serviceBlock(t, compose, svc)
+ if strings.Contains(block, "/extensions/test-extension") {
+ t.Fatalf("%s override should not add extension mounts:\n%s", svc, block)
+ }
+ }
+
+ for svc, configName := range map[string]string{
+ "pinchtab": "pinchtab.json",
+ "pinchtab-secure": "pinchtab-secure.json",
+ "pinchtab-autoclose": "pinchtab-autoclose.json",
+ "pinchtab-medium": "pinchtab-medium-permissive.json",
+ "pinchtab-full": "pinchtab-full-permissive.json",
+ "pinchtab-lite": "pinchtab-lite.json",
+ "pinchtab-bridge": "pinchtab-bridge.json",
+ } {
+ block := serviceBlock(t, compose, svc)
+ want := configs[configName] + ":/fixture-config/" + configName + ":ro"
+ if !strings.Contains(block, want) {
+ t.Fatalf("%s override missing cloak config mount %q:\n%s", svc, want, block)
+ }
+ if !strings.Contains(block, "image: "+cloakImage) {
+ t.Fatalf("%s override missing cloak image:\n%s", svc, block)
+ }
+ if !strings.Contains(block, "pull_policy: never") {
+ t.Fatalf("%s override missing pull_policy: never:\n%s", svc, block)
+ }
+ }
+}
+
+func TestWriteCloakConfigPreservesExtensionPaths(t *testing.T) {
+ tmp := t.TempDir()
+ src := filepath.Join(tmp, "pinchtab.json")
+ dst := filepath.Join(tmp, "pinchtab.cloak.json")
+
+ input := `{
+ "browser": {
+ "extensionPaths": ["/extensions/test-extension"]
+ },
+ "security": {
+ "allowedDomains": ["fixtures"]
+ }
+}`
+ if err := os.WriteFile(src, []byte(input), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := writeCloakConfig(src, dst); err != nil {
+ t.Fatal(err)
+ }
+
+ raw, err := os.ReadFile(dst)
+ if err != nil {
+ t.Fatal(err)
+ }
+ out := string(raw)
+ for _, want := range []string{
+ `"provider": "cloak"`,
+ `"binary": "/opt/cloakbrowser/chrome"`,
+ `"extensionPaths": [`,
+ `"/extensions/test-extension"`,
+ `"allowedDomains": [`,
+ `"fixtures"`,
+ } {
+ if !strings.Contains(out, want) {
+ t.Fatalf("cloak config missing %q:\n%s", want, out)
+ }
+ }
+}
+
+func serviceBlock(t *testing.T, compose, service string) string {
+ t.Helper()
+
+ marker := " " + service + ":\n"
+ start := strings.Index(compose, marker)
+ if start < 0 {
+ t.Fatalf("service %s not found in compose:\n%s", service, compose)
+ }
+ var lines []string
+ for _, line := range strings.Split(compose[start+len(marker):], "\n") {
+ if strings.HasPrefix(line, " ") && !strings.HasPrefix(line, " ") {
+ break
+ }
+ lines = append(lines, line)
+ }
+ return strings.Join(lines, "\n")
+}
diff --git a/tests/tools/runner/internal/e2e/runner.go b/tests/tools/runner/internal/e2e/runner.go
index ad574e80..248a4ab3 100644
--- a/tests/tools/runner/internal/e2e/runner.go
+++ b/tests/tools/runner/internal/e2e/runner.go
@@ -21,14 +21,15 @@ const (
)
type Runner struct {
- args Args
- suite string
- stdout io.Writer
- stderr io.Writer
- repoRoot string
- compose []string
- logsMode string
- overall overallReportData
+ args Args
+ suite string
+ stdout io.Writer
+ stderr io.Writer
+ repoRoot string
+ compose []string
+ logsMode string
+ overall overallReportData
+ overrides *providerOverrides
}
type overallReportData struct {
@@ -111,6 +112,16 @@ func NewRunner(args Args, stdout, stderr io.Writer) (*Runner, error) {
func (r *Runner) Run() int {
started := time.Now()
+ overrides, err := r.prepareProviderOverrides()
+ if err != nil {
+ _, _ = fmt.Fprintf(r.stderr, "e2e: %v\n", err)
+ return 1
+ }
+ r.overrides = overrides
+ if overrides != nil {
+ defer overrides.cleanup()
+ _, _ = fmt.Fprintf(r.stdout, " provider: %s (image: %s)\n", overrides.provider, cloakImage)
+ }
code := r.run()
duration := time.Since(started)
r.printOverallSummary(duration)
@@ -553,15 +564,38 @@ func (r *Runner) planSuites(defs []suiteDef) ([]suitePlan, int) {
}
func (r *Runner) bringUpSharedStack(composeFile string, services []string) int {
- if code := r.buildSharedStack(composeFile); code != 0 {
+ // Cloak runs against a prebuilt image (pinchtab-cloakbrowser:test) that
+ // must NOT be rebuilt by this lane. We still build support images such as
+ // fixtures and runners so clean workstations do not depend on stale local
+ // images.
+ skipPinchtabBuild := r.overrides != nil && r.overrides.provider == "cloak"
+ if skipPinchtabBuild {
+ if code := r.buildSharedStack(composeFile, cloakSupportBuildServices()...); code != 0 {
+ return code
+ }
+ } else {
+ if code := r.buildSharedStack(composeFile); code != 0 {
+ return code
+ }
+ }
+ args := []string{"up", "-d"}
+ if skipPinchtabBuild {
+ args = append(args, "--no-build")
+ }
+ args = append(args, services...)
+ if code := r.runLoggedCommand("starting shared stack", stackOutput, r.composeArgs(composeFile, args...)); code != 0 {
return code
}
- args := append([]string{"up", "-d"}, services...)
- return r.runLoggedCommand("starting shared stack", stackOutput, r.composeArgs(composeFile, args...))
+ if err := r.assertStealthStatus(composeFile); err != nil {
+ _, _ = fmt.Fprintf(r.stderr, "e2e: pre-suite stealth assertion failed: %v\n", err)
+ return 1
+ }
+ return 0
}
-func (r *Runner) buildSharedStack(composeFile string) int {
- code := r.runLoggedCommand("building shared-stack images", stackOutput, r.composeArgs(composeFile, "build"))
+func (r *Runner) buildSharedStack(composeFile string, services ...string) int {
+ args := append([]string{"build"}, services...)
+ code := r.runLoggedCommand("building shared-stack images", stackOutput, r.composeArgs(composeFile, args...))
if code == 0 {
return 0
}
@@ -569,7 +603,12 @@ func (r *Runner) buildSharedStack(composeFile string) int {
return code
}
_, _ = fmt.Fprintln(r.stdout, " build cache looked stale; retrying shared-stack build with --no-cache...")
- return r.runLoggedCommand("rebuilding shared-stack images without cache", stackOutput, r.composeArgs(composeFile, "build", "--no-cache"))
+ retryArgs := append([]string{"build", "--no-cache"}, services...)
+ return r.runLoggedCommand("rebuilding shared-stack images without cache", stackOutput, r.composeArgs(composeFile, retryArgs...))
+}
+
+func cloakSupportBuildServices() []string {
+ return []string{"fixtures", "runner-api", "runner-cli"}
}
func (r *Runner) stackOutputHasBuildKitCacheFailure() bool {
@@ -608,6 +647,10 @@ func (r *Runner) suiteRunCommand(composeFile string, def suiteDef, scenarios []s
}
func (r *Runner) suiteEnvironment(def suiteDef, scenarios []scenarioMeta) []string {
+ provider := r.args.Provider
+ if provider == "" {
+ provider = "chrome"
+ }
return []string{
"E2E_HELPER=" + def.Helper,
"E2E_SCENARIO_DIR=" + def.ScenarioDir,
@@ -615,6 +658,7 @@ func (r *Runner) suiteEnvironment(def suiteDef, scenarios []scenarioMeta) []stri
"E2E_READY_TARGETS=" + strings.Join(readyTargetsForScenarios(def, scenarios), " "),
"E2E_TEST_FILTER=" + r.args.Test,
"E2E_SUMMARY_TITLE=" + suiteReportTitle(def),
+ "PINCHTAB_E2E_PROVIDER=" + provider,
}
}
@@ -642,6 +686,11 @@ func suiteReportTitle(def suiteDef) string {
func (r *Runner) composeArgs(composeFile string, args ...string) []string {
out := append([]string{}, r.compose...)
out = append(out, "-f", composeFile)
+ if r.overrides != nil {
+ for _, override := range r.overrides.composeFiles {
+ out = append(out, "-f", override)
+ }
+ }
out = append(out, args...)
return out
}