Skip to content

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

feat: capture console logs on cloak via a console domain fallback session

Luigi Agostid9a7f6053487
diff --git a/docs/guides/cloakbrowser.md b/docs/guides/cloakbrowser.md
index 5a2aa902..d4d6463e 100644
--- a/docs/guides/cloakbrowser.md
+++ b/docs/guides/cloakbrowser.md
@@ -28,6 +28,18 @@ headless/headed mode, remote debugging, tab limits, and action humanization.
PinchTab does not bundle CloakBrowser in release binaries, npm packages,
Homebrew formulae, or the default published Docker image.
+### Console log capture
+
+CloakBrowser's native patches suppress CDP `Runtime` domain events after the
+first navigation (enabling that domain is a well-known bot-detection vector),
+so the standard `Runtime.consoleAPICalled` stream PinchTab uses on Chrome
+never delivers page console output. PinchTab detects this via the browser
+capability registry and instead attaches a second, read-only CDP session per
+tab that listens on the deprecated-but-functional `Console` domain. Console
+logs (`/console`, audit `consoleLogs`) and uncaught page errors (`/errors`)
+work on Cloak through that fallback. Nothing is injected into the page, so
+the fallback adds no fingerprint surface.
+
## Licensing
CloakBrowser has two relevant pieces:
diff --git a/internal/bridge/console_capture.go b/internal/bridge/console_capture.go
index 5fa8a24c..14edd8f7 100644
--- a/internal/bridge/console_capture.go
+++ b/internal/bridge/console_capture.go
@@ -20,6 +20,12 @@ func (tm *TabManager) setupConsoleCapture(ctx context.Context, rawCDPID string)
execContextSources := make(map[runtime.ExecutionContextID]string)
var execContextMu sync.RWMutex
+ // Browsers whose native stealth patches suppress Runtime domain events
+ // (no CapRuntimeConsoleEvents) record through the Console domain side
+ // session instead; the chromedp listener below must then stay silent so
+ // the buffered replay Runtime.enable still emits is not double-recorded.
+ recordViaRuntime := tm.runtimeConsoleEventsSupported()
+
chromedp.ListenTarget(ctx, func(ev any) {
switch ev := ev.(type) {
case *runtime.EventExecutionContextCreated:
@@ -41,6 +47,9 @@ func (tm *TabManager) setupConsoleCapture(ctx context.Context, rawCDPID string)
execContextMu.Unlock()
case *runtime.EventConsoleAPICalled:
+ if !recordViaRuntime {
+ return
+ }
var msg string
for _, arg := range ev.Args {
if len(arg.Value) > 0 {
@@ -83,6 +92,9 @@ func (tm *TabManager) setupConsoleCapture(ctx context.Context, rawCDPID string)
})
case *runtime.EventExceptionThrown:
+ if !recordViaRuntime {
+ return
+ }
msg := ev.ExceptionDetails.Text
if ev.ExceptionDetails.Exception != nil && ev.ExceptionDetails.Exception.Description != "" {
msg += ": " + ev.ExceptionDetails.Exception.Description
@@ -132,6 +144,10 @@ func (tm *TabManager) setupConsoleCapture(ctx context.Context, rawCDPID string)
_ = chromedp.Run(enableCtx, chromedp.ActionFunc(func(c context.Context) error {
return runtime.Enable().Do(c)
}))
+
+ if !recordViaRuntime {
+ go tm.runConsoleDomainFallback(ctx, rawCDPID)
+ }
}
// runtimeEnableTimeout bounds the synchronous Runtime.enable in
diff --git a/internal/bridge/console_domain_fallback.go b/internal/bridge/console_domain_fallback.go
new file mode 100644
index 00000000..e2706eae
--- /dev/null
+++ b/internal/bridge/console_domain_fallback.go
@@ -0,0 +1,186 @@
+package bridge
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "net"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/gobwas/ws"
+ "github.com/gobwas/ws/wsutil"
+ "github.com/pinchtab/pinchtab/internal/browsers"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+// The Console domain fallback captures page console output for browsers
+// without CapRuntimeConsoleEvents (e.g. CloakBrowser). Those builds natively
+// suppress Runtime.consoleAPICalled / Runtime.exceptionThrown after the first
+// navigation because Runtime.enable is a bot-detection vector, so the
+// chromedp listener in setupConsoleCapture never sees page logs. The
+// deprecated CDP Console domain is not patched and keeps delivering
+// Console.messageAdded across navigations, so we attach a second, read-only
+// CDP session to the tab's target and record from there. The extra session is
+// pure CDP — nothing is injected into the page, so it adds no fingerprint
+// surface the stealth build tries to remove.
+const (
+ consoleFallbackDialAttempts = 3
+ consoleFallbackDialBackoff = 500 * time.Millisecond
+ consoleFallbackDialTimeout = 5 * time.Second
+)
+
+func (tm *TabManager) runtimeConsoleEventsSupported() bool {
+ if tm == nil || tm.config == nil {
+ return true
+ }
+ if b, ok := browsers.Get(config.NormalizeBrowser(tm.config.DefaultBrowser)); ok {
+ return b.Capabilities().Has(browsers.CapRuntimeConsoleEvents)
+ }
+ return true
+}
+
+// consoleDomainEndpoint resolves the per-target DevTools WebSocket URL for the
+// fallback session: the launched browser's resolved debug port, or the attach
+// URL's host when PinchTab attached to an external browser.
+func consoleDomainEndpoint(cfg *config.RuntimeConfig, targetID string) (string, error) {
+ if cfg == nil {
+ return "", fmt.Errorf("no runtime config")
+ }
+ if cfg.BrowserDebugPort > 0 {
+ return fmt.Sprintf("ws://127.0.0.1:%d/devtools/page/%s", cfg.BrowserDebugPort, targetID), nil
+ }
+ if attach := strings.TrimSpace(cfg.CDPAttachURL); attach != "" {
+ u, err := url.Parse(attach)
+ if err != nil {
+ return "", fmt.Errorf("parse cdp attach url: %w", err)
+ }
+ scheme := "ws"
+ if u.Scheme == "wss" || u.Scheme == "https" {
+ scheme = "wss"
+ }
+ return fmt.Sprintf("%s://%s/devtools/page/%s", scheme, u.Host, targetID), nil
+ }
+ return "", fmt.Errorf("no devtools endpoint available")
+}
+
+type consoleDomainMessage struct {
+ Source string `json:"source"`
+ Level string `json:"level"`
+ Text string `json:"text"`
+ URL string `json:"url"`
+ Line int64 `json:"line"`
+ Column int64 `json:"column"`
+}
+
+// parseConsoleDomainEvent extracts the message from a raw Console.messageAdded
+// frame. The second return is false for every other CDP frame (command
+// replies, other events).
+func parseConsoleDomainEvent(data []byte) (consoleDomainMessage, bool) {
+ var envelope struct {
+ Method string `json:"method"`
+ Params struct {
+ Message consoleDomainMessage `json:"message"`
+ } `json:"params"`
+ }
+ if err := json.Unmarshal(data, &envelope); err != nil {
+ return consoleDomainMessage{}, false
+ }
+ if envelope.Method != "Console.messageAdded" {
+ return consoleDomainMessage{}, false
+ }
+ return envelope.Params.Message, true
+}
+
+// recordConsoleDomainMessage mirrors the Runtime-listener semantics: console
+// API calls feed the console store, uncaught page errors feed the error
+// store, everything else (network/violation/deprecation noise that the
+// Runtime path never recorded) is dropped.
+func (tm *TabManager) recordConsoleDomainMessage(rawCDPID string, msg consoleDomainMessage) {
+ if isInternalConsoleSource(msg.URL) {
+ return
+ }
+ switch msg.Source {
+ case "console-api":
+ tm.logStore.AddConsoleLog(rawCDPID, LogEntry{
+ Timestamp: time.Now(),
+ Level: msg.Level,
+ Message: msg.Text,
+ Source: msg.URL,
+ })
+ case "javascript":
+ if msg.Level != "error" {
+ return
+ }
+ tm.logStore.AddErrorLog(rawCDPID, ErrorEntry{
+ Timestamp: time.Now(),
+ Message: msg.Text,
+ URL: msg.URL,
+ Line: msg.Line,
+ Column: msg.Column,
+ })
+ }
+}
+
+// runConsoleDomainFallback owns the side session for one tab: dial, enable
+// the Console domain (Chrome replays buffered messages on enable), then pump
+// events into the log store until the tab context ends or the socket drops.
+func (tm *TabManager) runConsoleDomainFallback(ctx context.Context, rawCDPID string) {
+ endpoint, err := consoleDomainEndpoint(tm.config, rawCDPID)
+ if err != nil {
+ slog.Debug("console domain fallback unavailable", "tab", rawCDPID, "error", err)
+ return
+ }
+
+ var conn net.Conn
+ for attempt := 1; ; attempt++ {
+ dialCtx, cancel := context.WithTimeout(ctx, consoleFallbackDialTimeout)
+ c, _, _, dialErr := ws.Dial(dialCtx, endpoint)
+ cancel()
+ if dialErr == nil {
+ conn = c
+ break
+ }
+ if attempt >= consoleFallbackDialAttempts || ctx.Err() != nil {
+ slog.Warn("console domain fallback dial failed; page console logs will be missing for this tab",
+ "tab", rawCDPID, "error", dialErr)
+ return
+ }
+ select {
+ case <-ctx.Done():
+ return
+ case <-time.After(consoleFallbackDialBackoff):
+ }
+ }
+
+ // Unblock the read loop when the tab goes away.
+ done := make(chan struct{})
+ defer close(done)
+ go func() {
+ select {
+ case <-ctx.Done():
+ case <-done:
+ }
+ _ = conn.Close()
+ }()
+
+ if err := wsutil.WriteClientText(conn, []byte(`{"id":1,"method":"Console.enable"}`)); err != nil {
+ slog.Warn("console domain fallback enable failed", "tab", rawCDPID, "error", err)
+ return
+ }
+
+ for {
+ data, err := wsutil.ReadServerText(conn)
+ if err != nil {
+ if ctx.Err() == nil {
+ slog.Debug("console domain fallback session ended", "tab", rawCDPID, "error", err)
+ }
+ return
+ }
+ if msg, ok := parseConsoleDomainEvent(data); ok {
+ tm.recordConsoleDomainMessage(rawCDPID, msg)
+ }
+ }
+}
diff --git a/internal/bridge/console_domain_fallback_test.go b/internal/bridge/console_domain_fallback_test.go
new file mode 100644
index 00000000..d470f96a
--- /dev/null
+++ b/internal/bridge/console_domain_fallback_test.go
@@ -0,0 +1,138 @@
+package bridge
+
+import (
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestParseConsoleDomainEvent(t *testing.T) {
+ tests := []struct {
+ name string
+ data string
+ wantOK bool
+ wantMsg consoleDomainMessage
+ }{
+ {
+ name: "console-api message",
+ data: `{"method":"Console.messageAdded","params":{"message":{"source":"console-api","level":"warning","text":"late-warn","url":"http://localhost:8088/console.html","line":6,"column":32}}}`,
+ wantOK: true,
+ wantMsg: consoleDomainMessage{
+ Source: "console-api",
+ Level: "warning",
+ Text: "late-warn",
+ URL: "http://localhost:8088/console.html",
+ Line: 6,
+ Column: 32,
+ },
+ },
+ {
+ name: "command reply ignored",
+ data: `{"id":1,"result":{}}`,
+ wantOK: false,
+ },
+ {
+ name: "other event ignored",
+ data: `{"method":"Console.messagesCleared","params":{}}`,
+ wantOK: false,
+ },
+ {
+ name: "malformed frame ignored",
+ data: `{"method":`,
+ wantOK: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ msg, ok := parseConsoleDomainEvent([]byte(tt.data))
+ if ok != tt.wantOK {
+ t.Fatalf("ok = %v, want %v", ok, tt.wantOK)
+ }
+ if ok && msg != tt.wantMsg {
+ t.Errorf("msg = %+v, want %+v", msg, tt.wantMsg)
+ }
+ })
+ }
+}
+
+func TestRecordConsoleDomainMessage(t *testing.T) {
+ tm := &TabManager{logStore: NewConsoleLogStore(100)}
+
+ tm.recordConsoleDomainMessage("tab1", consoleDomainMessage{
+ Source: "console-api", Level: "error", Text: "boom", URL: "http://site/app.js",
+ })
+ tm.recordConsoleDomainMessage("tab1", consoleDomainMessage{
+ Source: "javascript", Level: "error", Text: "Uncaught TypeError", URL: "http://site/app.js", Line: 3,
+ })
+ // Network noise and extension-internal sources never reach the stores.
+ tm.recordConsoleDomainMessage("tab1", consoleDomainMessage{
+ Source: "network", Level: "error", Text: "404",
+ })
+ tm.recordConsoleDomainMessage("tab1", consoleDomainMessage{
+ Source: "console-api", Level: "log", Text: "ext", URL: "chrome-extension://abc/bg.js",
+ })
+
+ logs := tm.logStore.GetConsoleLogs("tab1", 0)
+ if len(logs) != 1 {
+ t.Fatalf("console logs = %d, want 1 (%+v)", len(logs), logs)
+ }
+ if logs[0].Level != "error" || logs[0].Message != "boom" {
+ t.Errorf("unexpected console entry: %+v", logs[0])
+ }
+
+ errs := tm.logStore.GetErrorLogs("tab1", 0)
+ if len(errs) != 1 {
+ t.Fatalf("error logs = %d, want 1 (%+v)", len(errs), errs)
+ }
+ if errs[0].Message != "Uncaught TypeError" || errs[0].Line != 3 {
+ t.Errorf("unexpected error entry: %+v", errs[0])
+ }
+}
+
+func TestConsoleDomainEndpoint(t *testing.T) {
+ tests := []struct {
+ name string
+ cfg *config.RuntimeConfig
+ want string
+ wantErr bool
+ }{
+ {
+ name: "launched browser uses resolved debug port",
+ cfg: &config.RuntimeConfig{BrowserDebugPort: 9869},
+ want: "ws://127.0.0.1:9869/devtools/page/TARGET1",
+ },
+ {
+ name: "attach url host reused",
+ cfg: &config.RuntimeConfig{CDPAttachURL: "ws://10.0.0.5:9222/devtools/browser/abc"},
+ want: "ws://10.0.0.5:9222/devtools/page/TARGET1",
+ },
+ {
+ name: "secure attach upgrades to wss",
+ cfg: &config.RuntimeConfig{CDPAttachURL: "wss://remote:443/devtools/browser/abc"},
+ want: "wss://remote:443/devtools/page/TARGET1",
+ },
+ {
+ name: "no endpoint known",
+ cfg: &config.RuntimeConfig{},
+ wantErr: true,
+ },
+ {
+ name: "nil config",
+ cfg: nil,
+ wantErr: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := consoleDomainEndpoint(tt.cfg, "TARGET1")
+ if (err != nil) != tt.wantErr {
+ t.Fatalf("err = %v, wantErr %v", err, tt.wantErr)
+ }
+ if got != tt.want {
+ t.Errorf("endpoint = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
diff --git a/internal/bridge/runtime/init.go b/internal/bridge/runtime/init.go
index b241aa27..fbcba7bd 100644
--- a/internal/bridge/runtime/init.go
+++ b/internal/bridge/runtime/init.go
@@ -88,6 +88,11 @@ func InitBrowser(cfg *config.RuntimeConfig, bundle *stealth.Bundle, hooks Hooks)
slog.Error("browser initialization failed", "headless", cfg.Headless, "error", err.Error())
return nil, nil, nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to start browser: %w", err)
}
+ // Publish the resolved DevTools port (auto-picked when the config left it
+ // unset) so bridge features that open side CDP sessions — e.g. the Console
+ // domain fallback for browsers without CapRuntimeConsoleEvents — can reach
+ // the launched browser.
+ cfg.BrowserDebugPort = debugPort
if ProxyAuthEnabled(cfg.Proxy) {
if err := EnableProxyAuth(browserCtx, cfg.Proxy, nil); err != nil {
diff --git a/internal/browsers/all/all_test.go b/internal/browsers/all/all_test.go
index ff43973c..1166459f 100644
--- a/internal/browsers/all/all_test.go
+++ b/internal/browsers/all/all_test.go
@@ -104,9 +104,13 @@ func TestCloakCapabilitySupersetOfChrome(t *testing.T) {
cloakCaps := browsers.MustGet("cloak").Capabilities()
// Cloak intentionally lacks CapEventScreencast because its CDP proxy
- // does not support Page.startScreencast — polling is used instead.
+ // does not support Page.startScreencast — polling is used instead — and
+ // CapRuntimeConsoleEvents because its native patches suppress Runtime
+ // domain events (bot-detection hardening); the bridge uses the Console
+ // domain fallback instead.
chromeOnly := map[browsers.BrowserCapability]bool{
- browsers.CapEventScreencast: true,
+ browsers.CapEventScreencast: true,
+ browsers.CapRuntimeConsoleEvents: true,
}
for _, c := range chromeCaps {
diff --git a/internal/browsers/capabilities.go b/internal/browsers/capabilities.go
index 17a4064b..9c778132 100644
--- a/internal/browsers/capabilities.go
+++ b/internal/browsers/capabilities.go
@@ -13,6 +13,12 @@ const (
CapDownloads BrowserCapability = "downloads"
CapNetworkInterception BrowserCapability = "networkInterception"
CapEventScreencast BrowserCapability = "eventScreencast"
+ // CapRuntimeConsoleEvents marks browsers whose CDP Runtime domain delivers
+ // consoleAPICalled/exceptionThrown events after navigations. Stealth-patched
+ // builds (e.g. Cloak) natively suppress these events because Runtime.enable
+ // is a bot-detection vector; the bridge falls back to the deprecated Console
+ // domain on a side session for such browsers.
+ CapRuntimeConsoleEvents BrowserCapability = "runtimeConsoleEvents"
)
// CapabilitySet is an immutable set of BrowserCapability values.
diff --git a/internal/browsers/chrome/chrome.go b/internal/browsers/chrome/chrome.go
index 54c83825..2a48c97c 100644
--- a/internal/browsers/chrome/chrome.go
+++ b/internal/browsers/chrome/chrome.go
@@ -113,6 +113,7 @@ func (Browser) Capabilities() browsers.CapabilitySet {
browsers.CapDownloads,
browsers.CapNetworkInterception,
browsers.CapEventScreencast,
+ browsers.CapRuntimeConsoleEvents,
)
}
diff --git a/internal/browsers/chrome/chrome_test.go b/internal/browsers/chrome/chrome_test.go
index 2fefc8f1..81e3e091 100644
--- a/internal/browsers/chrome/chrome_test.go
+++ b/internal/browsers/chrome/chrome_test.go
@@ -50,6 +50,7 @@ func TestCapabilities(t *testing.T) {
browsers.CapDownloads,
browsers.CapNetworkInterception,
browsers.CapEventScreencast,
+ browsers.CapRuntimeConsoleEvents,
}
for _, c := range want {
diff --git a/internal/browsers/cloak/cloak_test.go b/internal/browsers/cloak/cloak_test.go
index ddba9405..bf4f56f6 100644
--- a/internal/browsers/cloak/cloak_test.go
+++ b/internal/browsers/cloak/cloak_test.go
@@ -61,6 +61,10 @@ func TestCapabilities(t *testing.T) {
t.Errorf("Capabilities().Has(%q) = false; want true", c)
}
}
+
+ if caps.Has(browsers.CapRuntimeConsoleEvents) {
+ t.Error("cloak should NOT have CapRuntimeConsoleEvents: its native patches suppress Runtime domain events")
+ }
}
func TestSupportsRemoteCDP(t *testing.T) {
diff --git a/internal/stealth/bundle_test.go b/internal/stealth/bundle_test.go
index f29c1abc..8d984b15 100644
--- a/internal/stealth/bundle_test.go
+++ b/internal/stealth/bundle_test.go
@@ -252,7 +252,7 @@ func TestStatusFromBundleEchoesProviderCapabilities(t *testing.T) {
t.Fatal("expected non-nil status")
return
}
- want := []string{"cdp", "downloads", "eventScreencast", "extensions", "headless", "networkInterception", "pdf"}
+ want := []string{"cdp", "downloads", "eventScreencast", "extensions", "headless", "networkInterception", "pdf", "runtimeConsoleEvents"}
if !equalStringSlices(status.ProviderCapabilities, want) {
t.Fatalf("chrome ProviderCapabilities = %v, want %v", status.ProviderCapabilities, want)
}