Skip to content

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

feat(security): add handoff CLI flow and harden captcha safeguards

Luigi Agostibba157cc8ad0
diff --git a/cmd/pinchtab/cmd_cli_browser_nav.go b/cmd/pinchtab/cmd_cli_browser_nav.go
index 3bc30c7c..8b098408 100644
--- a/cmd/pinchtab/cmd_cli_browser_nav.go
+++ b/cmd/pinchtab/cmd_cli_browser_nav.go
@@ -103,3 +103,40 @@ var tabCloseCmd = &cobra.Command{
})
},
}
+
+var tabHandoffCmd = &cobra.Command{
+ Use: "handoff <id>",
+ Short: "Pause tab automation for human handoff",
+ Long: "Mark a tab as paused_handoff so action routes block until resumed or timeout expires.",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ reason, _ := cmd.Flags().GetString("reason")
+ timeoutMS, _ := cmd.Flags().GetInt("timeout-ms")
+ runCLI(func(rt cliRuntime) {
+ browseractions.TabHandoff(rt.client, rt.base, rt.token, args[0], reason, timeoutMS)
+ })
+ },
+}
+
+var tabResumeCmd = &cobra.Command{
+ Use: "resume <id>",
+ Short: "Resume a paused_handoff tab",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ status, _ := cmd.Flags().GetString("status")
+ runCLI(func(rt cliRuntime) {
+ browseractions.TabResume(rt.client, rt.base, rt.token, args[0], status)
+ })
+ },
+}
+
+var tabHandoffStatusCmd = &cobra.Command{
+ Use: "handoff-status <id>",
+ Short: "Show handoff status for a tab",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.TabHandoffStatus(rt.client, rt.base, rt.token, args[0])
+ })
+ },
+}
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
index 154a5391..47060b5a 100644
--- a/cmd/pinchtab/cmd_cli_register.go
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -59,7 +59,7 @@ func registerBrowserCommands() {
stateCmd,
)
- tabsCmd.AddCommand(tabNewCmd, tabCloseCmd)
+ tabsCmd.AddCommand(tabNewCmd, tabCloseCmd, tabHandoffCmd, tabResumeCmd, tabHandoffStatusCmd)
clipboardCmd.AddCommand(clipboardReadCmd, clipboardWriteCmd, clipboardCopyCmd, clipboardPasteCmd)
keyboardCmd.AddCommand(keyboardTypeCmd, keyboardInsertTextCmd)
dialogCmd.AddCommand(dialogAcceptCmd, dialogDismissCmd)
@@ -272,6 +272,9 @@ func configureBrowserFlags() {
evalCmd.Flags().Bool("await-promise", false, "Resolve a returned Promise before responding")
navCmd.Flags().Bool("print-tab-id", false, "Print only the tab ID on stdout (also triggered automatically when stdout is a pipe)")
+ tabHandoffCmd.Flags().String("reason", "", "Reason for human handoff (default: manual_handoff)")
+ tabHandoffCmd.Flags().Int("timeout-ms", 0, "Optional auto-resume timeout in milliseconds")
+ tabResumeCmd.Flags().String("status", "", "Optional resume status note (e.g. completed, failed)")
// Add --json flag to action commands (default is terse output)
addJSONFlag(
diff --git a/cmd/pinchtab/cmd_cli_test.go b/cmd/pinchtab/cmd_cli_test.go
index b0655d31..f88b50f5 100644
--- a/cmd/pinchtab/cmd_cli_test.go
+++ b/cmd/pinchtab/cmd_cli_test.go
@@ -64,3 +64,15 @@ func TestDragCommandRegistered(t *testing.T) {
t.Fatal("expected drag command to be registered")
}
}
+
+func TestTabHandoffCommandsRegistered(t *testing.T) {
+ tabCmd := findCommand(rootCmd, "tab [id]")
+ if tabCmd == nil {
+ t.Fatal("expected tab command to be registered")
+ }
+ for _, name := range []string{"handoff", "resume", "handoff-status"} {
+ if findCommand(tabCmd, name) == nil {
+ t.Fatalf("expected tab subcommand %q to be registered", name)
+ }
+ }
+}
diff --git a/docs/commands.md b/docs/commands.md
index fdf59996..9e05dd3b 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -171,9 +171,18 @@ pinchtab cache clear # Clear browser HTTP disk cache
pinchtab cache status # Check if cache can be cleared
```
-Manual handoff and resume are API-only today:
+Manual handoff and resume are available via CLI and API:
-This is currently a temporary, non-blocking implementation. It records handoff state, but it does not yet enforce a hard stop on future automation requests by itself.
+```bash
+pinchtab tab handoff <tabId> --reason captcha --timeout-ms 120000
+pinchtab tab handoff-status <tabId>
+pinchtab tab resume <tabId> --status completed
+```
+
+API equivalents:
+
+Paused handoff state blocks action execution routes (`/action`, `/actions/batch`, `/macro`) with `409 tab_paused_handoff`
+until resumed or expired via timeout.
```bash
curl -X POST "$PINCHTAB_SERVER/tabs/<tabId>/handoff"
diff --git a/docs/endpoints.md b/docs/endpoints.md
index 5c724be7..428b11d1 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -104,11 +104,10 @@ Notes:
- these routes are tab-scoped only
- `POST /tabs/{id}/handoff` marks the tab as `paused_handoff` and records a reason
-- `GET /tabs/{id}/handoff` returns the current handoff state, or `active` when no handoff is set
+- `GET /tabs/{id}/handoff` returns the current handoff state, or `active` when no handoff is set (includes `expiresAt` and `timeoutMs` when timeout is configured)
- `POST /tabs/{id}/resume` clears the handoff state and can carry resume metadata for the caller
-- current behavior is advisory only: handoff state is not yet a hard block on subsequent automation requests
-- treat the current implementation as temporary coordination state, not as a security boundary
-- there is currently no dedicated CLI wrapper for handoff or resume; use the HTTP API
+- action execution routes (`/action`, `/actions/batch`, `/macro`) reject paused tabs with `409 tab_paused_handoff`
+- CLI wrappers are available: `pinchtab tab handoff`, `pinchtab tab handoff-status`, and `pinchtab tab resume`
## Tab Locking
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index b5e7992a..3bf5e4d6 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -134,9 +134,18 @@ unless you override it with `--frame`.
Selector-based actions fail fast when a selector does not match. If you expect
dynamic content to appear shortly, use `pinchtab wait` first.
-Manual handoff is currently API-only:
+Manual handoff is available via the `tab` command:
-This is currently advisory state only. It marks the tab as `paused_handoff`, but it does not yet provide a guaranteed blocking pause for later automation.
+```bash
+pinchtab tab handoff <tabId> --reason captcha --timeout-ms 120000
+pinchtab tab handoff-status <tabId>
+pinchtab tab resume <tabId> --status completed
+```
+
+API equivalents:
+
+Paused handoff state blocks action execution routes (`/action`, `/actions/batch`, `/macro`) with `409 tab_paused_handoff`
+until resumed or expired via timeout.
```bash
curl -X POST http://localhost:9867/tabs/<tabId>/handoff \
@@ -157,6 +166,9 @@ pinchtab tab
pinchtab tab <id>
pinchtab tab new [url]
pinchtab tab close <id>
+pinchtab tab handoff <id>
+pinchtab tab handoff-status <id>
+pinchtab tab resume <id>
```
For tab-scoped actions, use the normal top-level command with `--tab`:
diff --git a/docs/reference/handoff.md b/docs/reference/handoff.md
index 9a1dcb53..d05d0423 100644
--- a/docs/reference/handoff.md
+++ b/docs/reference/handoff.md
@@ -2,11 +2,18 @@
Mark a tab for human intervention, inspect the handoff state, then resume automation when the manual step is complete.
-There is currently no dedicated CLI wrapper. Handoff is API-only.
+CLI wrappers are available:
-> Temporary status: the current handoff implementation is advisory only.
-> `POST /tabs/{id}/handoff` records `paused_handoff`, but it does not yet enforce a hard execution block across later automation requests.
-> Treat it as coordination metadata for now, not as a security boundary. A stricter blocking model tied to session-owned locks is expected later.
+```bash
+pinchtab tab handoff <tabId> --reason captcha --timeout-ms 120000
+pinchtab tab handoff-status <tabId>
+pinchtab tab resume <tabId> --status completed
+```
+
+API equivalents:
+
+When a tab is in `paused_handoff`, action execution routes reject with `409 tab_paused_handoff`
+until the tab is resumed or the optional handoff timeout expires.
```bash
curl -X POST http://localhost:9867/tabs/<tabId>/handoff \
@@ -24,9 +31,10 @@ Notes:
- `POST /tabs/{id}/handoff` sets the tab state to `paused_handoff`
- `GET /tabs/{id}/handoff` returns the current handoff state, or `active` when no handoff is set
+- when a timeout is set, status also includes `expiresAt` and `timeoutMs`
- `POST /tabs/{id}/resume` clears the handoff state and can carry resume metadata such as `status` or `resolvedData`
-- today this is informational state only; it does not by itself block other later automation
-- use this for CAPTCHA, 2FA, login approval, or other human-only steps only if your caller also coordinates access separately
+- paused tabs reject `/action`, `/actions/batch`, and `/macro` requests with `tab_paused_handoff`
+- use this for CAPTCHA, 2FA, login approval, or other human-only steps
## Related Pages
diff --git a/docs/reference/tabs.md b/docs/reference/tabs.md
index af593958..b9287a45 100644
--- a/docs/reference/tabs.md
+++ b/docs/reference/tabs.md
@@ -190,9 +190,18 @@ pinchtab mouse wheel --tab <tabId> 240 --dx 40
### Handoff State
-Human handoff is tab-scoped and API-only today.
+Human handoff is tab-scoped and available through CLI or API.
-Current limitation: this is not a blocking pause yet. The tab is marked as `paused_handoff`, but normal automation is not universally rejected just because that state is present. Treat it as temporary coordination metadata, not as an enforced lockout.
+```bash
+pinchtab tab handoff <tabId> --reason captcha --timeout-ms 120000
+pinchtab tab handoff-status <tabId>
+pinchtab tab resume <tabId> --status completed
+```
+
+API equivalents:
+
+When a tab is marked `paused_handoff`, action execution routes reject with `409 tab_paused_handoff`
+until the tab is resumed or the optional timeout expires.
```bash
curl -X POST http://localhost:9867/tabs/<tabId>/handoff \
@@ -206,7 +215,8 @@ curl -X POST http://localhost:9867/tabs/<tabId>/resume \
-d '{"status":"completed","resolvedData":{"operator":"human"}}'
```
-Use this when automation must pause for a CAPTCHA, 2FA prompt, login approval, or another human-only step, but pair it with separate ownership/locking if you need hard exclusion today.
+Use this when automation must pause for a CAPTCHA, 2FA prompt, login approval, or another human-only step.
+When a timeout is provided, handoff status includes `expiresAt` and `timeoutMs`.
### Screenshot
diff --git a/internal/autosolver/semantic/adapter.go b/internal/autosolver/semantic/adapter.go
index 53eca46b..e4340ee8 100644
--- a/internal/autosolver/semantic/adapter.go
+++ b/internal/autosolver/semantic/adapter.go
@@ -5,6 +5,7 @@ package semantic
import (
"context"
+ "fmt"
"strings"
"github.com/pinchtab/pinchtab/internal/autosolver"
@@ -290,7 +291,7 @@ func extractDescriptors(html string) []semantic.ElementDescriptor {
ref++
descs = append(descs, semantic.ElementDescriptor{
- Ref: strings.Repeat("e", 1) + string(rune('0'+ref)),
+ Ref: fmt.Sprintf("e%d", ref),
Role: p.role,
Name: name,
})
diff --git a/internal/autosolver/types.go b/internal/autosolver/types.go
index 067471b0..a8d216a8 100644
--- a/internal/autosolver/types.go
+++ b/internal/autosolver/types.go
@@ -131,7 +131,7 @@ func DefaultConfig() Config {
Enabled: true,
MaxAttempts: 8,
SolverTimeout: 30 * time.Second,
- Solvers: []string{"cloudflare", "semantic", "capsolver", "twocaptcha"},
+ Solvers: []string{"cloudflare", "semantic"},
LLMFallback: false,
RetryBaseDelay: 500 * time.Millisecond,
RetryMaxDelay: 10 * time.Second,
diff --git a/internal/bridge/handoff.go b/internal/bridge/handoff.go
index 55f72adc..8aad4faa 100644
--- a/internal/bridge/handoff.go
+++ b/internal/bridge/handoff.go
@@ -12,9 +12,10 @@ type TabHandoffState struct {
Reason string `json:"reason,omitempty"`
PausedAt time.Time `json:"pausedAt"`
LastUpdatedAt time.Time `json:"lastUpdatedAt"`
+ ExpiresAt time.Time `json:"expiresAt,omitempty"`
}
-func (b *Bridge) SetTabHandoff(tabID, reason string) error {
+func (b *Bridge) SetTabHandoff(tabID, reason string, timeout time.Duration) error {
if b == nil {
return fmt.Errorf("bridge not initialized")
}
@@ -28,6 +29,9 @@ func (b *Bridge) SetTabHandoff(tabID, reason string) error {
PausedAt: now,
LastUpdatedAt: now,
}
+ if timeout > 0 {
+ state.ExpiresAt = now.Add(timeout)
+ }
if state.Reason == "" {
state.Reason = "manual_handoff"
}
@@ -56,7 +60,18 @@ func (b *Bridge) TabHandoffState(tabID string) (TabHandoffState, bool) {
return TabHandoffState{}, false
}
b.handoffMu.RLock()
- defer b.handoffMu.RUnlock()
state, ok := b.handoffs[tabID]
+ b.handoffMu.RUnlock()
+ if !ok {
+ return TabHandoffState{}, false
+ }
+ if !state.ExpiresAt.IsZero() && time.Now().UTC().After(state.ExpiresAt) {
+ b.handoffMu.Lock()
+ if latest, stillPresent := b.handoffs[tabID]; stillPresent && latest.LastUpdatedAt.Equal(state.LastUpdatedAt) {
+ delete(b.handoffs, tabID)
+ }
+ b.handoffMu.Unlock()
+ return TabHandoffState{}, false
+ }
return state, ok
}
diff --git a/internal/bridge/handoff_test.go b/internal/bridge/handoff_test.go
new file mode 100644
index 00000000..147ab2ea
--- /dev/null
+++ b/internal/bridge/handoff_test.go
@@ -0,0 +1,24 @@
+package bridge
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestTabHandoffState_Expires(t *testing.T) {
+ b := New(context.TODO(), nil, &config.RuntimeConfig{})
+ if err := b.SetTabHandoff("tab1", "manual", 10*time.Millisecond); err != nil {
+ t.Fatalf("set handoff: %v", err)
+ }
+ if _, ok := b.TabHandoffState("tab1"); !ok {
+ t.Fatal("expected handoff state to exist immediately")
+ }
+ time.Sleep(20 * time.Millisecond)
+ if _, ok := b.TabHandoffState("tab1"); ok {
+ t.Fatal("expected handoff state to expire")
+ }
+}
+
diff --git a/internal/cli/actions/actions_handoff_test.go b/internal/cli/actions/actions_handoff_test.go
new file mode 100644
index 00000000..3f70d87a
--- /dev/null
+++ b/internal/cli/actions/actions_handoff_test.go
@@ -0,0 +1,71 @@
+package actions
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+func TestTabHandoff(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ TabHandoff(client, m.base(), "", "tab_123", "captcha_manual", 60000)
+
+ if m.lastMethod != "POST" {
+ t.Fatalf("expected POST, got %s", m.lastMethod)
+ }
+ if m.lastPath != "/tabs/tab_123/handoff" {
+ t.Fatalf("expected /tabs/tab_123/handoff, got %s", m.lastPath)
+ }
+
+ var body map[string]any
+ if err := json.Unmarshal([]byte(m.lastBody), &body); err != nil {
+ t.Fatalf("decode body: %v", err)
+ }
+ if got, _ := body["reason"].(string); got != "captcha_manual" {
+ t.Fatalf("expected reason=captcha_manual, got %v", body["reason"])
+ }
+ if got, _ := body["timeoutMs"].(float64); int(got) != 60000 {
+ t.Fatalf("expected timeoutMs=60000, got %v", body["timeoutMs"])
+ }
+}
+
+func TestTabResume(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ TabResume(client, m.base(), "", "tab_123", "completed")
+
+ if m.lastMethod != "POST" {
+ t.Fatalf("expected POST, got %s", m.lastMethod)
+ }
+ if m.lastPath != "/tabs/tab_123/resume" {
+ t.Fatalf("expected /tabs/tab_123/resume, got %s", m.lastPath)
+ }
+
+ var body map[string]any
+ if err := json.Unmarshal([]byte(m.lastBody), &body); err != nil {
+ t.Fatalf("decode body: %v", err)
+ }
+ if got, _ := body["status"].(string); got != "completed" {
+ t.Fatalf("expected status=completed, got %v", body["status"])
+ }
+}
+
+func TestTabHandoffStatus(t *testing.T) {
+ m := newMockServer()
+ m.response = `{"tabId":"tab_123","status":"active"}`
+ defer m.close()
+ client := m.server.Client()
+
+ TabHandoffStatus(client, m.base(), "", "tab_123")
+
+ if m.lastMethod != "GET" {
+ t.Fatalf("expected GET, got %s", m.lastMethod)
+ }
+ if m.lastPath != "/tabs/tab_123/handoff" {
+ t.Fatalf("expected /tabs/tab_123/handoff, got %s", m.lastPath)
+ }
+}
diff --git a/internal/cli/actions/actions_tabs.go b/internal/cli/actions/actions_tabs.go
index 0c37b417..a2676d71 100644
--- a/internal/cli/actions/actions_tabs.go
+++ b/internal/cli/actions/actions_tabs.go
@@ -100,3 +100,29 @@ func TabFocus(client *http.Client, base, token string, tabID string, cmd *cobra.
})
output.Value(tabID)
}
+
+// TabHandoff pauses automation on a tab for manual operator intervention.
+func TabHandoff(client *http.Client, base, token, tabID, reason string, timeoutMS int) {
+ body := map[string]any{}
+ if reason != "" {
+ body["reason"] = reason
+ }
+ if timeoutMS > 0 {
+ body["timeoutMs"] = timeoutMS
+ }
+ apiclient.DoPost(client, base, token, fmt.Sprintf("/tabs/%s/handoff", tabID), body)
+}
+
+// TabResume resumes automation on a tab after manual intervention.
+func TabResume(client *http.Client, base, token, tabID, status string) {
+ body := map[string]any{}
+ if status != "" {
+ body["status"] = status
+ }
+ apiclient.DoPost(client, base, token, fmt.Sprintf("/tabs/%s/resume", tabID), body)
+}
+
+// TabHandoffStatus shows whether a tab is in paused_handoff or active state.
+func TabHandoffStatus(client *http.Client, base, token, tabID string) {
+ apiclient.DoGet(client, base, token, fmt.Sprintf("/tabs/%s/handoff", tabID), nil)
+}
diff --git a/internal/config/config_load.go b/internal/config/config_load.go
index 4e8a982f..bc42cb04 100644
--- a/internal/config/config_load.go
+++ b/internal/config/config_load.go
@@ -5,9 +5,17 @@ import (
"log/slog"
"os"
"path/filepath"
+ "strings"
"time"
)
+var supportedAutoSolverNames = map[string]struct{}{
+ "cloudflare": {},
+ "semantic": {},
+}
+
+var defaultAutoSolverNames = []string{"cloudflare", "semantic"}
+
// Load returns the RuntimeConfig with precedence: env vars > config file > defaults.
func Load() *RuntimeConfig {
cfg := &RuntimeConfig{
@@ -123,7 +131,7 @@ func Load() *RuntimeConfig {
AutoSolver: AutoSolverConfig{
Enabled: false,
MaxAttempts: 8,
- Solvers: []string{"cloudflare", "semantic", "capsolver", "twocaptcha"},
+ Solvers: []string{"cloudflare", "semantic"},
LLMFallback: false,
},
}
@@ -506,6 +514,59 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
}
cfg.AutoSolver.CapsolverKey = fc.AutoSolver.External.CapsolverKey
cfg.AutoSolver.TwoCaptchaKey = fc.AutoSolver.External.TwoCaptchaKey
+ sanitizeAutoSolverRuntimeConfig(cfg)
+}
+
+func sanitizeAutoSolverRuntimeConfig(cfg *RuntimeConfig) {
+ if cfg == nil {
+ return
+ }
+
+ sanitized := normalizeAutoSolverNames(cfg.AutoSolver.Solvers)
+ if len(sanitized) == 0 {
+ sanitized = append([]string(nil), defaultAutoSolverNames...)
+ }
+ cfg.AutoSolver.Solvers = sanitized
+
+ if strings.TrimSpace(cfg.AutoSolver.LLMProvider) != "" {
+ slog.Warn("autosolver llmProvider is not implemented; ignoring configured provider",
+ "provider", cfg.AutoSolver.LLMProvider)
+ cfg.AutoSolver.LLMProvider = ""
+ }
+
+ if cfg.AutoSolver.LLMFallback {
+ slog.Warn("autosolver llmFallback is not implemented; forcing disabled")
+ cfg.AutoSolver.LLMFallback = false
+ }
+}
+
+func normalizeAutoSolverNames(raw []string) []string {
+ if len(raw) == 0 {
+ return nil
+ }
+
+ out := make([]string, 0, len(raw))
+ seen := make(map[string]struct{}, len(raw))
+
+ for _, name := range raw {
+ normalized := strings.ToLower(strings.TrimSpace(name))
+ if normalized == "" {
+ continue
+ }
+
+ if _, ok := supportedAutoSolverNames[normalized]; !ok {
+ slog.Warn("autosolver solver is not implemented; ignoring configured solver", "solver", name)
+ continue
+ }
+
+ if _, ok := seen[normalized]; ok {
+ continue
+ }
+ seen[normalized] = struct{}{}
+ out = append(out, normalized)
+ }
+
+ return out
}
// ApplyFileConfigToRuntime merges file configuration into an existing runtime
diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.go
index 9ae86b1b..f3c54f0d 100644
--- a/internal/config/config_load_test.go
+++ b/internal/config/config_load_test.go
@@ -1,8 +1,10 @@
package config
import (
+ "encoding/json"
"os"
"path/filepath"
+ "reflect"
"testing"
"time"
)
@@ -286,16 +288,21 @@ func TestLoadConfigActivityStateDirIgnoresConfigOverride(t *testing.T) {
_ = os.Setenv("PINCHTAB_CONFIG", configPath)
defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()
- if err := os.WriteFile(configPath, []byte(`{
- "server": {
- "stateDir": "/tmp/profile-state"
+ payload := map[string]any{
+ "server": map[string]any{
+ "stateDir": "/tmp/profile-state",
},
- "observability": {
- "activity": {
- "stateDir": "`+sharedActivityDir+`"
- }
- }
- }`), 0644); err != nil {
+ "observability": map[string]any{
+ "activity": map[string]any{
+ "stateDir": sharedActivityDir,
+ },
+ },
+ }
+ raw, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(configPath, raw, 0644); err != nil {
t.Fatal(err)
}
@@ -661,6 +668,47 @@ func TestApplyFileConfigToRuntime_SanitizesChromeExtraFlags(t *testing.T) {
}
}
+func TestApplyFileConfigToRuntime_SanitizesAutoSolverUnsupportedSettings(t *testing.T) {
+ llmFallback := true
+ cfg := &RuntimeConfig{}
+ fc := &FileConfig{
+ AutoSolver: AutoSolverFileConfig{
+ Solvers: []string{" cloudflare ", "capsolver", "semantic", "twocaptcha", "semantic"},
+ LLMProvider: "openai",
+ LLMFallback: &llmFallback,
+ },
+ }
+
+ ApplyFileConfigToRuntime(cfg, fc)
+
+ if cfg.AutoSolver.LLMProvider != "" {
+ t.Fatalf("AutoSolver.LLMProvider = %q, want empty", cfg.AutoSolver.LLMProvider)
+ }
+ if cfg.AutoSolver.LLMFallback {
+ t.Fatal("AutoSolver.LLMFallback = true, want false")
+ }
+ wantSolvers := []string{"cloudflare", "semantic"}
+ if !reflect.DeepEqual(cfg.AutoSolver.Solvers, wantSolvers) {
+ t.Fatalf("AutoSolver.Solvers = %v, want %v", cfg.AutoSolver.Solvers, wantSolvers)
+ }
+}
+
+func TestApplyFileConfigToRuntime_AutoSolverFallsBackToDefaultSupportedSolvers(t *testing.T) {
+ cfg := &RuntimeConfig{}
+ fc := &FileConfig{
+ AutoSolver: AutoSolverFileConfig{
+ Solvers: []string{"capsolver", "twocaptcha"},
+ },
+ }
+
+ ApplyFileConfigToRuntime(cfg, fc)
+
+ wantSolvers := []string{"cloudflare", "semantic"}
+ if !reflect.DeepEqual(cfg.AutoSolver.Solvers, wantSolvers) {
+ t.Fatalf("AutoSolver.Solvers = %v, want %v", cfg.AutoSolver.Solvers, wantSolvers)
+ }
+}
+
// clearConfigEnvVars unsets all config-related env vars for clean tests.
func clearConfigEnvVars(t *testing.T) {
t.Helper()
diff --git a/internal/config/validate.go b/internal/config/validate.go
index ca59ae93..7b575769 100644
--- a/internal/config/validate.go
+++ b/internal/config/validate.go
@@ -232,6 +232,41 @@ func ValidateFileConfig(fc *FileConfig) []error {
})
}
+ // AutoSolver validation
+ for _, solver := range fc.AutoSolver.Solvers {
+ switch strings.ToLower(strings.TrimSpace(solver)) {
+ case "":
+ errs = append(errs, ValidationError{
+ Field: "autoSolver.solvers",
+ Message: "solver name must not be empty",
+ })
+ case "cloudflare", "semantic":
+ // Supported.
+ case "capsolver", "twocaptcha":
+ errs = append(errs, ValidationError{
+ Field: "autoSolver.solvers",
+ Message: fmt.Sprintf("solver %q is not implemented yet; remove it from autoSolver.solvers", solver),
+ })
+ default:
+ errs = append(errs, ValidationError{
+ Field: "autoSolver.solvers",
+ Message: fmt.Sprintf("invalid solver %q (supported: cloudflare, semantic)", solver),
+ })
+ }
+ }
+ if fc.AutoSolver.LLMFallback != nil && *fc.AutoSolver.LLMFallback {
+ errs = append(errs, ValidationError{
+ Field: "autoSolver.llmFallback",
+ Message: "LLM fallback is not implemented yet and cannot be enabled",
+ })
+ }
+ if strings.TrimSpace(fc.AutoSolver.LLMProvider) != "" {
+ errs = append(errs, ValidationError{
+ Field: "autoSolver.llmProvider",
+ Message: "LLM provider integration is not implemented yet; leave autoSolver.llmProvider unset",
+ })
+ }
+
return errs
}
diff --git a/internal/config/validate_test.go b/internal/config/validate_test.go
index 9d19dfa0..1cca95be 100644
--- a/internal/config/validate_test.go
+++ b/internal/config/validate_test.go
@@ -514,6 +514,103 @@ func TestValidEnumValues(t *testing.T) {
}
}
+func TestValidateFileConfig_AutoSolverUnsupportedSolver(t *testing.T) {
+ fc := &FileConfig{
+ AutoSolver: AutoSolverFileConfig{
+ Solvers: []string{"cloudflare", "capsolver"},
+ },
+ }
+
+ errs := ValidateFileConfig(fc)
+ if len(errs) == 0 {
+ t.Fatal("expected autosolver validation error, got none")
+ }
+ found := false
+ for _, err := range errs {
+ if strings.Contains(err.Error(), "autoSolver.solvers") &&
+ strings.Contains(err.Error(), "not implemented") {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatalf("expected not implemented solver error, got %v", errs)
+ }
+}
+
+func TestValidateFileConfig_AutoSolverInvalidSolverName(t *testing.T) {
+ fc := &FileConfig{
+ AutoSolver: AutoSolverFileConfig{
+ Solvers: []string{"cloudflare", "madeupsolver"},
+ },
+ }
+
+ errs := ValidateFileConfig(fc)
+ if len(errs) == 0 {
+ t.Fatal("expected autosolver validation error, got none")
+ }
+ found := false
+ for _, err := range errs {
+ if strings.Contains(err.Error(), "autoSolver.solvers") &&
+ strings.Contains(err.Error(), "invalid solver") {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatalf("expected invalid solver name error, got %v", errs)
+ }
+}
+
+func TestValidateFileConfig_AutoSolverLLMFallbackRejected(t *testing.T) {
+ enabled := true
+ fc := &FileConfig{
+ AutoSolver: AutoSolverFileConfig{
+ LLMFallback: &enabled,
+ },
+ }
+
+ errs := ValidateFileConfig(fc)
+ if len(errs) == 0 {
+ t.Fatal("expected autosolver llmFallback validation error, got none")
+ }
+ found := false
+ for _, err := range errs {
+ if strings.Contains(err.Error(), "autoSolver.llmFallback") &&
+ strings.Contains(err.Error(), "not implemented") {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatalf("expected llm fallback not implemented error, got %v", errs)
+ }
+}
+
+func TestValidateFileConfig_AutoSolverLLMProviderRejected(t *testing.T) {
+ fc := &FileConfig{
+ AutoSolver: AutoSolverFileConfig{
+ LLMProvider: "openai",
+ },
+ }
+
+ errs := ValidateFileConfig(fc)
+ if len(errs) == 0 {
+ t.Fatal("expected autosolver llmProvider validation error, got none")
+ }
+ found := false
+ for _, err := range errs {
+ if strings.Contains(err.Error(), "autoSolver.llmProvider") &&
+ strings.Contains(err.Error(), "not implemented") {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatalf("expected llm provider not implemented error, got %v", errs)
+ }
+}
+
// --- IDPI validation tests ---
// TestValidateIDPIConfig_Disabled verifies that a disabled IDPI config produces
diff --git a/internal/handlers/actions.go b/internal/handlers/actions.go
index 41232590..cba0006c 100644
--- a/internal/handlers/actions.go
+++ b/internal/handlers/actions.go
@@ -52,6 +52,24 @@ func (h *Handlers) enforceTabLease(tabID, owner string) error {
return nil
}
+func (h *Handlers) enforceTabNotPausedForHandoff(tabID string) error {
+ if tabID == "" {
+ return nil
+ }
+ ctrl, ok := h.handoffController()
+ if !ok {
+ return nil
+ }
+ state, exists := ctrl.TabHandoffState(tabID)
+ if !exists || state.Status != "paused_handoff" {
+ return nil
+ }
+ if state.Reason != "" {
+ return fmt.Errorf("tab %s is paused for human handoff (%s)", tabID, state.Reason)
+ }
+ return fmt.Errorf("tab %s is paused for human handoff", tabID)
+}
+
// HandleAction performs a single action on a tab (click, type, fill, etc).
func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
var req bridge.ActionRequest
@@ -160,6 +178,10 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
return
}
+ if err := h.enforceTabNotPausedForHandoff(resolvedTabID); err != nil {
+ httpx.ErrorCode(w, 409, "tab_paused_handoff", err.Error(), false, nil)
+ return
+ }
}
h.recordResolvedTab(r, resolvedTabID)
w.Header().Set(activity.HeaderPTTabID, resolvedTabID)
@@ -553,6 +575,13 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
return
}
+ if err := h.enforceTabNotPausedForHandoff(resolvedTabID); err != nil {
+ results = append(results, actionResult{Index: i, Success: false, Error: err.Error()})
+ if req.StopOnError {
+ break
+ }
+ continue
+ }
}
tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
@@ -859,6 +888,13 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
return
}
+ if err := h.enforceTabNotPausedForHandoff(resolvedTabID); err != nil {
+ results = append(results, actionResult{Index: i, Success: false, Error: err.Error()})
+ if req.StopOnError {
+ break
+ }
+ continue
+ }
}
useLiteAction := h.shouldUseLiteAction(step.Kind)
// Unified selector resolution for macro steps (mirrors HandleAction).
diff --git a/internal/handlers/actions_test.go b/internal/handlers/actions_test.go
index ea9a7b89..10b10f53 100644
--- a/internal/handlers/actions_test.go
+++ b/internal/handlers/actions_test.go
@@ -9,6 +9,7 @@ import (
"net/http/httptest"
"strings"
"testing"
+ "time"
"github.com/chromedp/cdproto/target"
"github.com/pinchtab/pinchtab/internal/bridge"
@@ -31,6 +32,12 @@ type recordingActionBridge struct {
lastReq bridge.ActionRequest
}
+type handoffRecordingBridge struct {
+ mockBridge
+ state bridge.TabHandoffState
+ has bool
+}
+
func (m *liteActionBridge) AvailableActions() []string {
return []string{bridge.ActionClick, bridge.ActionType, bridge.ActionPress}
}
@@ -59,6 +66,30 @@ func (m *recordingActionBridge) ExecuteAction(ctx context.Context, kind string,
return map[string]any{"ok": true}, nil
}
+func (m *handoffRecordingBridge) SetTabHandoff(tabID, reason string, timeout time.Duration) error {
+ now := time.Now().UTC()
+ m.state = bridge.TabHandoffState{
+ Status: "paused_handoff",
+ Reason: reason,
+ PausedAt: now,
+ LastUpdatedAt: now,
+ }
+ if timeout > 0 {
+ m.state.ExpiresAt = now.Add(timeout)
+ }
+ m.has = true
+ return nil
+}
+
+func (m *handoffRecordingBridge) ResumeTabHandoff(tabID string) error {
+ m.has = false
+ return nil
+}
+
+func (m *handoffRecordingBridge) TabHandoffState(tabID string) (bridge.TabHandoffState, bool) {
+ return m.state, m.has
+}
+
type fakeLiteEngine struct {
clickRefs []string
typeCalls []struct {
@@ -523,6 +554,29 @@ func TestHandleAction_LegacyMouseKindIsRejected(t *testing.T) {
}
}
+func TestHandleAction_BlockedDuringHumanHandoff(t *testing.T) {
+ b := &handoffRecordingBridge{
+ state: bridge.TabHandoffState{
+ Status: "paused_handoff",
+ Reason: "captcha_manual",
+ PausedAt: time.Now().UTC(),
+ LastUpdatedAt: time.Now().UTC(),
+ },
+ has: true,
+ }
+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)
+
+ req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(`{"kind":"click","selector":"button"}`)))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ h.HandleAction(w, req)
+
+ if w.Code != 409 {
+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
func TestHandleMacro_Disabled(t *testing.T) {
h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
req := httptest.NewRequest("POST", "/macro", bytes.NewReader([]byte(`{"steps":[{"kind":"click","ref":"e0"}]}`)))
diff --git a/internal/handlers/handoff.go b/internal/handlers/handoff.go
index a816036c..fb5c8ef4 100644
--- a/internal/handlers/handoff.go
+++ b/internal/handlers/handoff.go
@@ -16,7 +16,7 @@ import (
)
type tabHandoffController interface {
- SetTabHandoff(tabID, reason string) error
+ SetTabHandoff(tabID, reason string, timeout time.Duration) error
ResumeTabHandoff(tabID string) error
TabHandoffState(tabID string) (bridge.TabHandoffState, bool)
}
@@ -66,7 +66,12 @@ func (h *Handlers) HandleTabHandoff(w http.ResponseWriter, r *http.Request) {
if reason == "" {
reason = "manual_handoff"
}
- if err := ctrl.SetTabHandoff(resolvedTabID, reason); err != nil {
+ timeout := time.Duration(req.TimeoutMs) * time.Millisecond
+ if req.TimeoutMs < 0 {
+ httpx.Error(w, 400, fmt.Errorf("timeoutMs must be >= 0"))
+ return
+ }
+ if err := ctrl.SetTabHandoff(resolvedTabID, reason, timeout); err != nil {
httpx.ErrorCode(w, 500, "handoff_failed", err.Error(), false, nil)
return
}
@@ -173,13 +178,18 @@ func (h *Handlers) HandleTabHandoffStatus(w http.ResponseWriter, r *http.Request
return
}
if state, ok := ctrl.TabHandoffState(resolvedTabID); ok {
- httpx.JSON(w, 200, map[string]any{
+ resp := map[string]any{
"tabId": resolvedTabID,
"status": state.Status,
"reason": state.Reason,
"pausedAt": state.PausedAt.Format(time.RFC3339),
"lastUpdatedAt": state.LastUpdatedAt.Format(time.RFC3339),
- })
+ }
+ if !state.ExpiresAt.IsZero() {
+ resp["expiresAt"] = state.ExpiresAt.Format(time.RFC3339)
+ resp["timeoutMs"] = int(state.ExpiresAt.Sub(state.PausedAt).Milliseconds())
+ }
+ httpx.JSON(w, 200, resp)
return
}
diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.go
index 99162bea..31d67a8e 100644
--- a/internal/handlers/middleware.go
+++ b/internal/handlers/middleware.go
@@ -539,6 +539,8 @@ func cookieAuthAllowed(r *http.Request) bool {
return true
case path == "/action":
return true
+ case path == "/instances/start":
+ return true
case path == "/instances/launch":
return true
case strings.HasPrefix(path, "/tabs/") && strings.HasSuffix(path, "/close"):
diff --git a/internal/handlers/middleware_action_auth_test.go b/internal/handlers/middleware_action_auth_test.go
index 7b22be45..38e7a941 100644
--- a/internal/handlers/middleware_action_auth_test.go
+++ b/internal/handlers/middleware_action_auth_test.go
@@ -11,3 +11,10 @@ func TestCookieAuthAllowed_ActionPost(t *testing.T) {
t.Fatal("expected cookie auth to allow POST /action for dashboard same-origin sessions")
}
}
+
+func TestCookieAuthAllowed_InstanceStartPost(t *testing.T) {
+ req := httptest.NewRequest("POST", "/instances/start", nil)
+ if !cookieAuthAllowed(req) {
+ t.Fatal("expected cookie auth to allow POST /instances/start for dashboard same-origin sessions")
+ }
+}
diff --git a/internal/handlers/middleware_test.go b/internal/handlers/middleware_test.go
index d4458f1d..c6d58a64 100644
--- a/internal/handlers/middleware_test.go
+++ b/internal/handlers/middleware_test.go
@@ -286,6 +286,34 @@ func TestAuthMiddleware_CookieAllowsActionEndpoint(t *testing.T) {
}
}
+func TestAuthMiddleware_CookieAllowsInstanceStartEndpoint(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+ sessions := browsersession.NewManager(browsersession.Config{})
+ sessionID, err := sessions.Create(cfg.Token)
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest(http.MethodPost, "/instances/start", nil)
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ req.Header.Set("Origin", "http://example.com")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if !called {
+ t.Fatal("handler should allow same-origin cookie-authenticated instance start from the dashboard")
+ }
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+}
+
func TestAuthMiddleware_CookieCrossOriginRejected(t *testing.T) {
cfg := &config.RuntimeConfig{Token: "secret123"}
sessions := browsersession.NewManager(browsersession.Config{})