Skip to content

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

chore: move popup gurad and some dashboard changes (#377)

luigiagent1215401afa26
diff --git a/.gitignore b/.gitignore
index 290ce1f9..c6e46c9b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,10 +1,3 @@
-
-!dashboard/eslint.config.js
-!dashboard/vite.config.ts
-!internal/assets/*.js
-!npm/bin/pinchtab
-!scripts/**/*.js
-!tests/e2e/results/.gitkeep
# Build artifacts and test output
# E2E test results
# Go code serves a built-in fallback when these files are absent.
@@ -14,6 +7,12 @@
# npm package
# package-lock.json is committed for reproducible installs via npm ci
*.js
+!dashboard/eslint.config.js
+!dashboard/vite.config.ts
+!internal/assets/*.js
+!npm/bin/pinchtab
+!scripts/**/*.js
+!tests/e2e/results/.gitkeep
*.pyc
*.test
.DS_Store
diff --git a/internal/assets/assets.go b/internal/assets/assets.go
index c6b27440..61f5de74 100644
--- a/internal/assets/assets.go
+++ b/internal/assets/assets.go
@@ -7,6 +7,9 @@ import (
//go:embed stealth.js
var StealthScript string
+//go:embed popup_guard.js
+var PopupGuardScript string
+
//go:embed readability.js
var ReadabilityJS string
diff --git a/internal/assets/popup_guard.js b/internal/assets/popup_guard.js
new file mode 100644
index 00000000..dba3629a
--- /dev/null
+++ b/internal/assets/popup_guard.js
@@ -0,0 +1,54 @@
+(function() {
+ const _split = String.prototype.split;
+ const _map = Array.prototype.map;
+ const _filter = Array.prototype.filter;
+ const _push = Array.prototype.push;
+ const _join = Array.prototype.join;
+ const _trim = String.prototype.trim;
+ const _toLowerCase = String.prototype.toLowerCase;
+ const _call = Function.prototype.call;
+ const _defineProperty = Object.defineProperty;
+
+ const mergeWindowFeatures = function(features) {
+ const parts = typeof features === 'string'
+ ? _filter.call(_map.call(_split.call(features, ','), function(part) { return _trim.call(String(part)); }), function(x) { return !!x; })
+ : [];
+
+ let hasNoOpener = false;
+ let hasNoReferrer = false;
+ for (let i = 0; i < parts.length; i++) {
+ const lower = _toLowerCase.call(String(parts[i]));
+ if (lower === 'noopener') hasNoOpener = true;
+ if (lower === 'noreferrer') hasNoReferrer = true;
+ }
+
+ if (!hasNoOpener) _push.call(parts, 'noopener');
+ if (!hasNoReferrer) _push.call(parts, 'noreferrer');
+ return _join.call(parts, ',');
+ };
+
+ try {
+ const originalOpen = window.open;
+ if (typeof originalOpen === 'function') {
+ _defineProperty(window, 'open', {
+ configurable: false,
+ writable: false,
+ value: function(url, target, features) {
+ return _call.call(originalOpen, window, url, target, mergeWindowFeatures(features));
+ }
+ });
+ }
+ } catch (_) {}
+
+ try {
+ _defineProperty(window, 'opener', {
+ configurable: false,
+ get: function() { return null; },
+ set: function() { return true; }
+ });
+ } catch (_) {
+ try {
+ window.opener = null;
+ } catch (_) {}
+ }
+})();
diff --git a/internal/bridge/init.go b/internal/bridge/init.go
index c8fe5683..a4053c81 100644
--- a/internal/bridge/init.go
+++ b/internal/bridge/init.go
@@ -3,11 +3,12 @@ package bridge
import (
"context"
+ "github.com/pinchtab/pinchtab/internal/assets"
bridgeruntime "github.com/pinchtab/pinchtab/internal/bridge/runtime"
"github.com/pinchtab/pinchtab/internal/config"
)
-const popupGuardInitScript = bridgeruntime.PopupGuardInitScript
+var popupGuardInitScript = assets.PopupGuardScript
// InitChrome initializes a Chrome browser for a Bridge instance.
func InitChrome(cfg *config.RuntimeConfig) (context.Context, context.CancelFunc, context.Context, context.CancelFunc, error) {
diff --git a/internal/bridge/runtime/init.go b/internal/bridge/runtime/init.go
index 895e7ffc..3251d457 100644
--- a/internal/bridge/runtime/init.go
+++ b/internal/bridge/runtime/init.go
@@ -184,7 +184,7 @@ func startChromeWithRecovery(parentCtx context.Context, cfg *config.RuntimeConfi
if hooks.SetHumanRandSeed != nil {
hooks.SetHumanRandSeed(int64(stealthSeed))
}
- seededScript := fmt.Sprintf("var __pinchtab_seed = %d;\nvar __pinchtab_stealth_level = %q;\n", stealthSeed, cfg.StealthLevel) + assets.StealthScript + "\n" + PopupGuardInitScript
+ seededScript := fmt.Sprintf("var __pinchtab_seed = %d;\nvar __pinchtab_stealth_level = %q;\n", stealthSeed, cfg.StealthLevel) + assets.StealthScript + "\n" + assets.PopupGuardScript
const chromeStartupTimeout = 20 * time.Second
type runResult struct{ err error }
@@ -399,47 +399,6 @@ func BuildChromeArgs(cfg *config.RuntimeConfig, port int) []string {
return appendChromeCompatibilityFlags(args)
}
-const PopupGuardInitScript = `(function() {
- const mergeWindowFeatures = function(features) {
- const parts = typeof features === 'string'
- ? features.split(',').map(function(part) { return String(part).trim(); }).filter(Boolean)
- : [];
- const seen = new Set(parts.map(function(part) { return part.toLowerCase(); }));
- if (!seen.has('noopener')) {
- parts.push('noopener');
- }
- if (!seen.has('noreferrer')) {
- parts.push('noreferrer');
- }
- return parts.join(',');
- };
-
- try {
- const originalOpen = window.open;
- if (typeof originalOpen === 'function') {
- Object.defineProperty(window, 'open', {
- configurable: true,
- writable: true,
- value: function(url, target, features) {
- return originalOpen.call(window, url, target, mergeWindowFeatures(features));
- }
- });
- }
- } catch (_) {}
-
- try {
- Object.defineProperty(window, 'opener', {
- configurable: true,
- get: function() { return null; },
- set: function() { return true; }
- });
- } catch (_) {
- try {
- window.opener = null;
- } catch (_) {}
- }
-})();`
-
func injectedScript(ctx context.Context, script string) error {
return chromedp.FromContext(ctx).Target.Execute(ctx,
"Page.addScriptToEvaluateOnNewDocument",
diff --git a/internal/dashboard/dashboard.go b/internal/dashboard/dashboard.go
index 42d5de03..f3bcd6fc 100644
--- a/internal/dashboard/dashboard.go
+++ b/internal/dashboard/dashboard.go
@@ -295,7 +295,6 @@ func (d *Dashboard) RegisterHandlers(mux *http.ServeMux) {
mux.HandleFunc("GET /api/agents/{id}", d.handleAgent)
mux.HandleFunc("GET /api/agents/{id}/events", d.handleAgentSSE)
mux.HandleFunc("POST /api/agents/{id}/events", d.handleAgentEventsByID)
- mux.HandleFunc("POST /api/agent-events", d.handleAgentEvents)
// Static files served at /dashboard/
sub, _ := fs.Sub(dashboardFS, "dashboard")
@@ -339,15 +338,6 @@ func (d *Dashboard) handleAgent(w http.ResponseWriter, r *http.Request) {
})
}
-func (d *Dashboard) handleAgentEvents(w http.ResponseWriter, r *http.Request) {
- evt, ok := d.decodeProgressEvent(w, r, "")
- if !ok {
- return
- }
- d.RecordEvent(evt)
- httpx.JSON(w, http.StatusCreated, map[string]string{"status": "ok", "id": evt.ID})
-}
-
func (d *Dashboard) handleAgentEventsByID(w http.ResponseWriter, r *http.Request) {
pathAgentID := agentIDOrAnonymous(r.PathValue("id"))
evt, ok := d.decodeProgressEvent(w, r, pathAgentID)
diff --git a/internal/dashboard/dashboard_test.go b/internal/dashboard/dashboard_test.go
index 736e407b..b4f88240 100644
--- a/internal/dashboard/dashboard_test.go
+++ b/internal/dashboard/dashboard_test.go
@@ -196,51 +196,6 @@ func TestDashboardHandleAgentReturnsDetail(t *testing.T) {
}
}
-func TestDashboardHandleAgentEventsValidation(t *testing.T) {
- d := NewDashboard(nil)
-
- req := httptest.NewRequest(http.MethodPost, "/api/agent-events", bytes.NewBufferString(`{"agentId":"","message":""}`))
- w := httptest.NewRecorder()
- d.handleAgentEvents(w, req)
-
- if w.Code != http.StatusBadRequest {
- t.Fatalf("handleAgentEvents() status = %d, want %d", w.Code, http.StatusBadRequest)
- }
-}
-
-func TestDashboardHandleAgentEventsRecordsProgress(t *testing.T) {
- d := NewDashboard(nil)
- body := map[string]any{
- "agentId": "agent-1",
- "message": "Step 1",
- "progress": 1,
- "total": 3,
- }
- data, err := json.Marshal(body)
- if err != nil {
- t.Fatalf("Marshal() error = %v", err)
- }
-
- req := httptest.NewRequest(http.MethodPost, "/api/agent-events", bytes.NewReader(data))
- w := httptest.NewRecorder()
- d.handleAgentEvents(w, req)
-
- if w.Code != http.StatusCreated {
- t.Fatalf("handleAgentEvents() status = %d, want %d", w.Code, http.StatusCreated)
- }
-
- events := d.RecentEvents()
- if len(events) != 1 {
- t.Fatalf("RecentEvents() len = %d, want 1", len(events))
- }
- if events[0].Channel != "progress" {
- t.Fatalf("RecentEvents()[0].Channel = %q, want progress", events[0].Channel)
- }
- if events[0].Type != "progress" {
- t.Fatalf("RecentEvents()[0].Type = %q, want progress", events[0].Type)
- }
-}
-
func TestDashboardHandleAgentEventsByIDUsesRouteAgent(t *testing.T) {
d := NewDashboard(nil)
diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.go
index ed40525a..5b8f0fad 100644
--- a/internal/handlers/middleware.go
+++ b/internal/handlers/middleware.go
@@ -185,8 +185,6 @@ func cookieAuthAllowed(r *http.Request) bool {
switch {
case path == "/api/auth/elevate":
return true
- case path == "/api/agent-events":
- return true
case strings.HasPrefix(path, "/api/agents/") && strings.HasSuffix(path, "/events"):
return true
case path == "/action":
diff --git a/internal/orchestrator/handlers_instances.go b/internal/orchestrator/handlers_instances.go
index 11291de4..4c240c81 100644
--- a/internal/orchestrator/handlers_instances.go
+++ b/internal/orchestrator/handlers_instances.go
@@ -343,13 +343,18 @@ func (o *Orchestrator) handleAttachBridge(w http.ResponseWriter, r *http.Request
name = fmt.Sprintf("bridge-%d", time.Now().UnixNano())
}
- inst, err := o.AttachBridge(name, req.BaseURL, req.Token)
+ inst, created, err := o.AttachBridge(name, req.BaseURL, req.Token)
if err != nil {
httpx.Error(w, classifyLaunchError(err), err)
return
}
- authn.AuditLog(r, "instance.attached", "instanceId", inst.ID, "instanceName", inst.ProfileName, "attachType", "bridge")
- httpx.JSON(w, 201, inst)
+ if created {
+ authn.AuditLog(r, "instance.attached", "instanceId", inst.ID, "instanceName", inst.ProfileName, "attachType", "bridge")
+ httpx.JSON(w, 201, inst)
+ } else {
+ authn.AuditLog(r, "instance.reattached", "instanceId", inst.ID, "instanceName", inst.ProfileName, "attachType", "bridge")
+ httpx.JSON(w, 200, inst)
+ }
}
// probeAttachBridge checks that a remote bridge is reachable.
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index a17e6b68..287a1855 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -2,6 +2,7 @@ package orchestrator
import (
"context"
+ "crypto/subtle"
"encoding/json"
"fmt"
"io"
@@ -427,8 +428,11 @@ func (o *Orchestrator) attachExternalInstance(name string, inst bridge.Instance,
o.mu.Lock()
for _, existing := range o.instances {
if existing.ProfileName == name && instanceIsActive(existing) {
- // Allow upsert for bridge re-attach Other attach types still conflict.
if existing.Attached && inst.AttachType == "bridge" && existing.AttachType == "bridge" {
+ if existing.authToken != "" && subtle.ConstantTimeCompare([]byte(existing.authToken), []byte(authToken)) != 1 {
+ o.mu.Unlock()
+ return nil, false, fmt.Errorf("bridge %q already attached: token mismatch", name)
+ }
existing.URL = inst.URL
existing.Instance.URL = inst.URL
existing.authToken = authToken
@@ -490,8 +494,9 @@ func (o *Orchestrator) Attach(name, cdpURL string) (*bridge.Instance, error) {
}
// AttachBridge registers an already-running bridge server as an attached instance.
-// If a bridge with the same name is already attached, it is updated in place (upsert).
-func (o *Orchestrator) AttachBridge(name, baseURL, token string) (*bridge.Instance, error) {
+// If a bridge with the same name is already attached, it is updated in place (upsert)
+// provided the caller presents the current bridge token.
+func (o *Orchestrator) AttachBridge(name, baseURL, token string) (*bridge.Instance, bool, error) {
normalizedBaseURL := strings.TrimRight(baseURL, "/")
if parsed, err := url.Parse(normalizedBaseURL); err == nil && parsed.Scheme != "" && parsed.Host != "" {
normalizedBaseURL = parsed.Scheme + "://" + parsed.Host
@@ -503,7 +508,7 @@ func (o *Orchestrator) AttachBridge(name, baseURL, token string) (*bridge.Instan
URL: normalizedBaseURL,
}, token)
if err != nil {
- return nil, err
+ return nil, false, err
}
slog.Info("attached to external bridge", "id", inst.ID, "name", name, "url", internalurls.RedactForLog(inst.URL))
@@ -516,7 +521,7 @@ func (o *Orchestrator) AttachBridge(name, baseURL, token string) (*bridge.Instan
go o.monitorAttachedBridge(internal)
}
}
- return inst, nil
+ return inst, created, nil
}
func (o *Orchestrator) Stop(id string) error {
diff --git a/internal/orchestrator/orchestrator_test.go b/internal/orchestrator/orchestrator_test.go
index 089157e1..9c55a812 100644
--- a/internal/orchestrator/orchestrator_test.go
+++ b/internal/orchestrator/orchestrator_test.go
@@ -403,10 +403,13 @@ func TestOrchestrator_AttachBridge(t *testing.T) {
runner := &mockRunner{portAvail: true}
o := NewOrchestratorWithRunner(t.TempDir(), runner)
- inst, err := o.AttachBridge("bridge1", "http://10.0.0.8:9868", "bridge-token")
+ inst, created, err := o.AttachBridge("bridge1", "http://10.0.0.8:9868", "bridge-token")
if err != nil {
t.Fatalf("AttachBridge failed: %v", err)
}
+ if !created {
+ t.Fatal("expected new bridge to be created")
+ }
if !inst.Attached {
t.Fatal("expected attached instance")
}
@@ -425,15 +428,19 @@ func TestOrchestrator_AttachBridge_UpsertsExistingBridge(t *testing.T) {
runner := &mockRunner{portAvail: true}
o := NewOrchestratorWithRunner(t.TempDir(), runner)
- first, err := o.AttachBridge("bridge1", "http://10.0.0.8:9868", "bridge-token-1")
+ first, _, err := o.AttachBridge("bridge1", "http://10.0.0.8:9868", "bridge-token-1")
if err != nil {
t.Fatalf("first AttachBridge failed: %v", err)
}
- second, err := o.AttachBridge("bridge1", "http://10.0.0.9:9868", "bridge-token-2")
+ // Same token → upsert succeeds
+ second, created, err := o.AttachBridge("bridge1", "http://10.0.0.9:9868", "bridge-token-1")
if err != nil {
t.Fatalf("second AttachBridge failed: %v", err)
}
+ if created {
+ t.Fatal("expected upsert, not create")
+ }
if second.ID != first.ID {
t.Fatalf("ID = %q, want %q", second.ID, first.ID)
@@ -448,8 +455,8 @@ func TestOrchestrator_AttachBridge_UpsertsExistingBridge(t *testing.T) {
if internal == nil {
t.Fatalf("attached instance %q missing from orchestrator", first.ID)
}
- if internal.authToken != "bridge-token-2" {
- t.Fatalf("authToken = %q, want %q", internal.authToken, "bridge-token-2")
+ if internal.authToken != "bridge-token-1" {
+ t.Fatalf("authToken = %q, want %q", internal.authToken, "bridge-token-1")
}
list := o.List()
@@ -458,6 +465,25 @@ func TestOrchestrator_AttachBridge_UpsertsExistingBridge(t *testing.T) {
}
}
+func TestOrchestrator_AttachBridge_RejectsTokenMismatch(t *testing.T) {
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+
+ _, _, err := o.AttachBridge("bridge1", "http://10.0.0.8:9868", "bridge-token-1")
+ if err != nil {
+ t.Fatalf("first AttachBridge failed: %v", err)
+ }
+
+ // Different token → rejected
+ _, _, err = o.AttachBridge("bridge1", "http://10.0.0.9:9868", "bridge-token-2")
+ if err == nil {
+ t.Fatal("expected error for token mismatch, got nil")
+ }
+ if !strings.Contains(err.Error(), "token mismatch") {
+ t.Fatalf("expected token mismatch error, got: %v", err)
+ }
+}
+
func TestOrchestrator_AttachBridge_RemovesUnhealthyBridge(t *testing.T) {
unhealthy := false
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -475,7 +501,7 @@ func TestOrchestrator_AttachBridge_RemovesUnhealthyBridge(t *testing.T) {
o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
o.client = backend.Client()
- inst, err := o.AttachBridge("bridge1", backend.URL, "bridge-token")
+ inst, _, err := o.AttachBridge("bridge1", backend.URL, "bridge-token")
if err != nil {
t.Fatalf("AttachBridge failed: %v", err)
}
@@ -570,7 +596,7 @@ func TestOrchestrator_AttachBridge_NormalizesBaseURL(t *testing.T) {
runner := &mockRunner{portAvail: true}
o := NewOrchestratorWithRunner(t.TempDir(), runner)
- inst, err := o.AttachBridge("bridge1", "http://10.0.0.8:9868/?debug=1#frag", "bridge-token")
+ inst, _, err := o.AttachBridge("bridge1", "http://10.0.0.8:9868/?debug=1#frag", "bridge-token")
if err != nil {
t.Fatalf("AttachBridge failed: %v", err)
}
diff --git a/internal/orchestrator/proxy_test.go b/internal/orchestrator/proxy_test.go
index 5cd82824..fc8b8ce9 100644
--- a/internal/orchestrator/proxy_test.go
+++ b/internal/orchestrator/proxy_test.go
@@ -97,7 +97,7 @@ func TestProxyToURL_UsesAttachedBridgeOriginAndAuth(t *testing.T) {
o := NewOrchestrator(t.TempDir())
o.client = backend.Client()
- attached, err := o.AttachBridge("bridge1", backend.URL, "bridge-token")
+ attached, _, err := o.AttachBridge("bridge1", backend.URL, "bridge-token")
if err != nil {
t.Fatalf("AttachBridge failed: %v", err)
}