Skip to content

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

fix: coordinate per-tab fetch domain between routes, credentials listeners, and proxy auth

Bosch9983306bace9
diff --git a/internal/bridge/api.go b/internal/bridge/api.go
index f82e8665..f6b7386b 100644
--- a/internal/bridge/api.go
+++ b/internal/bridge/api.go
@@ -56,6 +56,11 @@ type BridgeAPI interface {
EnsureBrowser(cfg *config.RuntimeConfig) error
RestartBrowser(cfg *config.RuntimeConfig) error
+ // RunningBrowser reports the provider of the live browser process, or
+ // ("", false) when nothing is running. EnsureBrowser ignores the requested
+ // config once initialized, so handlers use this to reject explicit
+ // browser params that the running process cannot honor.
+ RunningBrowser() (string, bool)
StealthStatus() *stealth.Status
// Memory metrics
diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.go
index 8a7f9c6e..21a9fc2f 100644
--- a/internal/bridge/bridge.go
+++ b/internal/bridge/bridge.go
@@ -4,9 +4,11 @@ import (
"context"
"fmt"
"sync"
+ "sync/atomic"
"time"
"github.com/chromedp/chromedp"
+ bridgeruntime "github.com/pinchtab/pinchtab/internal/bridge/runtime"
"github.com/pinchtab/pinchtab/internal/browsers"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/ids"
@@ -34,6 +36,12 @@ type Bridge struct {
// only when at least one rule is active for a tab.
routeMgr *RouteManager
+ // fetchPauseMu guards fetchPauseFlags: per-tab suppression of the
+ // proxy-auth listener's blanket ContinueRequest while another Fetch
+ // user (route rules, credentials handler) owns request-pause dispatch.
+ fetchPauseMu sync.Mutex
+ fetchPauseFlags map[string]*atomic.Bool
+
fingerprintMu sync.RWMutex
fingerprintOverlays map[string]bool
workerStealthTargets sync.Map
@@ -90,6 +98,10 @@ func New(allocCtx, browserCtx context.Context, cfg *config.RuntimeConfig) *Bridg
}
return b.Config.AllowedDomains
})
+ b.routeMgr.SetFetchAuthCoordination(
+ func() bool { return b.Config != nil && bridgeruntime.ProxyAuthEnabled(b.Config.Proxy) },
+ b.SetFetchPauseSuppressed,
+ )
b.ensureStealthBundle()
b.Dialogs = NewDialogManager()
if cfg != nil && browserCtx != nil {
@@ -98,6 +110,7 @@ func New(allocCtx, browserCtx context.Context, cfg *config.RuntimeConfig) *Bridg
b.SetDialogManager(b.Dialogs)
b.SetNetworkMonitor(b.netMonitor)
b.SetRouteManager(b.routeMgr)
+ b.SetOnTabRemoved(b.dropFetchPauseSuppression)
if !b.quietStealthObservers() {
b.StartBrowserGuards()
}
@@ -107,6 +120,42 @@ func New(allocCtx, browserCtx context.Context, cfg *config.RuntimeConfig) *Bridg
return b
}
+// fetchPauseSuppression returns (creating if needed) the per-tab flag that
+// quiets the proxy-auth listener's request-pause continue while another
+// Fetch user owns dispatch on the tab.
+func (b *Bridge) fetchPauseSuppression(tabID string) *atomic.Bool {
+ if tabID == "" {
+ return nil
+ }
+ b.fetchPauseMu.Lock()
+ defer b.fetchPauseMu.Unlock()
+ if b.fetchPauseFlags == nil {
+ b.fetchPauseFlags = map[string]*atomic.Bool{}
+ }
+ flag, ok := b.fetchPauseFlags[tabID]
+ if !ok {
+ flag = &atomic.Bool{}
+ b.fetchPauseFlags[tabID] = flag
+ }
+ return flag
+}
+
+// SetFetchPauseSuppressed marks whether another Fetch user (route rules, the
+// credentials handler) currently owns request-pause dispatch on the tab.
+func (b *Bridge) SetFetchPauseSuppressed(tabID string, v bool) {
+ if b == nil || tabID == "" {
+ return
+ }
+ b.fetchPauseSuppression(tabID).Store(v)
+}
+
+// dropFetchPauseSuppression releases the per-tab flag when a tab goes away.
+func (b *Bridge) dropFetchPauseSuppression(tabID string) {
+ b.fetchPauseMu.Lock()
+ defer b.fetchPauseMu.Unlock()
+ delete(b.fetchPauseFlags, tabID)
+}
+
// StartNetworkCapture enables network monitoring for a specific tab.
// This is called lazily when network data is first requested for a tab.
func (b *Bridge) StartNetworkCapture(tabCtx context.Context, tabID string) error {
diff --git a/internal/bridge/bridge_cleanup_test.go b/internal/bridge/bridge_cleanup_test.go
index 42f6a8dd..3719881b 100644
--- a/internal/bridge/bridge_cleanup_test.go
+++ b/internal/bridge/bridge_cleanup_test.go
@@ -228,3 +228,23 @@ func TestCleanup_RemoteCDP_SkipsKillLogic(t *testing.T) {
t.Errorf("remote-CDP cleanup must not SIGKILL, got %d", got)
}
}
+
+// M16: per-tab pause-suppression flag lifecycle on the Bridge.
+func TestFetchPauseSuppressionLifecycle(t *testing.T) {
+ b := &Bridge{}
+ flag := b.fetchPauseSuppression("t1")
+ if flag == nil || flag.Load() {
+ t.Fatal("fresh flag should exist and be false")
+ }
+ b.SetFetchPauseSuppressed("t1", true)
+ if !flag.Load() {
+ t.Fatal("the same flag instance must observe SetFetchPauseSuppressed")
+ }
+ b.dropFetchPauseSuppression("t1")
+ if recreated := b.fetchPauseSuppression("t1"); recreated == flag || recreated.Load() {
+ t.Fatal("dropped flag should be recreated fresh and unset")
+ }
+ if b.fetchPauseSuppression("") != nil {
+ t.Fatal("empty tab ID must not allocate a flag")
+ }
+}
diff --git a/internal/bridge/bridge_lifecycle.go b/internal/bridge/bridge_lifecycle.go
index 55b027e0..86e1617b 100644
--- a/internal/bridge/bridge_lifecycle.go
+++ b/internal/bridge/bridge_lifecycle.go
@@ -14,6 +14,7 @@ import (
"github.com/chromedp/cdproto/page"
cdpruntime "github.com/chromedp/cdproto/runtime"
"github.com/chromedp/chromedp"
+ bridgeruntime "github.com/pinchtab/pinchtab/internal/bridge/runtime"
"github.com/pinchtab/pinchtab/internal/browsers"
"github.com/pinchtab/pinchtab/internal/browsers/chrome"
"github.com/pinchtab/pinchtab/internal/config"
@@ -82,7 +83,19 @@ func (b *Bridge) applyTargetStealth(ctx context.Context) {
}
}
-func (b *Bridge) tabSetup(ctx context.Context) {
+func (b *Bridge) tabSetup(ctx context.Context, tabID string) {
+ // Fetch auth events are session-scoped, so each new tab needs its own
+ // proxy-auth listener + Fetch enablement; the initial tab is covered by
+ // the launch/attach init paths. The suppression flag quiets this
+ // listener's request-pause continue while RouteManager rules or the
+ // credentials handler own dispatch on the tab.
+ if b.Config != nil {
+ if err := bridgeruntime.EnableProxyAuth(ctx, b.Config.Proxy, b.fetchPauseSuppression(tabID)); err != nil {
+ slog.Warn("per-tab proxy auth setup failed", "err", err)
+ } else if bridgeruntime.ProxyAuthEnabled(b.Config.Proxy) {
+ slog.Debug("per-tab proxy auth enabled", "tab", tabID)
+ }
+ }
if !config.PinchTabStealthDefaultsDisabled(b.Config) {
b.applyTargetStealth(ctx)
b.installWorkerStealthParity(ctx)
@@ -123,6 +136,17 @@ func (b *Bridge) StealthStatus() *stealth.Status {
return stealth.StatusFromBundle(b.StealthBundle, b.Config, b.stealthLaunchMode)
}
+// RunningBrowser reports the provider of the live browser process, or
+// ("", false) when no browser is initialized (or its context died).
+func (b *Bridge) RunningBrowser() (string, bool) {
+ b.initMu.Lock()
+ defer b.initMu.Unlock()
+ if !b.initialized || b.BrowserCtx == nil || b.BrowserCtx.Err() != nil || b.Config == nil {
+ return "", false
+ }
+ return b.Config.DefaultBrowser, true
+}
+
func (b *Bridge) EnsureBrowser(cfg *config.RuntimeConfig) error {
b.initMu.Lock()
defer b.initMu.Unlock()
diff --git a/internal/bridge/bridge_types.go b/internal/bridge/bridge_types.go
index c639a8f8..c385a9d7 100644
--- a/internal/bridge/bridge_types.go
+++ b/internal/bridge/bridge_types.go
@@ -2,6 +2,7 @@ package bridge
import (
"context"
+ "fmt"
"net"
"time"
@@ -133,6 +134,27 @@ type NavigateParams struct {
TrustedProxyCIDRs []net.IPNet
TrustedResolvedIPs []net.IP
IDPIGuard idpi.Guard
+ // NoEscalate makes a static-first bridge return *StaticEscalateError
+ // instead of internally escalating to Chrome. Handlers use it to defer
+ // the Chrome launch until the static path has proven insufficient.
+ NoEscalate bool
+ // SkipStatic bypasses the static-first attempt entirely (the handler
+ // already ran it via NoEscalate and is escalating).
+ SkipStatic bool
+}
+
+// StaticEscalateError signals that the static-first path cannot serve a
+// navigate (NavigateParams.NoEscalate mode) and the caller should launch
+// Chrome and retry with SkipStatic. Route carries the static attempt's
+// metadata so the caller can merge it with the Chrome attempt.
+type StaticEscalateError struct {
+ Quality int
+ Reason string
+ Route *browserops.RouteMetadata
+}
+
+func (e *StaticEscalateError) Error() string {
+ return fmt.Sprintf("static path cannot serve this navigate (quality %d): %s", e.Quality, e.Reason)
}
// ContentParams carries per-request IDPI policy for content operations.
diff --git a/internal/bridge/download.go b/internal/bridge/download.go
index 76d1506e..431dd163 100644
--- a/internal/bridge/download.go
+++ b/internal/bridge/download.go
@@ -2,14 +2,28 @@ package bridge
import (
"context"
+ "errors"
"fmt"
"sync"
"sync/atomic"
+ "time"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/fetch"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
+ bridgeruntime "github.com/pinchtab/pinchtab/internal/bridge/runtime"
+)
+
+// downloadNavTimeout caps the navigate-and-capture phase of a browser-based
+// download, matching the pre-refactor handler behavior.
+const downloadNavTimeout = 30 * time.Second
+
+// Sentinels for handler-side status mapping via errors.Is. Texts match the
+// historical messages so anything still string-matching keeps working.
+var (
+ ErrDownloadTooLarge = errors.New("download response too large")
+ ErrDownloadTimeout = errors.New("download timed out")
)
// DownloadOpts configures a browser-based download.
@@ -46,21 +60,28 @@ func (b *Bridge) DownloadURL(ctx context.Context, dlURL string, opts DownloadOpt
tabCtx, tabCancel := chromedp.NewContext(browserCtx)
defer tabCancel()
- tCtx, tCancel := context.WithCancel(ctx)
+ // Bound all tab work by the download deadline AND the caller's
+ // cancellation: tCtx derives from tabCtx so chromedp ops keep their
+ // target, and AfterFunc bridges caller disconnect/deadline into tCancel.
+ // The guard listeners below also call tCancel to abort an in-flight
+ // transfer (size cap, blocked remote IP).
+ tCtx, tCancel := context.WithTimeout(tabCtx, downloadNavTimeout)
defer tCancel()
+ stop := context.AfterFunc(ctx, tCancel)
+ defer stop()
- // Replace the tab context with one that inherits the caller's deadline.
- _ = tabCtx // ensure tabCtx stays alive for the chromedp target
-
- var requestID network.RequestID
- var responseMIME string
- var responseStatus int
- var mainFrameID cdp.FrameID
done := make(chan struct{}, 1)
var receivedBytes atomic.Int64
+ // mu guards blockedErr and the capture fields, which are written from the
+ // event-dispatch goroutine and read by this goroutine; the done channel
+ // only orders events sent before the read, not stragglers.
var mu sync.Mutex
var blockedErr error
+ var requestID network.RequestID
+ var responseMIME string
+ var responseStatus int
+ var mainFrameID cdp.FrameID
noteBlocked := func(err error) {
mu.Lock()
@@ -76,19 +97,43 @@ func (b *Bridge) DownloadURL(ctx context.Context, dlURL string, opts DownloadOpt
return blockedErr
}
- if err := chromedp.Run(tabCtx, chromedp.ActionFunc(func(ctx context.Context) error {
- return fetch.Enable().Do(ctx)
+ isMainRequest := func(id network.RequestID) bool {
+ mu.Lock()
+ defer mu.Unlock()
+ return requestID != "" && id == requestID
+ }
+
+ // The temp tab bypasses TabManager's tabSetup, so proxy auth handling
+ // must be wired here; this listener's EventAuthRequired case answers
+ // the challenges.
+ proxyAuth := b.Config != nil && bridgeruntime.ProxyAuthEnabled(b.Config.Proxy)
+ enableFetch := fetch.Enable()
+ if proxyAuth {
+ enableFetch = enableFetch.WithHandleAuthRequests(true)
+ }
+ if err := chromedp.Run(tCtx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return enableFetch.Do(ctx)
})); err != nil {
return nil, fmt.Errorf("fetch enable: %w", err)
}
+ // Cleanup runs on tabCtx, not tCtx: it must still work after the
+ // download deadline fired.
defer func() {
_ = chromedp.Run(tabCtx, chromedp.ActionFunc(func(ctx context.Context) error {
return fetch.Disable().Do(ctx)
}))
}()
- chromedp.ListenTarget(tabCtx, func(ev interface{}) {
+ chromedp.ListenTarget(tCtx, func(ev interface{}) {
switch e := ev.(type) {
+ case *fetch.EventAuthRequired:
+ if !proxyAuth {
+ return
+ }
+ go func() {
+ resp := bridgeruntime.AuthChallengeResponse(e, b.Config.Proxy.Username, b.Config.Proxy.Password)
+ _ = fetch.ContinueWithAuth(e.RequestID, resp).Do(cdp.WithExecutor(tCtx, chromedp.FromContext(tCtx).Target))
+ }()
case *fetch.EventRequestPaused:
go func() {
reqID := e.RequestID
@@ -100,27 +145,33 @@ func (b *Bridge) DownloadURL(ctx context.Context, dlURL string, opts DownloadOpt
case done <- struct{}{}:
default:
}
- _ = fetch.FailRequest(reqID, network.ErrorReasonBlockedByClient).Do(cdp.WithExecutor(tabCtx, chromedp.FromContext(tabCtx).Target))
+ _ = fetch.FailRequest(reqID, network.ErrorReasonBlockedByClient).Do(cdp.WithExecutor(tCtx, chromedp.FromContext(tCtx).Target))
return
}
}
- _ = fetch.ContinueRequest(reqID).Do(cdp.WithExecutor(tabCtx, chromedp.FromContext(tabCtx).Target))
+ _ = fetch.ContinueRequest(reqID).Do(cdp.WithExecutor(tCtx, chromedp.FromContext(tCtx).Target))
}()
case *network.EventRequestWillBeSent:
if e.Type != network.ResourceTypeDocument {
return
}
+ mu.Lock()
if mainFrameID == "" {
mainFrameID = e.FrameID
}
if e.FrameID == mainFrameID {
requestID = e.RequestID
}
+ mu.Unlock()
case *network.EventResponseReceived:
- if e.RequestID == requestID && requestID != "" {
- requestID = e.RequestID
+ mu.Lock()
+ match := e.RequestID == requestID && requestID != ""
+ if match {
responseMIME = e.Response.MimeType
responseStatus = int(e.Response.Status)
+ }
+ mu.Unlock()
+ if match {
if opts.IsDomainAllowed != nil && !opts.IsDomainAllowed(e.Response.URL) {
if opts.ValidateRemoteIP != nil {
if err := opts.ValidateRemoteIP(e.Response.RemoteIPAddress); err != nil {
@@ -136,7 +187,7 @@ func (b *Bridge) DownloadURL(ctx context.Context, dlURL string, opts DownloadOpt
}
if opts.MaxBytes > 0 && opts.ParseContentLength != nil {
if contentLength, ok := opts.ParseContentLength(e.Response.Headers); ok && contentLength > int64(opts.MaxBytes) {
- noteBlocked(fmt.Errorf("download response too large: received %d bytes, max %d", contentLength, opts.MaxBytes))
+ noteBlocked(fmt.Errorf("%w: received %d bytes, max %d", ErrDownloadTooLarge, contentLength, opts.MaxBytes))
select {
case done <- struct{}{}:
default:
@@ -147,13 +198,13 @@ func (b *Bridge) DownloadURL(ctx context.Context, dlURL string, opts DownloadOpt
}
}
case *network.EventDataReceived:
- if e.RequestID == requestID && requestID != "" {
+ if isMainRequest(e.RequestID) {
chunk := e.EncodedDataLength
if chunk <= 0 {
chunk = e.DataLength
}
if opts.MaxBytes > 0 && chunk > 0 && receivedBytes.Add(chunk) > int64(opts.MaxBytes) {
- noteBlocked(fmt.Errorf("download response too large: received %d bytes, max %d", receivedBytes.Load(), opts.MaxBytes))
+ noteBlocked(fmt.Errorf("%w: received %d bytes, max %d", ErrDownloadTooLarge, receivedBytes.Load(), opts.MaxBytes))
select {
case done <- struct{}{}:
default:
@@ -163,14 +214,14 @@ func (b *Bridge) DownloadURL(ctx context.Context, dlURL string, opts DownloadOpt
}
}
case *network.EventLoadingFinished:
- if e.RequestID == requestID && requestID != "" {
+ if isMainRequest(e.RequestID) {
select {
case done <- struct{}{}:
default:
}
}
case *network.EventLoadingFailed:
- if e.RequestID == requestID && requestID != "" {
+ if isMainRequest(e.RequestID) {
select {
case done <- struct{}{}:
default:
@@ -179,15 +230,18 @@ func (b *Bridge) DownloadURL(ctx context.Context, dlURL string, opts DownloadOpt
}
})
- if err := chromedp.Run(tabCtx, network.Enable()); err != nil {
+ if err := chromedp.Run(tCtx, network.Enable()); err != nil {
return nil, fmt.Errorf("network enable: %w", err)
}
- navErr := chromedp.Run(tabCtx, chromedp.Navigate(dlURL))
+ navErr := chromedp.Run(tCtx, chromedp.Navigate(dlURL))
if navErr != nil {
if bErr := getBlockedErr(); bErr != nil {
return nil, bErr
}
+ if tCtx.Err() != nil {
+ return nil, ErrDownloadTimeout
+ }
return nil, navErr
}
@@ -197,23 +251,29 @@ func (b *Bridge) DownloadURL(ctx context.Context, dlURL string, opts DownloadOpt
if bErr := getBlockedErr(); bErr != nil {
return nil, bErr
}
- return nil, fmt.Errorf("download timed out")
+ return nil, ErrDownloadTimeout
}
if bErr := getBlockedErr(); bErr != nil {
return nil, bErr
}
- if responseStatus >= 400 {
- return &DownloadResult{StatusCode: responseStatus, MIMEType: responseMIME}, fmt.Errorf("remote server returned HTTP %d", responseStatus)
+ mu.Lock()
+ reqID := requestID
+ respMIME := responseMIME
+ respStatus := responseStatus
+ mu.Unlock()
+
+ if respStatus >= 400 {
+ return &DownloadResult{StatusCode: respStatus, MIMEType: respMIME}, fmt.Errorf("remote server returned HTTP %d", respStatus)
}
- if requestID == "" {
+ if reqID == "" {
return nil, fmt.Errorf("download response was not captured")
}
var body []byte
- if err := chromedp.Run(tabCtx, chromedp.ActionFunc(func(ctx context.Context) error {
- b, err := network.GetResponseBody(requestID).Do(ctx)
+ if err := chromedp.Run(tCtx, chromedp.ActionFunc(func(ctx context.Context) error {
+ b, err := network.GetResponseBody(reqID).Do(ctx)
if err != nil {
return err
}
@@ -225,7 +285,7 @@ func (b *Bridge) DownloadURL(ctx context.Context, dlURL string, opts DownloadOpt
return &DownloadResult{
Body: body,
- MIMEType: responseMIME,
- StatusCode: responseStatus,
+ MIMEType: respMIME,
+ StatusCode: respStatus,
}, nil
}
diff --git a/internal/bridge/download_test.go b/internal/bridge/download_test.go
new file mode 100644
index 00000000..4548f9e6
--- /dev/null
+++ b/internal/bridge/download_test.go
@@ -0,0 +1,27 @@
+package bridge
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+)
+
+// Regression guard for the lost-deadline bug: DownloadURL must fail fast on a
+// dead browser context instead of blocking past its caps (it once navigated
+// on an unbounded tab context and could hang until Chrome's own timeouts).
+func TestDownloadURL_FailsFastOnDeadBrowserContext(t *testing.T) {
+ parent, cancel := chromedp.NewContext(context.Background())
+ cancel()
+
+ b := &Bridge{BrowserCtx: parent}
+ start := time.Now()
+ _, err := b.DownloadURL(context.Background(), "https://example.com/file", DownloadOpts{})
+ if err == nil {
+ t.Fatal("expected error on dead browser context")
+ }
+ if elapsed := time.Since(start); elapsed > 5*time.Second {
+ t.Fatalf("DownloadURL blocked for %v on a dead context", elapsed)
+ }
+}
diff --git a/internal/bridge/init_test.go b/internal/bridge/init_test.go
index ba1980a0..79261c00 100644
--- a/internal/bridge/init_test.go
+++ b/internal/bridge/init_test.go
@@ -44,7 +44,6 @@ func TestBuildBrowserArgsHeadlessUsesSoftwareRendering(t *testing.T) {
for _, want := range []string{
"--headless=new",
- "--disable-gpu",
"--disable-vulkan",
"--use-angle=swiftshader",
"--enable-unsafe-swiftshader",
@@ -53,6 +52,11 @@ func TestBuildBrowserArgsHeadlessUsesSoftwareRendering(t *testing.T) {
t.Fatalf("missing headless browser arg %q in %v", want, args)
}
}
+ // --disable-gpu would remove the compositor backend that the swiftshader
+ // flags above provide; capture/print CDP calls then hang.
+ if slices.Contains(args, "--disable-gpu") {
+ t.Fatalf("headless args must not contain --disable-gpu: %v", args)
+ }
}
func TestBuildBrowserArgsIncludesGlobalUserAgent(t *testing.T) {
diff --git a/internal/bridge/profile_lock.go b/internal/bridge/profile_lock.go
index 0da6a4f9..8a5ab28f 100644
--- a/internal/bridge/profile_lock.go
+++ b/internal/bridge/profile_lock.go
@@ -124,6 +124,10 @@ func clearStaleProfileLocks(profileDir, errMsg string) (bool, error) {
return removed, nil
}
+// quarantineExitWait bounds how long quarantine waits for the dying browser
+// to release the profile before renaming. Var so tests can shrink it.
+var quarantineExitWait = 5 * time.Second
+
// quarantineCorruptedProfile renames profileDir to "<profileDir>.quarantine-<ts>"
// and recreates an empty directory at the original path. Used to recover
// from silent CDP attach failures where CloakBrowser refuses to ingest
@@ -139,11 +143,18 @@ func quarantineCorruptedProfile(profileDir string) (string, error) {
}
return "", fmt.Errorf("stat profile dir: %w", err)
}
+ // The caller cancels chromedp contexts without waiting for the process to
+ // exit; renaming under a still-running browser fails on Windows and lets
+ // the old process keep writing into the quarantined dir on POSIX. On
+ // timeout, proceed anyway — refusing entirely would block recovery.
+ if !waitForChromeExit(profileDir, quarantineExitWait) {
+ slog.Warn("quarantining profile while a browser process may still hold it", "profile", profileDir)
+ }
quarantinePath := fmt.Sprintf("%s.quarantine-%d", profileDir, time.Now().Unix())
if err := os.Rename(profileDir, quarantinePath); err != nil {
return "", fmt.Errorf("rename profile dir: %w", err)
}
- if err := os.MkdirAll(profileDir, 0755); err != nil {
+ if err := os.MkdirAll(profileDir, 0700); err != nil {
return quarantinePath, fmt.Errorf("recreate profile dir: %w", err)
}
return quarantinePath, nil
diff --git a/internal/bridge/profile_lock_test.go b/internal/bridge/profile_lock_test.go
index cf2dae09..e4a470f5 100644
--- a/internal/bridge/profile_lock_test.go
+++ b/internal/bridge/profile_lock_test.go
@@ -316,3 +316,77 @@ func TestIsProfileOwnedByRunningPinchtabKeepsLockWhenChromeUsesProfile(t *testin
t.Fatalf("expected profile with active chrome to stay locked, got owned=%v pid=%d", owned, pid)
}
}
+
+// M11 regression: quarantine must wait for the dying browser to release the
+// profile before renaming, proceed anyway after the bounded wait times out,
+// and recreate the dir with 0700.
+func TestQuarantineCorruptedProfile_WaitsForBrowserExit(t *testing.T) {
+ profileDir := filepath.Join(t.TempDir(), "profile")
+ if err := os.MkdirAll(profileDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+
+ oldFind := findChromePIDsByProfileDirFunc
+ oldWait := quarantineExitWait
+ oldPoll := chromeExitPollInterval
+ quarantineExitWait = 20 * time.Millisecond
+ chromeExitPollInterval = 5 * time.Millisecond
+ calls := 0
+ findChromePIDsByProfileDirFunc = func(dir string) []int {
+ calls++
+ if calls < 2 {
+ return []int{4242} // first poll: browser still holds the profile
+ }
+ return nil
+ }
+ t.Cleanup(func() {
+ findChromePIDsByProfileDirFunc = oldFind
+ quarantineExitWait = oldWait
+ chromeExitPollInterval = oldPoll
+ })
+
+ quarantinePath, err := quarantineCorruptedProfile(profileDir)
+ if err != nil {
+ t.Fatalf("quarantineCorruptedProfile: %v", err)
+ }
+ if calls < 2 {
+ t.Fatalf("expected quarantine to poll for browser exit, polls=%d", calls)
+ }
+ if quarantinePath == "" {
+ t.Fatal("expected quarantine to proceed after the browser exited")
+ }
+ info, err := os.Stat(profileDir)
+ if err != nil {
+ t.Fatalf("recreated profile dir missing: %v", err)
+ }
+ if perm := info.Mode().Perm(); perm != 0o700 {
+ t.Fatalf("recreated profile dir perms = %o, want 0700", perm)
+ }
+}
+
+func TestQuarantineCorruptedProfile_ProceedsAfterWaitTimeout(t *testing.T) {
+ profileDir := filepath.Join(t.TempDir(), "profile")
+ if err := os.MkdirAll(profileDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+
+ oldFind := findChromePIDsByProfileDirFunc
+ oldWait := quarantineExitWait
+ oldPoll := chromeExitPollInterval
+ quarantineExitWait = 10 * time.Millisecond
+ chromeExitPollInterval = 2 * time.Millisecond
+ findChromePIDsByProfileDirFunc = func(dir string) []int { return []int{4242} } // never exits
+ t.Cleanup(func() {
+ findChromePIDsByProfileDirFunc = oldFind
+ quarantineExitWait = oldWait
+ chromeExitPollInterval = oldPoll
+ })
+
+ quarantinePath, err := quarantineCorruptedProfile(profileDir)
+ if err != nil {
+ t.Fatalf("quarantine should proceed (with a warning) after the wait times out: %v", err)
+ }
+ if quarantinePath == "" {
+ t.Fatal("expected a quarantine path despite the timed-out wait")
+ }
+}
diff --git a/internal/bridge/route.go b/internal/bridge/route.go
index 1fbb4f36..7956f1cb 100644
--- a/internal/bridge/route.go
+++ b/internal/bridge/route.go
@@ -190,6 +190,13 @@ type RouteManager struct {
mu sync.Mutex
perTab map[string]*tabRouteState
allowedDomainsFn func() []string // nil ⇒ no allowlist enforcement
+
+ // Fetch-domain coordination with proxy auth (see Bridge.tabSetup): while
+ // rules own a tab's Fetch domain, the proxy-auth listener's blanket
+ // ContinueRequest is suppressed and the route enable must keep
+ // handleAuthRequests so challenges stay answerable.
+ proxyAuthActive func() bool // nil ⇒ no proxy auth configured
+ setPauseSuppressed func(tabID string, v bool) // nil ⇒ no coordination
}
// tabRouteState holds per-tab interception state. listenCtx, when non-nil, is
@@ -211,6 +218,27 @@ func NewRouteManager(allowedDomainsFn func() []string) *RouteManager {
return &RouteManager{perTab: make(map[string]*tabRouteState), allowedDomainsFn: allowedDomainsFn}
}
+// SetFetchAuthCoordination wires the proxy-auth coordination callbacks: the
+// gate reporting whether proxy credentials are configured, and the per-tab
+// pause-suppression setter on the owning Bridge.
+func (rm *RouteManager) SetFetchAuthCoordination(proxyAuthActive func() bool, setPauseSuppressed func(tabID string, v bool)) {
+ if rm == nil {
+ return
+ }
+ rm.proxyAuthActive = proxyAuthActive
+ rm.setPauseSuppressed = setPauseSuppressed
+}
+
+func (rm *RouteManager) proxyAuthOn() bool {
+ return rm.proxyAuthActive != nil && rm.proxyAuthActive()
+}
+
+func (rm *RouteManager) suppressPause(tabID string, v bool) {
+ if rm.setPauseSuppressed != nil {
+ rm.setPauseSuppressed(tabID, v)
+ }
+}
+
// MaxFulfillBodyBytes caps the size of a fulfill rule's response body. The
// HTTP handler enforces this for early 400s; AddRule re-checks so non-HTTP
// callers (direct bridge users, future ipc) also benefit.
@@ -351,11 +379,18 @@ func (rm *RouteManager) AddRule(ctx context.Context, tabID string, rule RouteRul
rm.registerListener(listenCtx, tabID)
}
if needEnable {
+ // Suppress the proxy-auth listener's blanket continue BEFORE rules
+ // take over dispatch, and keep handleAuthRequests on so proxy
+ // challenges stay answerable while routes own the Fetch domain.
+ rm.suppressPause(tabID, true)
+ handleAuth := rm.proxyAuthOn()
if err := chromedp.Run(ctx, chromedp.ActionFunc(func(c context.Context) error {
return fetch.Enable().
WithPatterns([]*fetch.RequestPattern{{URLPattern: "*"}}).
+ WithHandleAuthRequests(handleAuth).
Do(c)
})); err != nil {
+ rm.suppressPause(tabID, false)
rm.rollbackAddRule(tabID, isNewState, needRegister, priorRules, priorListenCtx, priorListenCancel, priorFetchEnabled)
return fmt.Errorf("fetch.enable: %w", err)
}
@@ -442,11 +477,26 @@ func (rm *RouteManager) Remove(ctx context.Context, tabID string, pattern string
if teardown {
if wasEnabled {
- if err := chromedp.Run(ctx, chromedp.ActionFunc(func(c context.Context) error {
- return fetch.Disable().Do(c)
- })); err != nil {
- slog.Debug("fetch.disable failed during route teardown", "tabId", tabID, "err", err)
+ if rm.proxyAuthOn() {
+ // Hand the Fetch domain back to proxy auth instead of
+ // disabling it (which would kill auth handling too).
+ // Unsuppress first so no paused request goes unanswered.
+ rm.suppressPause(tabID, false)
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(c context.Context) error {
+ return fetch.Enable().WithHandleAuthRequests(true).Do(c)
+ })); err != nil {
+ slog.Debug("fetch re-enable for proxy auth failed during route teardown", "tabId", tabID, "err", err)
+ }
+ } else {
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(c context.Context) error {
+ return fetch.Disable().Do(c)
+ })); err != nil {
+ slog.Debug("fetch.disable failed during route teardown", "tabId", tabID, "err", err)
+ }
+ rm.suppressPause(tabID, false)
}
+ } else {
+ rm.suppressPause(tabID, false)
}
if cancel != nil {
cancel()
@@ -475,6 +525,10 @@ func (rm *RouteManager) RemoveTab(tabID string) {
cancel := state.listenCancel
delete(rm.perTab, tabID)
rm.mu.Unlock()
+ // Hand pause dispatch back even though the Bridge drops the whole flag in
+ // its own onTabRemoved hook right after — RemoveTab must stay correct on
+ // its own, not by courtesy of the caller's cleanup ordering.
+ rm.suppressPause(tabID, false)
if cancel != nil {
cancel()
}
diff --git a/internal/bridge/route_test.go b/internal/bridge/route_test.go
index 68bf84aa..820d63b1 100644
--- a/internal/bridge/route_test.go
+++ b/internal/bridge/route_test.go
@@ -1,9 +1,12 @@
package bridge
import (
+ "context"
"errors"
"fmt"
"testing"
+
+ "github.com/chromedp/chromedp"
)
func TestGlobMatch(t *testing.T) {
@@ -700,3 +703,50 @@ func TestRouteManager_AddRule_Validation(t *testing.T) {
t.Error("expected error for invalid action")
}
}
+
+// M16: route teardown must release the proxy-auth pause suppression even
+// when Fetch was never enabled (no CDP call path).
+func TestRouteManager_TeardownReleasesPauseSuppression(t *testing.T) {
+ rm := NewRouteManager(nil)
+ var calls []string
+ rm.SetFetchAuthCoordination(
+ func() bool { return true },
+ func(tabID string, v bool) { calls = append(calls, fmt.Sprintf("%s=%v", tabID, v)) },
+ )
+
+ rm.mu.Lock()
+ rm.perTab["tab1"] = &tabRouteState{rules: []RouteRule{
+ {Pattern: "*.png", Action: RouteActionAbort},
+ }}
+ rm.mu.Unlock()
+
+ if _, err := rm.Remove(t.Context(), "tab1", ""); err != nil {
+ t.Fatalf("remove: %v", err)
+ }
+ if len(calls) != 1 || calls[0] != "tab1=false" {
+ t.Fatalf("teardown should unsuppress exactly once, got %v", calls)
+ }
+}
+
+// M16: a failed Fetch enable must roll the suppression back so the
+// proxy-auth listener resumes continuing paused requests.
+func TestRouteManager_FailedEnableRollsBackSuppression(t *testing.T) {
+ rm := NewRouteManager(nil)
+ var calls []string
+ rm.SetFetchAuthCoordination(
+ func() bool { return true },
+ func(tabID string, v bool) { calls = append(calls, fmt.Sprintf("%s=%v", tabID, v)) },
+ )
+
+ // A canceled chromedp context makes fetch.Enable fail deterministically.
+ parent, cancel := chromedp.NewContext(context.Background())
+ cancel()
+
+ err := rm.AddRule(parent, "tab1", RouteRule{Pattern: "*.png", Action: RouteActionAbort})
+ if err == nil {
+ t.Fatal("expected enable failure on dead chromedp context")
+ }
+ if len(calls) != 2 || calls[0] != "tab1=true" || calls[1] != "tab1=false" {
+ t.Fatalf("expected suppress-then-rollback, got %v", calls)
+ }
+}
diff --git a/internal/bridge/tab_adopt.go b/internal/bridge/tab_adopt.go
index 42c4a714..abc215f2 100644
--- a/internal/bridge/tab_adopt.go
+++ b/internal/bridge/tab_adopt.go
@@ -38,7 +38,7 @@ func (tm *TabManager) tabBlockPatterns() []string {
func (tm *TabManager) setupManagedTarget(ctx context.Context, tabID, rawCDPID string) bool {
if tm.onTabSetup != nil {
- tm.onTabSetup(ctx)
+ tm.onTabSetup(ctx, tabID)
}
if blockPatterns := tm.tabBlockPatterns(); len(blockPatterns) > 0 {
if err := SetResourceBlocking(ctx, blockPatterns); err != nil {
diff --git a/internal/bridge/tab_cleanup.go b/internal/bridge/tab_cleanup.go
index 64c65041..f4081295 100644
--- a/internal/bridge/tab_cleanup.go
+++ b/internal/bridge/tab_cleanup.go
@@ -132,6 +132,9 @@ func (tm *TabManager) purgeTrackedTabState(tabID, cdpTargetID string) bool {
if tm.routeMgr != nil {
tm.routeMgr.RemoveTab(resolvedTabID)
}
+ if tm.onTabRemoved != nil {
+ tm.onTabRemoved(resolvedTabID)
+ }
// Notify listeners (e.g. session persistence) that a tab disappeared,
// regardless of whether the trigger was a deliberate CloseTab, an eviction,
// the auto-close lifecycle timer, or Chrome reporting the target gone
diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.go
index 958e51a8..39abbcb7 100644
--- a/internal/bridge/tab_manager.go
+++ b/internal/bridge/tab_manager.go
@@ -15,7 +15,7 @@ import (
"github.com/pinchtab/pinchtab/internal/ids"
)
-type TabSetupFunc func(ctx context.Context)
+type TabSetupFunc func(ctx context.Context, tabID string)
type TabManager struct {
browserCtx context.Context
@@ -30,6 +30,7 @@ type TabManager struct {
dialogMgr *DialogManager
logStore *ConsoleLogStore
routeMgr *RouteManager
+ onTabRemoved func(tabID string)
netMonitor *NetworkMonitor
currentTab string // ID of the most recently used tab
executor *TabExecutor
@@ -91,6 +92,12 @@ func (tm *TabManager) SetRouteManager(rm *RouteManager) {
tm.routeMgr = rm
}
+// SetOnTabRemoved registers a per-tab cleanup callback fired alongside the
+// route/log/executor cleanup whenever a tracked tab is removed.
+func (tm *TabManager) SetOnTabRemoved(fn func(tabID string)) {
+ tm.onTabRemoved = fn
+}
+
// browserExecutorContext returns a context bound to the top-level browser
// executor, suitable for issuing browser-scoped CDP calls (e.g. target.*).
// Shared helper used by tab lifecycle, lookup, popup-guard, and cleanup paths.
@@ -157,17 +164,17 @@ func (tm *TabManager) CreateTab(url string) (string, context.Context, context.Ca
chromedp.WithTargetID(targetID),
)
+ rawCDPID := string(targetID)
+ tabID := tm.idMgr.TabIDFromCDPTarget(rawCDPID)
+
if tm.onTabSetup != nil {
- tm.onTabSetup(ctx)
+ tm.onTabSetup(ctx, tabID)
}
if blockPatterns := tm.tabBlockPatterns(); len(blockPatterns) > 0 {
_ = SetResourceBlocking(ctx, blockPatterns)
}
- rawCDPID := string(targetID)
- tabID := tm.idMgr.TabIDFromCDPTarget(rawCDPID)
-
// Start network capture before navigation so CDP events are captured.
if tm.netMonitor != nil {
if err := tm.netMonitor.StartCapture(ctx, tabID); err != nil {