High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: enforce attach allowlist on legacy CDP path and split runtime init
Bosch2501e0781318
diff --git a/internal/bridge/runtime/cdp_url_test.go b/internal/bridge/runtime/cdp_url_test.goindex af348057..2193fbf0 100644--- a/internal/bridge/runtime/cdp_url_test.go+++ b/internal/bridge/runtime/cdp_url_test.go@@ -3,12 +3,16 @@ package runtimeimport ("context""fmt"+ "net""net/http""net/http/httptest""net/netip""net/url""strings""testing"+ "time"++ "github.com/pinchtab/pinchtab/internal/config")func TestNormalizeCDPURL_BrowserWebSocket(t *testing.T) {@@ -262,3 +266,57 @@ func TestNormalizeResolvedDevToolsURL_RejectsAllowlistedDifferentHost(t *testingt.Fatalf("unexpected error: %v", err)}}++func stubCDPResolver(t *testing.T, fn func(ctx context.Context, network, host string) ([]net.IP, error)) {+ t.Helper()+ old := cdpResolveHostIPs+ cdpResolveHostIPs = fn+ t.Cleanup(func() { cdpResolveHostIPs = old })+}++// H9 regression: an allowlisted DNS hostname must pass the connectivity+// probe's allowlist check. Normalization pins the URL host to the resolved+// IP, and probing that rewritten URL re-validated the bare IP against the+// hostname allowlist — which can never match. The dial here still fails (no+// live endpoint), but the failure must be a connectivity error, not the+// pre-fix "add it to security.attach.allowHosts" rejection.+func TestInitRemoteCDP_AllowlistedHostnamePassesProbeAllowlist(t *testing.T) {+ stubCDPResolver(t, func(_ context.Context, _, host string) ([]net.IP, error) {+ if host == "browsers.corp" {+ return []net.IP{net.ParseIP("203.0.113.10")}, nil+ }+ return nil, fmt.Errorf("unexpected host %q", host)+ })++ cfg := &config.RuntimeConfig{+ AttachAllowHosts: []string{"browsers.corp"},+ AttachAllowSchemes: []string{"ws"},+ }+ ctx, cancel := context.WithTimeout(context.Background(), 1500*time.Millisecond)+ defer cancel()+ _, _, _, _, _, err := InitRemoteCDP(ctx, cfg, "ws://browsers.corp:9222/devtools/browser/abc")+ if err == nil {+ t.Fatal("expected connectivity failure against unreachable endpoint")+ }+ if strings.Contains(err.Error(), "allowHosts") {+ t.Fatalf("allowlisted hostname rejected by the probe's allowlist re-check: %v", err)+ }+}++func TestInitRemoteCDP_NonAllowlistedHostnameStillRejected(t *testing.T) {+ stubCDPResolver(t, func(_ context.Context, _, host string) ([]net.IP, error) {+ return []net.IP{net.ParseIP("203.0.113.11")}, nil+ })++ cfg := &config.RuntimeConfig{+ AttachAllowHosts: []string{"browsers.corp"},+ AttachAllowSchemes: []string{"ws"},+ }+ _, _, _, _, _, err := InitRemoteCDP(context.Background(), cfg, "ws://evil.corp:9222/devtools/browser/abc")+ if err == nil {+ t.Fatal("expected non-allowlisted hostname to be rejected")+ }+ if !strings.Contains(err.Error(), "allowHosts") {+ t.Fatalf("expected allowlist rejection from normalization, got: %v", err)+ }+}diff --git a/internal/bridge/runtime/init.go b/internal/bridge/runtime/init.goindex 1135316b..b241aa27 100644--- a/internal/bridge/runtime/init.go+++ b/internal/bridge/runtime/init.go@@ -1,13 +1,9 @@package runtimeimport (- "bytes""context"- "crypto/rand""fmt"- "io""log/slog"- "math/big""os""os/exec"goruntime "runtime"@@ -93,56 +89,19 @@ func InitBrowser(cfg *config.RuntimeConfig, bundle *stealth.Bundle, hooks Hooks)return nil, nil, nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to start browser: %w", err)}- if proxyAuthEnabled(cfg.Proxy) {- if err := enableProxyAuth(browserCtx, cfg.Proxy); err != nil {+ if ProxyAuthEnabled(cfg.Proxy) {+ if err := EnableProxyAuth(browserCtx, cfg.Proxy, nil); err != nil {browserCancel()allocCancel()return nil, nil, nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to enable proxy auth: %w", err)}+ slog.Info("proxy authentication enabled via CDP", "proxy", cfg.Proxy.Redacted())}slog.Info("browser initialized successfully", "headless", cfg.Headless, "profile", cfg.ProfileDir)return allocCtx, allocCancel, browserCtx, browserCancel, launchMode, nil}-// initBrowserFromExistingCDP attaches the bridge to a browser that is already-// running outside pinchtab (e.g. the user's everyday browser launched with-// --remote-debugging-port=NNNN). No process is spawned and no profile lock-// is taken. The allocator is a chromedp remote allocator; the returned-// cancel funcs release only the chromedp side, never the external browser.-func initBrowserFromExistingCDP(cfg *config.RuntimeConfig, bundle *stealth.Bundle) (context.Context, context.CancelFunc, context.Context, context.CancelFunc, stealth.LaunchMode, error) {- browserID, _ := config.ParseBrowser(cfg.DefaultBrowser, cfg.BrowsersAvailable)- if browserID == "" {- browserID = config.NormalizeBrowser(cfg.DefaultBrowser)- }- if b, ok := browsers.Get(browserID); ok && !b.SupportsRemoteCDP() {- return nil, nil, nil, nil, stealth.LaunchModeUninitialized,- fmt.Errorf("provider %q does not support remote CDP attach", browserID)- }-- wsURL := strings.TrimSpace(cfg.CDPAttachURL)- slog.Info("attaching to existing browser via CDP", "cdpUrl", wsURL)-- remoteAllocCtx, remoteAllocCancel := chromedp.NewRemoteAllocator(context.Background(), wsURL)- browserCtx, browserCancel := chromedp.NewContext(remoteAllocCtx)-- // Touch the browser so we fail fast if the CDP URL is unreachable. We- // intentionally do NOT inject the stealth/UA script here — the user's- // browser is theirs, and rewriting its launch contract would be both- // surprising and likely break extensions, profile features, and- // already-open tabs.- if err := chromedp.Run(browserCtx, chromedp.ActionFunc(func(ctx context.Context) error {- return nil- })); err != nil {- browserCancel()- remoteAllocCancel()- return nil, nil, nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to attach to CDP at %s: %w", wsURL, err)- }-- slog.Info("attached to existing browser via CDP", "cdpUrl", wsURL)- return remoteAllocCtx, remoteAllocCancel, browserCtx, browserCancel, stealth.LaunchModeAttached, nil-}-// FindBrowserBinary exposes the launch-time browser discovery used by runtime// initialization so diagnostics can report against the same search path.func FindBrowserBinary() string {@@ -173,14 +132,6 @@ func resolveProviderLaunchPlan(cfg *config.RuntimeConfig, launchCfg browsers.Lau}, nil}-func appendExecAllocatorFlag(opts []chromedp.ExecAllocatorOption, flag string) []chromedp.ExecAllocatorOption {- name := strings.TrimPrefix(flag, "--")- if parts := strings.SplitN(name, "=", 2); len(parts) == 2 {- return append(opts, chromedp.Flag(parts[0], parts[1]))- }- return append(opts, chromedp.Flag(name, true))-}-func ensureStealthBundle(cfg *config.RuntimeConfig, bundle *stealth.Bundle) *stealth.Bundle {if bundle != nil {return bundle@@ -188,13 +139,6 @@ func ensureStealthBundle(cfg *config.RuntimeConfig, bundle *stealth.Bundle) *stereturn stealth.NewBundle(cfg, cryptoRandSeed())}-func appendExecAllocatorFlags(opts []chromedp.ExecAllocatorOption, flags []string) []chromedp.ExecAllocatorOption {- for _, flag := range flags {- opts = appendExecAllocatorFlag(opts, flag)- }- return opts-}-func setupAllocator(cfg *config.RuntimeConfig, bundle *stealth.Bundle, hooks Hooks, geoAlignment launchGeoAlignment) (context.Context, context.CancelFunc, []chromedp.ExecAllocatorOption, int, error) {opts := []chromedp.ExecAllocatorOption{chromedp.NoFirstRun,@@ -210,13 +154,22 @@ func setupAllocator(cfg *config.RuntimeConfig, bundle *stealth.Bundle, hooks Hooif binary == "" {binary = runtimekit.FindBrowserBinary(config.NormalizeBrowser(cfg.DefaultBrowser))}- plan, err := resolveProviderLaunchPlan(cfg, runtimekit.LaunchConfigFromRuntime(cfg, binary, debugPort, launchNeedsNoSandbox()))+ launchCfg := runtimekit.LaunchConfigFromRuntime(cfg, binary, debugPort, launchNeedsNoSandbox())+ // setupAllocator appends user extra flags itself (below), where the+ // DisableInProcessGPU kill switch can strip them; the plan must not+ // re-inject a second, unstrippable copy.+ launchCfg.ExtraFlags = nil+ plan, err := resolveProviderLaunchPlan(cfg, launchCfg)if err != nil {return nil, nil, nil, 0, err}opts = appendExecAllocatorFlags(opts, plan.args)opts = appendExecAllocatorFlags(opts, bundle.Launch.Args)- opts = appendExecAllocatorFlags(opts, config.BrowserProxyFlags(cfg.Proxy))+ proxyFlags, err := config.BrowserProxyFlags(cfg.Proxy)+ if err != nil {+ return nil, nil, nil, 0, err+ }+ opts = appendExecAllocatorFlags(opts, proxyFlags)opts = appendExecAllocatorFlags(opts, geoAlignment.flags)if plan.binary != "" {@@ -305,79 +258,6 @@ func setupAllocator(cfg *config.RuntimeConfig, bundle *stealth.Bundle, hooks Hooreturn ctx, cancel, opts, debugPort, nil}-func browserLaunchArgs(headless bool) []string {- return runtimekit.BaseFlagArgs("chrome", headless)-}--func BaseBrowserFlagArgs() []string {- return browserLaunchArgs(false)-}--func appendBrowserCompatibilityFlags(args []string) []string {- if launchNeedsNoSandbox() {- return append(args, "--no-sandbox")- }- return args-}--func launchNeedsNoSandbox() bool {- _, err := os.Stat(containerMarkerPath)- return runtimekit.ChromeNeedsNoSandbox(runtimeGOOS, osGeteuid(), err == nil)-}--func BuildBrowserArgs(cfg *config.RuntimeConfig, port int) []string {- geoAlignment, err := resolveLaunchGeoAlignment(context.Background(), cfg)- if err != nil {- args, _, buildErr := buildBrowserArgsWithBundle(cfg, nil, port, launchGeoAlignment{})- if buildErr != nil {- return nil- }- return args- }- args, _, err := buildBrowserArgsWithBundle(cfg, nil, port, geoAlignment)- if err != nil {- return nil- }- return args-}--func existingExtensionPaths(paths []string) []string {- if len(paths) == 0 {- return nil- }- validPaths := make([]string, 0, len(paths))- for _, path := range paths {- if _, err := os.Stat(path); err == nil {- validPaths = append(validPaths, path)- }- }- return validPaths-}--func buildBrowserArgsWithBundle(cfg *config.RuntimeConfig, bundle *stealth.Bundle, port int, geoAlignment launchGeoAlignment) ([]string, []string, error) {- bundle = ensureStealthBundle(cfg, bundle)- binary := strings.TrimSpace(cfg.BrowserBinary)- if binary == "" {- binary = runtimekit.FindBrowserBinary(config.NormalizeBrowser(cfg.DefaultBrowser))- }- plan, err := resolveProviderLaunchPlan(cfg, runtimekit.LaunchConfigFromRuntime(cfg, binary, port, launchNeedsNoSandbox()))- if err != nil {- return nil, nil, err- }- args := append([]string(nil), plan.args...)-- args = append(args, bundle.Launch.Args...)- args = append(args, config.BrowserProxyFlags(cfg.Proxy)...)- args = append(args, geoAlignment.flags...)-- env := append([]string(nil), plan.env...)- return args, env, nil-}--func CloakBrowserFlagArgs(cfg *config.RuntimeConfig) []string {- return runtimekit.CloakBrowserFlagArgs(cfg)-}-func applyStartupStealth(ctx context.Context, cfg *config.RuntimeConfig, bundle *stealth.Bundle, script string) error {if !config.PinchTabStealthDefaultsDisabled(cfg) {ua := ""@@ -394,18 +274,6 @@ func applyStartupStealth(ctx context.Context, cfg *config.RuntimeConfig, bundlereturn injectedScript(ctx, script)}-func stripInProcessGPUFlag(flags []string) []string {- out := flags[:0]- for _, f := range flags {- name := strings.SplitN(f, "=", 2)[0]- if strings.EqualFold(name, "--in-process-gpu") {- continue- }- out = append(out, f)- }- return out-}-func missingBrowserBinaryError(cfg *config.RuntimeConfig) error {browserID := config.NormalizeBrowser(cfg.DefaultBrowser)if b, ok := browsers.Get(browserID); ok {@@ -423,48 +291,6 @@ func injectedScript(ctx context.Context, script string) error {}, nil)}-func randomWindowSize() (int, int) {- sizes := [][2]int{- {1920, 1080}, {1366, 768}, {1536, 864}, {1440, 900},- {1280, 720}, {1600, 900}, {2560, 1440}, {1280, 800},- }- n, err := rand.Int(rand.Reader, big.NewInt(int64(len(sizes))))- idx := 0- if err == nil {- idx = int(n.Int64())- }- s := sizes[idx]- return s[0], s[1]-}--type prefixedLogWriter struct {- dst io.Writer- prefix string- buf []byte-}--func newPrefixedLogWriter(dst io.Writer, prefix string) *prefixedLogWriter {- return &prefixedLogWriter{dst: dst, prefix: prefix, buf: make([]byte, 0, 1024)}-}--func (w *prefixedLogWriter) Write(p []byte) (int, error) {- w.buf = append(w.buf, p...)- for {- idx := bytes.IndexByte(w.buf, '\n')- if idx < 0 {- break- }- line := w.buf[:idx]- w.buf = w.buf[idx+1:]- if len(line) > 0 {- if _, err := fmt.Fprintf(w.dst, "%s: %s\n", w.prefix, string(line)); err != nil {- return 0, err- }- }- }- 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{}@@ -521,11 +347,3 @@ func mergeGeoEnv(base, additions []string) []string {out = append(out, additions...)return out}--func cryptoRandSeed() int64 {- n, err := rand.Int(rand.Reader, big.NewInt(1000000000))- if err != nil {- return 42- }- return n.Int64()-}diff --git a/internal/bridge/runtime/init_attach.go b/internal/bridge/runtime/init_attach.gonew file mode 100644index 00000000..79021d55--- /dev/null+++ b/internal/bridge/runtime/init_attach.go@@ -0,0 +1,57 @@+package runtime++import (+ "context"+ "fmt"+ "log/slog"++ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/browsers"+ "github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/stealth"+)++// initBrowserFromExistingCDP attaches the bridge to a browser that is already+// running outside pinchtab (e.g. the user's everyday browser launched with+// --remote-debugging-port=NNNN). No process is spawned and no profile lock+// is taken. The allocator is a chromedp remote allocator; the returned+// cancel funcs release only the chromedp side, never the external browser.+func initBrowserFromExistingCDP(cfg *config.RuntimeConfig, bundle *stealth.Bundle) (context.Context, context.CancelFunc, context.Context, context.CancelFunc, stealth.LaunchMode, error) {+ browserID, _ := config.ParseBrowser(cfg.DefaultBrowser, cfg.BrowsersAvailable)+ if browserID == "" {+ browserID = config.NormalizeBrowser(cfg.DefaultBrowser)+ }+ if b, ok := browsers.Get(browserID); ok && !b.SupportsRemoteCDP() {+ return nil, nil, nil, nil, stealth.LaunchModeUninitialized,+ fmt.Errorf("provider %q does not support remote CDP attach", browserID)+ }++ // Same SSRF/attach guard as the RemoteCDPURL path (init_remote.go):+ // loopback endpoints always pass; non-loopback hosts must be listed in+ // security.attach.allowHosts. The returned URL is host-pinned to the+ // resolved IP so the dial can't be re-routed by a second DNS answer.+ wsURL, err := NormalizeCDPURLWithAllowlist(cfg.CDPAttachURL, cfg.AttachAllowHosts, cfg.AttachAllowSchemes)+ if err != nil {+ return nil, nil, nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("normalize cdpAttachUrl: %w", err)+ }+ slog.Info("attaching to existing browser via CDP", "cdpUrl", wsURL)++ remoteAllocCtx, remoteAllocCancel := chromedp.NewRemoteAllocator(context.Background(), wsURL)+ browserCtx, browserCancel := chromedp.NewContext(remoteAllocCtx)++ // Touch the browser so we fail fast if the CDP URL is unreachable. We+ // intentionally do NOT inject the stealth/UA script here — the user's+ // browser is theirs, and rewriting its launch contract would be both+ // surprising and likely break extensions, profile features, and+ // already-open tabs.+ if err := chromedp.Run(browserCtx, chromedp.ActionFunc(func(ctx context.Context) error {+ return nil+ })); err != nil {+ browserCancel()+ remoteAllocCancel()+ return nil, nil, nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to attach to CDP at %s: %w", wsURL, err)+ }++ slog.Info("attached to existing browser via CDP", "cdpUrl", wsURL)+ return remoteAllocCtx, remoteAllocCancel, browserCtx, browserCancel, stealth.LaunchModeAttached, nil+}diff --git a/internal/bridge/runtime/init_attach_test.go b/internal/bridge/runtime/init_attach_test.gonew file mode 100644index 00000000..3c5bd1b2--- /dev/null+++ b/internal/bridge/runtime/init_attach_test.go@@ -0,0 +1,57 @@+package runtime++import (+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+)++func TestInitBrowserFromExistingCDPRejectsNonAllowlistedHost(t *testing.T) {+ cfg := &config.RuntimeConfig{+ CDPAttachURL: "ws://203.0.113.10:9222/devtools/browser/abc",+ }++ _, _, _, _, _, err := initBrowserFromExistingCDP(cfg, nil)+ if err == nil {+ t.Fatal("expected non-loopback CDPAttachURL without allowlist to be rejected")+ }+ if !strings.Contains(err.Error(), "security.attach.allowHosts") {+ t.Fatalf("error should mention security.attach.allowHosts, got %v", err)+ }+}++func TestInitBrowserFromExistingCDPRejectsDisallowedScheme(t *testing.T) {+ cfg := &config.RuntimeConfig{+ CDPAttachURL: "http://127.0.0.1:9222",+ AttachAllowSchemes: []string{"ws"},+ }++ _, _, _, _, _, err := initBrowserFromExistingCDP(cfg, nil)+ 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)+ }+}++// Loopback must keep working with empty allowlists: normalization passes and+// the failure (nothing is listening on port 1) comes from the attach dial,+// not the validator.+func TestInitBrowserFromExistingCDPAllowsLoopbackWithoutAllowlist(t *testing.T) {+ cfg := &config.RuntimeConfig{+ CDPAttachURL: "ws://127.0.0.1:1/devtools/browser/abc",+ }++ _, _, _, _, _, err := initBrowserFromExistingCDP(cfg, nil)+ if err == nil {+ t.Fatal("expected attach to fail: nothing is listening on 127.0.0.1:1")+ }+ if strings.Contains(err.Error(), "normalize cdpAttachUrl") {+ t.Fatalf("loopback URL should pass normalization, got %v", err)+ }+ if !strings.Contains(err.Error(), "failed to attach to CDP") {+ t.Fatalf("expected dial-stage attach failure, got %v", err)+ }+}diff --git a/internal/bridge/runtime/init_remote.go b/internal/bridge/runtime/init_remote.goindex 603aad9a..f3ed9468 100644--- a/internal/bridge/runtime/init_remote.go+++ b/internal/bridge/runtime/init_remote.go@@ -5,6 +5,7 @@ import ("fmt""log/slog""net/url"+ "strings""time""github.com/chromedp/chromedp"@@ -36,7 +37,13 @@ func InitRemoteCDP(ctx context.Context, cfg *config.RuntimeConfig, cdpURL stringallocCtx, allocCancel := chromedp.NewRemoteAllocator(ctx, normalized)probeCtx, probeCancel := context.WithTimeout(ctx, 10*time.Second)- _, err = ProbeCDPVersion(probeCtx, normalized, cfg.AttachAllowHosts)+ // Probe the ORIGINAL URL, not the normalized one: normalization pins the+ // host by rewriting it to the resolved IP, and re-validating that bare IP+ // against a hostname allowlist can never match — every allowlisted DNS+ // hostname would fail here. The probe validates and pins the original+ // hostname itself, so the dial stays SSRF-safe; the allocator above still+ // attaches via the normalized pinned URL.+ _, err = ProbeCDPVersion(probeCtx, strings.TrimSpace(cdpURL), cfg.AttachAllowHosts)probeCancel()if err != nil {allocCancel()@@ -44,13 +51,14 @@ func InitRemoteCDP(ctx context.Context, cfg *config.RuntimeConfig, cdpURL string}browserCtx, browserCancel := chromedp.NewContext(allocCtx)- if proxyAuthEnabled(cfg.Proxy) {+ if ProxyAuthEnabled(cfg.Proxy) {auditRemoteProxyAuthForward(normalized, cfg)- if err := enableProxyAuth(browserCtx, cfg.Proxy); err != nil {+ if err := EnableProxyAuth(browserCtx, cfg.Proxy, nil); err != nil {browserCancel()allocCancel()return nil, nil, nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("enable proxy auth on remote CDP: %w", err)}+ slog.Info("proxy authentication enabled via CDP", "proxy", cfg.Proxy.Redacted())}return allocCtx, allocCancel, browserCtx, func() {@@ -61,7 +69,7 @@ func InitRemoteCDP(ctx context.Context, cfg *config.RuntimeConfig, cdpURL string}func requireRemoteProxyAuthOptIn(browserWSURL string, cfg *config.RuntimeConfig) error {- if cfg == nil || !proxyAuthEnabled(cfg.Proxy) {+ if cfg == nil || !ProxyAuthEnabled(cfg.Proxy) {return nil}targetHost := remoteCDPTargetHost(browserWSURL)@@ -77,7 +85,7 @@ func requireRemoteProxyAuthOptIn(browserWSURL string, cfg *config.RuntimeConfig)}func auditRemoteProxyAuthForward(browserWSURL string, cfg *config.RuntimeConfig) {- if cfg == nil || !proxyAuthEnabled(cfg.Proxy) || !cfg.AttachForwardProxyAuth {+ if cfg == nil || !ProxyAuthEnabled(cfg.Proxy) || !cfg.AttachForwardProxyAuth {return}slog.Warn("audit",diff --git a/internal/bridge/runtime/init_test.go b/internal/bridge/runtime/init_test.goindex 5df67eae..c620ea94 100644--- a/internal/bridge/runtime/init_test.go+++ b/internal/bridge/runtime/init_test.go@@ -325,3 +325,75 @@ func TestInitRemoteCDP_RejectsUnsupportedProvider(t *testing.T) {t.Fatalf("expected 'does not support remote CDP' in error; got: %v", err)}}++// Crash-recovery kill switch (H8 regression): a user-supplied+// --in-process-gpu must be stripped from the direct-launch args when+// DisableInProcessGPU is set, and must appear exactly once when it is not —+// the provider plan must not inject a second, unstrippable copy.+func TestBuildBrowserArgs_DisableInProcessGPUKillSwitch(t *testing.T) {+ cfg := &config.RuntimeConfig{+ DefaultBrowser: config.BrowserChrome,+ BrowserExtraFlags: "--in-process-gpu",+ Headless: true,+ }++ count := func(args []string) int {+ n := 0+ for _, a := range args {+ if a == "--in-process-gpu" {+ n+++ }+ }+ return n+ }++ if got := count(BuildBrowserArgs(cfg, 9222)); got != 1 {+ t.Fatalf("expected user --in-process-gpu exactly once without kill switch, got %d", got)+ }++ cfg.DisableInProcessGPU = true+ if got := count(BuildBrowserArgs(cfg, 9222)); got != 0 {+ t.Fatalf("kill switch active but --in-process-gpu still present (%d occurrences)", got)+ }+}++// Headless launch args must not contain --disable-gpu on any chrome-family+// path: under --headless=new it removes the compositor's GPU backend and+// Page.captureScreenshot/printToPDF hang.+func TestBuildBrowserArgs_HeadlessOmitsDisableGPU(t *testing.T) {+ for _, provider := range []string{config.BrowserChrome, config.BrowserGhostChrome} {+ cfg := &config.RuntimeConfig{DefaultBrowser: provider, Headless: true}+ for _, a := range BuildBrowserArgs(cfg, 9222) {+ if a == "--disable-gpu" {+ t.Fatalf("provider %s: headless args contain --disable-gpu", provider)+ }+ }+ }+}++// M2 regression: a malformed proxy server must fail the launch-args build —+// launching without the configured proxy would egress from the real IP.+func TestBuildBrowserArgs_MalformedProxyFailsClosed(t *testing.T) {+ cfg := &config.RuntimeConfig{+ DefaultBrowser: config.BrowserChrome,+ Proxy: config.BrowserProxyConfig{Server: "not a proxy url"},+ }+ if _, _, err := buildBrowserArgsWithBundle(cfg, nil, 9222, launchGeoAlignment{}); err == nil {+ t.Fatal("expected launch-args build to fail for malformed proxy server")+ }++ cfg.Proxy.Server = "http://proxy.example.com:8080"+ args, _, err := buildBrowserArgsWithBundle(cfg, nil, 9222, launchGeoAlignment{})+ if err != nil {+ t.Fatalf("valid proxy should build: %v", err)+ }+ count := 0+ for _, a := range args {+ if a == "--proxy-server=http://proxy.example.com:8080" {+ count+++ }+ }+ if count != 1 {+ t.Fatalf("expected exactly one --proxy-server flag, got %d in %v", count, args)+ }+}diff --git a/internal/bridge/runtime/launch_args.go b/internal/bridge/runtime/launch_args.gonew file mode 100644index 00000000..ed0c3403--- /dev/null+++ b/internal/bridge/runtime/launch_args.go@@ -0,0 +1,149 @@+package runtime++import (+ "context"+ "crypto/rand"+ "log/slog"+ "math/big"+ "os"+ "strings"++ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/browsers/runtimekit"+ "github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/stealth"+)++func appendExecAllocatorFlag(opts []chromedp.ExecAllocatorOption, flag string) []chromedp.ExecAllocatorOption {+ name := strings.TrimPrefix(flag, "--")+ if parts := strings.SplitN(name, "=", 2); len(parts) == 2 {+ return append(opts, chromedp.Flag(parts[0], parts[1]))+ }+ return append(opts, chromedp.Flag(name, true))+}++func appendExecAllocatorFlags(opts []chromedp.ExecAllocatorOption, flags []string) []chromedp.ExecAllocatorOption {+ for _, flag := range flags {+ opts = appendExecAllocatorFlag(opts, flag)+ }+ return opts+}++func browserLaunchArgs(headless bool) []string {+ return runtimekit.BaseFlagArgs("chrome", headless)+}++func BaseBrowserFlagArgs() []string {+ return browserLaunchArgs(false)+}++func appendBrowserCompatibilityFlags(args []string) []string {+ if launchNeedsNoSandbox() {+ return append(args, "--no-sandbox")+ }+ return args+}++func launchNeedsNoSandbox() bool {+ _, err := os.Stat(containerMarkerPath)+ return runtimekit.ChromeNeedsNoSandbox(runtimeGOOS, osGeteuid(), err == nil)+}++func BuildBrowserArgs(cfg *config.RuntimeConfig, port int) []string {+ geoAlignment, err := resolveLaunchGeoAlignment(context.Background(), cfg)+ if err != nil {+ args, _, buildErr := buildBrowserArgsWithBundle(cfg, nil, port, launchGeoAlignment{})+ if buildErr != nil {+ slog.Error("build browser args failed", "err", buildErr)+ return nil+ }+ return args+ }+ args, _, err := buildBrowserArgsWithBundle(cfg, nil, port, geoAlignment)+ if err != nil {+ slog.Error("build browser args failed", "err", err)+ return nil+ }+ return args+}++func existingExtensionPaths(paths []string) []string {+ if len(paths) == 0 {+ return nil+ }+ validPaths := make([]string, 0, len(paths))+ for _, path := range paths {+ if _, err := os.Stat(path); err == nil {+ validPaths = append(validPaths, path)+ }+ }+ return validPaths+}++func buildBrowserArgsWithBundle(cfg *config.RuntimeConfig, bundle *stealth.Bundle, port int, geoAlignment launchGeoAlignment) ([]string, []string, error) {+ bundle = ensureStealthBundle(cfg, bundle)+ binary := strings.TrimSpace(cfg.BrowserBinary)+ if binary == "" {+ binary = runtimekit.FindBrowserBinary(config.NormalizeBrowser(cfg.DefaultBrowser))+ }+ launchCfg := runtimekit.LaunchConfigFromRuntime(cfg, binary, port, launchNeedsNoSandbox())+ if cfg.DisableInProcessGPU {+ // Crash-recovery kill switch: a user-supplied --in-process-gpu must+ // not survive a retry after a GPU crash loop.+ launchCfg.ExtraFlags = stripInProcessGPUFlag(launchCfg.ExtraFlags)+ }+ plan, err := resolveProviderLaunchPlan(cfg, launchCfg)+ if err != nil {+ return nil, nil, err+ }+ args := append([]string(nil), plan.args...)++ args = append(args, bundle.Launch.Args...)+ proxyFlags, err := config.BrowserProxyFlags(cfg.Proxy)+ if err != nil {+ return nil, nil, err+ }+ args = append(args, proxyFlags...)+ args = append(args, geoAlignment.flags...)++ env := append([]string(nil), plan.env...)+ return args, env, nil+}++func CloakBrowserFlagArgs(cfg *config.RuntimeConfig) []string {+ return runtimekit.CloakBrowserFlagArgs(cfg)+}++func stripInProcessGPUFlag(flags []string) []string {+ out := flags[:0]+ for _, f := range flags {+ name := strings.SplitN(f, "=", 2)[0]+ if strings.EqualFold(name, "--in-process-gpu") {+ continue+ }+ out = append(out, f)+ }+ return out+}++func randomWindowSize() (int, int) {+ sizes := [][2]int{+ {1920, 1080}, {1366, 768}, {1536, 864}, {1440, 900},+ {1280, 720}, {1600, 900}, {2560, 1440}, {1280, 800},+ }+ n, err := rand.Int(rand.Reader, big.NewInt(int64(len(sizes))))+ idx := 0+ if err == nil {+ idx = int(n.Int64())+ }+ s := sizes[idx]+ return s[0], s[1]+}++func cryptoRandSeed() int64 {+ n, err := rand.Int(rand.Reader, big.NewInt(1000000000))+ if err != nil {+ return 42+ }+ return n.Int64()+}diff --git a/internal/bridge/runtime/log_writer.go b/internal/bridge/runtime/log_writer.gonew file mode 100644index 00000000..92d727be--- /dev/null+++ b/internal/bridge/runtime/log_writer.go@@ -0,0 +1,35 @@+package runtime++import (+ "bytes"+ "fmt"+ "io"+)++type prefixedLogWriter struct {+ dst io.Writer+ prefix string+ buf []byte+}++func newPrefixedLogWriter(dst io.Writer, prefix string) *prefixedLogWriter {+ return &prefixedLogWriter{dst: dst, prefix: prefix, buf: make([]byte, 0, 1024)}+}++func (w *prefixedLogWriter) Write(p []byte) (int, error) {+ w.buf = append(w.buf, p...)+ for {+ idx := bytes.IndexByte(w.buf, '\n')+ if idx < 0 {+ break+ }+ line := w.buf[:idx]+ w.buf = w.buf[idx+1:]+ if len(line) > 0 {+ if _, err := fmt.Fprintf(w.dst, "%s: %s\n", w.prefix, string(line)); err != nil {+ return 0, err+ }+ }+ }+ return len(p), nil+}diff --git a/internal/bridge/runtime/proxy_auth.go b/internal/bridge/runtime/proxy_auth.goindex 975cb63c..8b860822 100644--- a/internal/bridge/runtime/proxy_auth.go+++ b/internal/bridge/runtime/proxy_auth.go@@ -4,75 +4,91 @@ import ("context""fmt""log/slog"+ "sync/atomic""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+// ProxyAuthEnabled is the single gate for the CDP credential path// (testable without a running Chrome).-func proxyAuthEnabled(p config.BrowserProxyConfig) bool {+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) {+// EnableProxyAuth makes the target behind tabCtx answer proxy auth challenges+// with the configured credentials. Fetch events are session-scoped — chromedp+// delivers them only to ListenTarget listeners on the session that enabled the+// domain — so this must run once per target: the initial tab at launch/attach+// and every managed tab via tabSetup. A ListenBrowser listener never sees them.+//+// pauseSuppressed (optional) quiets this listener's blanket ContinueRequest+// while another Fetch user (RouteManager rules, the credentials handler) owns+// request-pause dispatch on the tab — chromedp listeners are additive, so+// without it both would race on every paused request. Auth challenges are+// never suppressed. Never log the password — use p.Redacted().+func EnableProxyAuth(tabCtx context.Context, p config.BrowserProxyConfig, pauseSuppressed *atomic.Bool) 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.Usernamepassword := p.Password- chromedp.ListenBrowser(browserCtx, func(ev interface{}) {+ // Register before Fetch.enable: events cannot flow until the domain is+ // enabled, so nothing is missed, while the reverse order can drop the+ // first authRequired. ListenTarget queues the listener when the target+ // is not materialized yet. Handlers run in goroutines — issuing CDP+ // commands synchronously from the event-dispatch goroutine deadlocks.+ chromedp.ListenTarget(tabCtx, func(ev interface{}) {switch e := ev.(type) {case *fetch.EventAuthRequired:- handleAuthRequired(browserCtx, e, username, password)+ go handleAuthRequired(tabCtx, e, username, password)case *fetch.EventRequestPaused:- handleRequestPaused(browserCtx, e)+ if pauseSuppressed != nil && pauseSuppressed.Load() {+ return+ }+ go handleRequestPaused(tabCtx, e)}})- slog.Info("proxy authentication enabled via CDP", "proxy", p.Redacted())+ if err := chromedp.Run(tabCtx,+ fetch.Enable().WithHandleAuthRequests(true),+ ); err != nil {+ return fmt.Errorf("enable fetch domain for proxy auth: %w", err)+ }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+// AuthChallengeResponse decides how to answer an auth challenge: provide the+// proxy credentials for proxy challenges, yield with Default for everything+// else (e.g. server WWW-Authenticate).+func AuthChallengeResponse(e *fetch.EventAuthRequired, username, password string) *fetch.AuthChallengeResponse {+ if e == nil || e.AuthChallenge == nil || e.AuthChallenge.Source != fetch.AuthChallengeSourceProxy {+ return &fetch.AuthChallengeResponse{Response: fetch.AuthChallengeResponseResponseDefault}}- 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)+ return &fetch.AuthChallengeResponse{+ Response: fetch.AuthChallengeResponseResponseProvideCredentials,+ Username: username,+ Password: password,+ }+}++func handleAuthRequired(tabCtx context.Context, e *fetch.EventAuthRequired, username, password string) {+ resp := AuthChallengeResponse(e, username, password)+ if err := chromedp.Run(tabCtx,+ fetch.ContinueWithAuth(e.RequestID, resp),+ ); err != nil && tabCtx.Err() == nil {+ slog.Warn("proxy auth: continue with auth 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 {+func handleRequestPaused(tabCtx context.Context, e *fetch.EventRequestPaused) {+ if err := chromedp.Run(tabCtx, fetch.ContinueRequest(e.RequestID)); err != nil && tabCtx.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.goindex 2452cdc8..16137a96 100644--- a/internal/bridge/runtime/proxy_auth_test.go+++ b/internal/bridge/runtime/proxy_auth_test.go@@ -7,6 +7,7 @@ import ("strings""testing"+ "github.com/chromedp/cdproto/fetch""github.com/pinchtab/pinchtab/internal/config")@@ -34,8 +35,8 @@ func TestProxyAuthEnabled_DisabledWhenNoCredentials(t *testing.T) {}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())+ if ProxyAuthEnabled(tc.p) {+ t.Fatalf("ProxyAuthEnabled(%+v) = true, want false", tc.p.Redacted())}})}@@ -47,8 +48,8 @@ func TestProxyAuthEnabled_EnabledWhenCredentialsPresent(t *testing.T) {Username: "user",Password: "pw",}- if !proxyAuthEnabled(p) {- t.Fatalf("proxyAuthEnabled(%+v) = false, want true", p.Redacted())+ if !ProxyAuthEnabled(p) {+ t.Fatalf("ProxyAuthEnabled(%+v) = false, want true", p.Redacted())}}@@ -56,11 +57,51 @@ func TestProxyAuthEnabled_EnabledWhenCredentialsPresent(t *testing.T) {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{}, nil); 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)+ if err := EnableProxyAuth(ctx, config.BrowserProxyConfig{Server: "http://p:1"}, nil); err != nil {+ t.Fatalf("EnableProxyAuth on credential-less proxy returned %v, want nil", err)+ }+}++func TestAuthChallengeResponse_ProvidesCredentialsForProxyChallenge(t *testing.T) {+ e := &fetch.EventAuthRequired{+ AuthChallenge: &fetch.AuthChallenge{Source: fetch.AuthChallengeSourceProxy},+ }+ resp := AuthChallengeResponse(e, "user", "pw")+ if resp.Response != fetch.AuthChallengeResponseResponseProvideCredentials {+ t.Fatalf("Response = %q, want ProvideCredentials", resp.Response)+ }+ if resp.Username != "user" || resp.Password != "pw" {+ t.Fatalf("credentials = %q/%q, want user/pw", resp.Username, resp.Password)+ }+}++func TestAuthChallengeResponse_YieldsNonProxyChallenges(t *testing.T) {+ cases := []struct {+ name string+ e *fetch.EventAuthRequired+ }{+ {name: "nil event", e: nil},+ {name: "nil challenge", e: &fetch.EventAuthRequired{}},+ {+ name: "server challenge (WWW-Authenticate)",+ e: &fetch.EventAuthRequired{+ AuthChallenge: &fetch.AuthChallenge{Source: fetch.AuthChallengeSourceServer},+ },+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ resp := AuthChallengeResponse(tc.e, "user", "pw")+ if resp.Response != fetch.AuthChallengeResponseResponseDefault {+ t.Fatalf("Response = %q, want Default", resp.Response)+ }+ if resp.Username != "" || resp.Password != "" {+ t.Fatalf("credentials leaked into non-proxy challenge response: %q/%q", resp.Username, resp.Password)+ }+ })}}diff --git a/internal/bridge/runtime/recovery.go b/internal/bridge/runtime/recovery.goindex c8d2b387..713ccda0 100644--- a/internal/bridge/runtime/recovery.go+++ b/internal/bridge/runtime/recovery.go@@ -78,14 +78,16 @@ func startBrowserWithRecovery(parentCtx context.Context, cfg *config.RuntimeConfif silentDrop && !retriedProfileCorruption && hooks.QuarantineCorruptedProfile != nil && strings.TrimSpace(cfg.ProfileDir) != "" {if quarantinePath, qerr := hooks.QuarantineCorruptedProfile(cfg.ProfileDir); qerr == nil {- slog.Warn("cloakbrowser silently dropped CDP attach; quarantined profile and retrying with fresh profile",+ slog.Warn("browser silently dropped CDP attach; quarantined profile and retrying with fresh profile",+ "provider", browserID,"originalProfile", cfg.ProfileDir,"quarantinedTo", quarantinePath,"elapsedMs", elapsed.Milliseconds())time.Sleep(500 * time.Millisecond)return startBrowserWithRecovery(parentCtx, cfg, bundle, opts, debugPort, hooks, geoAlignment, retriedProfileLock, true)} else {- slog.Warn("cloakbrowser silently dropped CDP attach; profile quarantine failed",+ slog.Warn("browser silently dropped CDP attach; profile quarantine failed",+ "provider", browserID,"originalProfile", cfg.ProfileDir,"err", qerr.Error())}@@ -98,7 +100,7 @@ func startBrowserWithRecovery(parentCtx context.Context, cfg *config.RuntimeConf}if silentDrop {- return nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to connect to browser: %w (cloakbrowser dropped CDP attach silently after %dms; profile %q may be corrupted — try removing it or use a fresh profile)", err, elapsed.Milliseconds(), cfg.ProfileDir)+ return nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to connect to browser: %w (%s dropped CDP attach silently after %dms; profile %q may be corrupted — try removing it or use a fresh profile)", err, browserID, elapsed.Milliseconds(), cfg.ProfileDir)}return nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to connect to browser: %w", err)}diff --git a/internal/bridge/runtime/recovery_test.go b/internal/bridge/runtime/recovery_test.gonew file mode 100644index 00000000..afe71cf1--- /dev/null+++ b/internal/bridge/runtime/recovery_test.go@@ -0,0 +1,54 @@+package runtime++import (+ "context"+ "sync/atomic"+ "testing"+ "time"++ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/config"+)++// M10 regression: the recovery ladder's profile-lock hook path. A nonexistent+// binary makes the exec allocator fail fast and deterministically; the+// profile-lock clear must run exactly once (the retriedProfileLock guard+// prevents loops), and chrome's classifier never reports silent-drop, so the+// quarantine hook must not fire.+func TestStartBrowserWithRecovery_ProfileLockClearedOnce(t *testing.T) {+ cfg := &config.RuntimeConfig{+ DefaultBrowser: config.BrowserChrome,+ ProfileDir: t.TempDir(),+ }+ opts := []chromedp.ExecAllocatorOption{+ chromedp.ExecPath("/nonexistent/pinchtab-m10-test-binary"),+ chromedp.NoFirstRun,+ chromedp.NoDefaultBrowserCheck,+ }++ var clearCalls, quarantineCalls atomic.Int32+ hooks := Hooks{+ IsProfileLockError: func(string) bool { return true },+ ClearStaleProfileLocks: func(profileDir, errMsg string) (bool, error) {+ clearCalls.Add(1)+ return true, nil+ },+ QuarantineCorruptedProfile: func(profileDir string) (string, error) {+ quarantineCalls.Add(1)+ return profileDir + ".quarantine", nil+ },+ }++ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ _, _, _, err := startBrowserWithRecovery(ctx, cfg, nil, opts, 0, hooks, launchGeoAlignment{}, false, false)+ if err == nil {+ t.Fatal("expected startup failure with a nonexistent binary")+ }+ if got := clearCalls.Load(); got != 1 {+ t.Fatalf("ClearStaleProfileLocks calls = %d, want exactly 1 (retry guard)", got)+ }+ if got := quarantineCalls.Load(); got != 0 {+ t.Fatalf("QuarantineCorruptedProfile calls = %d, want 0 (chrome never classifies silent-drop)", got)+ }+}