High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat(config,bridge,handlers): Add configurable action guard toggle (e… (#422)
Darshan Jain4eadbcbb1db8
diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.goindex 0c742622..0d0add0a 100644--- a/internal/bridge/bridge.go+++ b/internal/bridge/bridge.go@@ -40,6 +40,7 @@ type Bridge struct {BrowserCtx context.ContextBrowserCancel context.CancelFuncConfig *config.RuntimeConfig+ URLReader URLReaderIdMgr *ids.Manager*TabManagerStealthBundle *stealth.Bundle@@ -529,7 +530,34 @@ func (b *Bridge) ExecuteAction(ctx context.Context, kind string, req ActionRequeif !ok {return nil, fmt.Errorf("unknown action: %s", kind)}- return fn(ctx, req)+ guardEnabled := b.Config == nil || b.Config.EnableActionGuards+ checkNav := guardEnabled && shouldCheckUnexpectedNavigation(req)+ urlReader := b.URLReader+ if urlReader == nil {+ urlReader = defaultActionURLReader+ }+ var beforeURL string+ if checkNav {+ if u, err := urlReader(ctx); err == nil {+ beforeURL = u+ }+ }++ res, err := fn(ctx, req)+ if err != nil {+ return nil, classifyActionError(err)+ }++ if checkNav && beforeURL != "" {+ afterURL, uErr := urlReader(ctx)+ if uErr == nil {+ if navErr := checkUnexpectedNavigation(beforeURL, afterURL); navErr != nil {+ return nil, navErr+ }+ }+ }++ return res, nil}// Execute delegates to TabManager.Execute for safe parallel tab execution.diff --git a/internal/bridge/guards.go b/internal/bridge/guards.gonew file mode 100644index 00000000..b1521602--- /dev/null+++ b/internal/bridge/guards.go@@ -0,0 +1,80 @@+package bridge++import (+ "context"+ "errors"+ "fmt"+ "net/url"+ "strings"++ "github.com/chromedp/chromedp"+)++var (+ // ErrUnexpectedNavigation indicates an action was expected to keep context stable+ // but the page URL changed.+ ErrUnexpectedNavigation = errors.New("unexpected page navigation")+ // ErrElementStale indicates the targeted DOM/backend node is no longer valid.+ ErrElementStale = errors.New("element reference is stale")+)++// URLReader is used by guards to read the current tab URL from an action context.+type URLReader func(ctx context.Context) (string, error)++func defaultActionURLReader(ctx context.Context) (string, error) {+ if chromedp.FromContext(ctx) == nil {+ return "", nil+ }+ var current string+ if err := chromedp.Run(ctx, chromedp.Location(¤t)); err != nil {+ return "", err+ }+ return strings.TrimSpace(current), nil+}++func classifyActionError(err error) error {+ if err == nil {+ return nil+ }+ if errors.Is(err, ErrElementStale) {+ return err+ }+ e := strings.ToLower(err.Error())+ if strings.Contains(e, "could not find node") ||+ strings.Contains(e, "node with given id") ||+ strings.Contains(e, "no node") ||+ strings.Contains(e, "node with given identifier does not exist") {+ return fmt.Errorf("%w: %v", ErrElementStale, err)+ }+ return err+}++func shouldCheckUnexpectedNavigation(req ActionRequest) bool {+ return !req.WaitNav+}++func checkUnexpectedNavigation(before, after string) error {+ before = strings.TrimSpace(before)+ after = strings.TrimSpace(after)+ if before == "" || after == "" || before == after {+ return nil+ }+ if normalizedBefore, ok := normalizeGuardURL(before); ok {+ if normalizedAfter, ok := normalizeGuardURL(after); ok && normalizedBefore == normalizedAfter {+ return nil+ }+ }+ return fmt.Errorf("%w: %s -> %s", ErrUnexpectedNavigation, before, after)+}++func normalizeGuardURL(raw string) (string, bool) {+ parsed, err := url.Parse(strings.TrimSpace(raw))+ if err != nil || parsed == nil {+ return "", false+ }+ parsed.Fragment = ""+ if parsed.Host != "" {+ parsed.Host = strings.ToLower(parsed.Host)+ }+ return parsed.String(), true+}diff --git a/internal/bridge/guards_test.go b/internal/bridge/guards_test.gonew file mode 100644index 00000000..cc9cd377--- /dev/null+++ b/internal/bridge/guards_test.go@@ -0,0 +1,170 @@+package bridge++import (+ "context"+ "errors"+ "fmt"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+)++func TestClassifyActionError_StaleNode(t *testing.T) {+ err := classifyActionError(errors.New("Node with given identifier does not exist"))+ if !errors.Is(err, ErrElementStale) {+ t.Fatalf("expected ErrElementStale, got %v", err)+ }+}++func TestClassifyActionError_PreservesTyped(t *testing.T) {+ err := classifyActionError(fmt.Errorf("wrapped: %w", ErrElementStale))+ if !errors.Is(err, ErrElementStale) {+ t.Fatalf("expected ErrElementStale, got %v", err)+ }+}++func TestCheckUnexpectedNavigation(t *testing.T) {+ err := checkUnexpectedNavigation("https://a.example", "https://b.example")+ if !errors.Is(err, ErrUnexpectedNavigation) {+ t.Fatalf("expected ErrUnexpectedNavigation, got %v", err)+ }+}++func TestCheckUnexpectedNavigation_NoChange(t *testing.T) {+ if err := checkUnexpectedNavigation("https://a.example", "https://a.example"); err != nil {+ t.Fatalf("expected nil error, got %v", err)+ }+}++func TestCheckUnexpectedNavigation_EquivalentURLs(t *testing.T) {+ if err := checkUnexpectedNavigation("https://A.EXAMPLE/path?x=1#section", "https://a.example/path?x=1"); err != nil {+ t.Fatalf("expected nil error for equivalent URLs, got %v", err)+ }+}++func TestNormalizeGuardURL(t *testing.T) {+ got, ok := normalizeGuardURL("https://A.EXAMPLE/path#frag")+ if !ok {+ t.Fatal("expected URL normalization to succeed")+ }+ if got != "https://a.example/path" {+ t.Fatalf("expected normalized URL, got %q", got)+ }+}++func TestShouldCheckUnexpectedNavigation(t *testing.T) {+ if !shouldCheckUnexpectedNavigation(ActionRequest{}) {+ t.Fatal("click should be guarded when WaitNav is false")+ }+ if !shouldCheckUnexpectedNavigation(ActionRequest{}) {+ t.Fatal("press should be guarded when WaitNav is false")+ }+ if shouldCheckUnexpectedNavigation(ActionRequest{WaitNav: true}) {+ t.Fatal("WaitNav=true should disable navigation guard")+ }+}++func TestReadActionURL_NoChromeDPContext(t *testing.T) {+ u, err := defaultActionURLReader(context.Background())+ if err != nil {+ t.Fatalf("expected nil error, got %v", err)+ }+ if u != "" {+ t.Fatalf("expected empty URL, got %q", u)+ }+}++func TestExecuteAction_UnexpectedNavigation_WhenEnabled(t *testing.T) {+ call := 0+ readActionURL := func(context.Context) (string, error) {+ call+++ if call == 1 {+ return "https://a.example", nil+ }+ return "https://b.example", nil+ }++ b := &Bridge{+ Config: &config.RuntimeConfig{EnableActionGuards: true},+ URLReader: readActionURL,+ Actions: map[string]ActionFunc{+ ActionClick: func(context.Context, ActionRequest) (map[string]any, error) {+ return map[string]any{"ok": true}, nil+ },+ ActionType: func(context.Context, ActionRequest) (map[string]any, error) {+ return map[string]any{"ok": true}, nil+ },+ },+ }++ _, err := b.ExecuteAction(context.Background(), ActionClick, ActionRequest{})+ if !errors.Is(err, ErrUnexpectedNavigation) {+ t.Fatalf("expected ErrUnexpectedNavigation, got %v", err)+ }+}++func TestExecuteAction_UnexpectedNavigationGuardDisabled(t *testing.T) {+ called := 0+ readActionURL := func(context.Context) (string, error) {+ called+++ return "https://a.example", nil+ }++ b := &Bridge{+ Config: &config.RuntimeConfig{EnableActionGuards: false},+ URLReader: readActionURL,+ Actions: map[string]ActionFunc{+ ActionType: func(context.Context, ActionRequest) (map[string]any, error) {+ return map[string]any{"ok": true}, nil+ },+ },+ }++ if _, err := b.ExecuteAction(context.Background(), ActionType, ActionRequest{}); err != nil {+ t.Fatalf("expected nil error, got %v", err)+ }+ if called != 0 {+ t.Fatalf("expected readActionURL to not be called when guards are disabled, got %d calls", called)+ }+}++func TestExecuteAction_UnexpectedNavigation_WithNilConfigDefaultsEnabled(t *testing.T) {+ call := 0+ readActionURL := func(context.Context) (string, error) {+ call+++ if call == 1 {+ return "https://a.example", nil+ }+ return "https://b.example", nil+ }++ b := &Bridge{+ URLReader: readActionURL,+ Actions: map[string]ActionFunc{+ ActionType: func(context.Context, ActionRequest) (map[string]any, error) {+ return map[string]any{"ok": true}, nil+ },+ },+ }++ _, err := b.ExecuteAction(context.Background(), ActionType, ActionRequest{})+ if !errors.Is(err, ErrUnexpectedNavigation) {+ t.Fatalf("expected ErrUnexpectedNavigation, got %v", err)+ }+}++func TestExecuteAction_ClassifiesStaleError_WhenGuardsDisabled(t *testing.T) {+ b := &Bridge{+ Config: &config.RuntimeConfig{EnableActionGuards: false},+ Actions: map[string]ActionFunc{+ ActionType: func(context.Context, ActionRequest) (map[string]any, error) {+ return nil, errors.New("Node with given identifier does not exist")+ },+ },+ }++ _, err := b.ExecuteAction(context.Background(), ActionType, ActionRequest{})+ if !errors.Is(err, ErrElementStale) {+ t.Fatalf("expected ErrElementStale, got %v", err)+ }+}diff --git a/internal/config/config_file.go b/internal/config/config_file.goindex f5ff26c2..f5e8b74b 100644--- a/internal/config/config_file.go+++ b/internal/config/config_file.go@@ -26,6 +26,7 @@ func DefaultFileConfig() FileConfig {downloadMaxBytes := DefaultDownloadMaxBytesallowUpload := falseallowClipboard := false+ enableActionGuards := trueuploadMaxRequestBytes := DefaultUploadMaxRequestBytesuploadMaxFiles := DefaultUploadMaxFilesuploadMaxFileBytes := DefaultUploadMaxFileBytes@@ -66,6 +67,7 @@ func DefaultFileConfig() FileConfig {DownloadMaxBytes: &downloadMaxBytes,AllowUpload: &allowUpload,AllowClipboard: &allowClipboard,+ EnableActionGuards: &enableActionGuards,UploadMaxRequestBytes: &uploadMaxRequestBytes,UploadMaxFiles: &uploadMaxFiles,UploadMaxFileBytes: &uploadMaxFileBytes,@@ -191,6 +193,7 @@ type securityConfigJSON struct {DownloadMaxBytes *int `json:"downloadMaxBytes"`AllowUpload *bool `json:"allowUpload"`AllowClipboard *bool `json:"allowClipboard"`+ EnableActionGuards *bool `json:"enableActionGuards"`UploadMaxRequestBytes *int `json:"uploadMaxRequestBytes"`UploadMaxFiles *int `json:"uploadMaxFiles"`UploadMaxFileBytes *int `json:"uploadMaxFileBytes"`@@ -342,6 +345,7 @@ func (fc FileConfig) MarshalJSON() ([]byte, error) {DownloadMaxBytes: fc.Security.DownloadMaxBytes,AllowUpload: fc.Security.AllowUpload,AllowClipboard: fc.Security.AllowClipboard,+ EnableActionGuards: fc.Security.EnableActionGuards,UploadMaxRequestBytes: fc.Security.UploadMaxRequestBytes,UploadMaxFiles: fc.Security.UploadMaxFiles,UploadMaxFileBytes: fc.Security.UploadMaxFileBytes,@@ -449,6 +453,7 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {downloadMaxBytes := cfg.EffectiveDownloadMaxBytes()allowUpload := cfg.AllowUploadallowClipboard := cfg.AllowClipboard+ enableActionGuards := cfg.EnableActionGuardsuploadMaxRequestBytes := cfg.EffectiveUploadMaxRequestBytes()uploadMaxFiles := cfg.EffectiveUploadMaxFiles()uploadMaxFileBytes := cfg.EffectiveUploadMaxFileBytes()@@ -523,6 +528,7 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {DownloadMaxBytes: &downloadMaxBytes,AllowUpload: &allowUpload,AllowClipboard: &allowClipboard,+ EnableActionGuards: &enableActionGuards,UploadMaxRequestBytes: &uploadMaxRequestBytes,UploadMaxFiles: &uploadMaxFiles,UploadMaxFileBytes: &uploadMaxFileBytes,diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex 5737a1a2..1e3475fb 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -28,6 +28,7 @@ func Load() *RuntimeConfig {DownloadAllowedDomains: nil,DownloadMaxBytes: DefaultDownloadMaxBytes,AllowUpload: false,+ EnableActionGuards: true,UploadMaxRequestBytes: DefaultUploadMaxRequestBytes,UploadMaxFiles: DefaultUploadMaxFiles,UploadMaxFileBytes: DefaultUploadMaxFileBytes,@@ -230,6 +231,9 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {if fc.Security.AllowClipboard != nil {cfg.AllowClipboard = *fc.Security.AllowClipboard}+ if fc.Security.EnableActionGuards != nil {+ cfg.EnableActionGuards = *fc.Security.EnableActionGuards+ }if fc.Security.UploadMaxRequestBytes != nil {cfg.UploadMaxRequestBytes = clampPositiveLimit(*fc.Security.UploadMaxRequestBytes, DefaultUploadMaxRequestBytes, MaxUploadMaxRequestBytes)}diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.goindex b44bbd45..8710a648 100644--- a/internal/config/config_load_test.go+++ b/internal/config/config_load_test.go@@ -40,6 +40,9 @@ func TestLoadConfigDefaults(t *testing.T) {if cfg.AllowEvaluate {t.Errorf("default AllowEvaluate = %v, want false", cfg.AllowEvaluate)}+ if !cfg.EnableActionGuards {+ t.Errorf("default EnableActionGuards = %v, want true", cfg.EnableActionGuards)+ }if cfg.TrustProxyHeaders {t.Errorf("default TrustProxyHeaders = %v, want false", cfg.TrustProxyHeaders)}@@ -284,6 +287,9 @@ func TestApplyFileConfigToRuntimeResetsSecurityFlagsToSafeDefaults(t *testing.T)if cfg.AllowUpload {t.Errorf("ApplyFileConfigToRuntime AllowUpload = %v, want false", cfg.AllowUpload)}+ if !cfg.EnableActionGuards {+ t.Errorf("ApplyFileConfigToRuntime EnableActionGuards = %v, want true", cfg.EnableActionGuards)+ }if len(cfg.DownloadAllowedDomains) != 0 {t.Errorf("ApplyFileConfigToRuntime DownloadAllowedDomains = %v, want empty list", cfg.DownloadAllowedDomains)}diff --git a/internal/config/config_types.go b/internal/config/config_types.goindex 4d0566f0..305fb5ff 100644--- a/internal/config/config_types.go+++ b/internal/config/config_types.go@@ -24,6 +24,7 @@ type RuntimeConfig struct {DownloadMaxBytes intAllowUpload boolAllowClipboard bool+ EnableActionGuards bool // Enable bridge-level stale/navigation guard checks around actionsUploadMaxRequestBytes intUploadMaxFiles intUploadMaxFileBytes int@@ -238,6 +239,7 @@ type SecurityConfig struct {DownloadMaxBytes *int `json:"downloadMaxBytes,omitempty"`AllowUpload *bool `json:"allowUpload,omitempty"`AllowClipboard *bool `json:"allowClipboard,omitempty"`+ EnableActionGuards *bool `json:"enableActionGuards,omitempty"`UploadMaxRequestBytes *int `json:"uploadMaxRequestBytes,omitempty"`UploadMaxFiles *int `json:"uploadMaxFiles,omitempty"`UploadMaxFileBytes *int `json:"uploadMaxFileBytes,omitempty"`diff --git a/internal/config/editor_get.go b/internal/config/editor_get.goindex 7be65443..b31e6424 100644--- a/internal/config/editor_get.go+++ b/internal/config/editor_get.go@@ -138,6 +138,8 @@ func getSecurityField(s *SecurityConfig, field string) (string, error) {switch field {case "allowEvaluate":return formatBoolPtr(s.AllowEvaluate), nil+ case "allowClipboard":+ return formatBoolPtr(s.AllowClipboard), nilcase "allowMacro":return formatBoolPtr(s.AllowMacro), nilcase "allowScreencast":@@ -150,6 +152,8 @@ func getSecurityField(s *SecurityConfig, field string) (string, error) {return formatIntPtr(s.DownloadMaxBytes), nilcase "allowUpload":return formatBoolPtr(s.AllowUpload), nil+ case "enableActionGuards":+ return formatBoolPtr(s.EnableActionGuards), nilcase "uploadMaxRequestBytes":return formatIntPtr(s.UploadMaxRequestBytes), nilcase "uploadMaxFiles":diff --git a/internal/config/editor_get_test.go b/internal/config/editor_get_test.goindex 11f9fea6..7584d4e6 100644--- a/internal/config/editor_get_test.go+++ b/internal/config/editor_get_test.go@@ -29,12 +29,14 @@ func TestGetConfigValue_RoundTrip(t *testing.T) {{"instanceDefaults.stealthLevel", "full", "full"},{"instanceDefaults.tabEvictionPolicy", "close_lru", "close_lru"},{"security.allowEvaluate", "true", "true"},+ {"security.allowClipboard", "true", "true"},{"security.allowMacro", "false", "false"},{"security.allowScreencast", "on", "true"},{"security.allowDownload", "off", "false"},{"security.downloadAllowedDomains", "pinchtab.com,*.pinchtab.com", "pinchtab.com,*.pinchtab.com"},{"security.downloadMaxBytes", "33554432", "33554432"},{"security.allowUpload", "yes", "true"},+ {"security.enableActionGuards", "0", "false"},{"security.uploadMaxRequestBytes", "12582912", "12582912"},{"security.uploadMaxFiles", "12", "12"},{"security.uploadMaxFileBytes", "6291456", "6291456"},@@ -91,11 +93,13 @@ func TestGetConfigValue_NilPointerReturnsEmpty(t *testing.T) {"instanceDefaults.maxParallelTabs","instanceDefaults.noAnimations","security.allowEvaluate",+ "security.allowClipboard","security.allowMacro","security.allowScreencast","security.allowDownload","security.downloadMaxBytes","security.allowUpload",+ "security.enableActionGuards","security.uploadMaxRequestBytes","security.uploadMaxFiles","security.uploadMaxFileBytes",diff --git a/internal/config/editor_set.go b/internal/config/editor_set.goindex 831dce13..709f60ad 100644--- a/internal/config/editor_set.go+++ b/internal/config/editor_set.go@@ -264,6 +264,8 @@ func setSecurityField(s *SecurityConfig, field, value string) error {switch field {case "allowEvaluate":s.AllowEvaluate = &b+ case "allowClipboard":+ s.AllowClipboard = &bcase "allowMacro":s.AllowMacro = &bcase "allowScreencast":@@ -272,6 +274,8 @@ func setSecurityField(s *SecurityConfig, field, value string) error {s.AllowDownload = &bcase "allowUpload":s.AllowUpload = &b+ case "enableActionGuards":+ s.EnableActionGuards = &bdefault:return fmt.Errorf("unknown field security.%s", field)}diff --git a/internal/config/editor_set_test.go b/internal/config/editor_set_test.goindex fcad8830..10b8a506 100644--- a/internal/config/editor_set_test.go+++ b/internal/config/editor_set_test.go@@ -81,6 +81,9 @@ func TestSetConfigValue_SecurityFields(t *testing.T) {wantErr bool}{{"security.allowEvaluate", "true", func(fc *FileConfig) bool { return *fc.Security.AllowEvaluate == true }, false},+ {"security.allowClipboard", "true", func(fc *FileConfig) bool {+ return fc.Security.AllowClipboard != nil && *fc.Security.AllowClipboard+ }, false},{"security.allowMacro", "1", func(fc *FileConfig) bool { return *fc.Security.AllowMacro == true }, false},{"security.allowScreencast", "false", func(fc *FileConfig) bool { return *fc.Security.AllowScreencast == false }, false},{"security.allowDownload", "on", func(fc *FileConfig) bool { return *fc.Security.AllowDownload == true }, false},@@ -93,6 +96,9 @@ func TestSetConfigValue_SecurityFields(t *testing.T) {return fc.Security.DownloadMaxBytes != nil && *fc.Security.DownloadMaxBytes == 33554432}, false},{"security.allowUpload", "off", func(fc *FileConfig) bool { return *fc.Security.AllowUpload == false }, false},+ {"security.enableActionGuards", "true", func(fc *FileConfig) bool {+ return fc.Security.EnableActionGuards != nil && *fc.Security.EnableActionGuards+ }, false},{"security.uploadMaxRequestBytes", "12582912", func(fc *FileConfig) bool {return fc.Security.UploadMaxRequestBytes != nil && *fc.Security.UploadMaxRequestBytes == 12582912}, false},@@ -106,6 +112,8 @@ func TestSetConfigValue_SecurityFields(t *testing.T) {return fc.Security.UploadMaxTotalBytes != nil && *fc.Security.UploadMaxTotalBytes == 18874368}, false},{"security.allowEvaluate", "maybe", nil, true},+ {"security.allowClipboard", "maybe", nil, true},+ {"security.enableActionGuards", "maybe", nil, true},{"security.unknown", "true", nil, true},}diff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex 2109367e..00810767 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -321,6 +321,10 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {})return}+ if errors.Is(actionErr, bridge.ErrUnexpectedNavigation) {+ httpx.ErrorCode(w, 409, "navigation_changed", actionErr.Error(), false, nil)+ return+ }if errors.Is(actionErr, engine.ErrLiteNotSupported) {httpx.ErrorCode(w, http.StatusNotImplemented, "not_supported", actionErr.Error(), false, nil)return@@ -1076,6 +1080,12 @@ func shouldRetryStaleRef(err error) bool {if err == nil {return false}+ if errors.Is(err, bridge.ErrElementStale) {+ return true+ }+ // Fallback string matching is still needed for stale failures that can bypass+ // bridge.ExecuteAction classification (for example, lite-engine paths or other+ // non-bridge error surfaces that return raw backend-node messages).e := strings.ToLower(err.Error())return strings.Contains(e, "could not find node") || strings.Contains(e, "node with given id") || strings.Contains(e, "no node")}