Skip to content

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

refactor: generic solver framework with Cloudflare as first implementation

Ariaa19a69e46881
diff --git a/docs/endpoints.md b/docs/endpoints.md
index f808ea46..e51520c4 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -271,6 +271,25 @@ Console and error routes use query parameters:
- `tabId`
- `limit`
+## Challenge Solvers
+
+```text
+GET /solvers
+POST /solve
+POST /solve/{name}
+POST /tabs/{id}/solve
+POST /tabs/{id}/solve/{name}
+```
+
+The solver framework auto-detects and resolves browser challenges (Cloudflare Turnstile, etc.). See [Solve reference](./reference/solve.md) for details.
+
+Solve body fields:
+
+- `solver` optional solver name (auto-detect when omitted)
+- `tabId` optional
+- `maxAttempts` optional (default: 3)
+- `timeout` optional in ms (default: 30000)
+
## Profiles And Instances
```text
diff --git a/docs/reference/index.md b/docs/reference/index.md
index 5f5af9f3..c300210d 100644
--- a/docs/reference/index.md
+++ b/docs/reference/index.md
@@ -23,6 +23,7 @@ Note: this index is generated and should be checked against the code when comman
- [Scroll](./scroll.md)
- [Select](./select.md)
- [Snapshot](./snapshot.md)
+- [Solve](./solve.md)
- [Strategies](./strategies.md)
- [Tabs](./tabs.md)
- [Text](./text.md)
diff --git a/docs/reference/solve.md b/docs/reference/solve.md
new file mode 100644
index 00000000..3ce42425
--- /dev/null
+++ b/docs/reference/solve.md
@@ -0,0 +1,155 @@
+# Solve
+
+Detect and solve browser challenges (Cloudflare Turnstile, CAPTCHAs, interstitials, etc.) on the current page.
+
+PinchTab ships with a pluggable **solver framework**. Each solver targets a specific provider (e.g. Cloudflare). Solvers are registered at startup and can be invoked explicitly by name or discovered automatically.
+
+## Endpoints
+
+```text
+GET /solvers
+POST /solve
+POST /solve/{name}
+POST /tabs/{id}/solve
+POST /tabs/{id}/solve/{name}
+```
+
+## List Solvers
+
+```bash
+curl http://localhost:9867/solvers
+```
+
+```json
+{
+ "solvers": ["cloudflare"]
+}
+```
+
+## Auto-Detect Solve
+
+When no `solver` field is provided, PinchTab tries each registered solver in order. The first one whose `CanHandle` returns true is used.
+
+```bash
+curl -X POST http://localhost:9867/solve \
+ -H "Content-Type: application/json" \
+ -d '{"maxAttempts": 3, "timeout": 30000}'
+```
+
+If no challenge is detected on the page, the response returns immediately with `solved: true` and `attempts: 0`.
+
+## Named Solver
+
+Specify the solver by name in the body or path:
+
+```bash
+# Body
+curl -X POST http://localhost:9867/solve \
+ -H "Content-Type: application/json" \
+ -d '{"solver": "cloudflare", "maxAttempts": 3}'
+
+# Path
+curl -X POST http://localhost:9867/solve/cloudflare \
+ -H "Content-Type: application/json" \
+ -d '{"maxAttempts": 3}'
+```
+
+## Tab-Scoped Solve
+
+```bash
+curl -X POST http://localhost:9867/tabs/{tabId}/solve \
+ -H "Content-Type: application/json" \
+ -d '{"solver": "cloudflare"}'
+```
+
+## Request Body
+
+| Field | Type | Default | Description |
+|--------------|--------|---------|------------------------------------------|
+| `tabId` | string | — | Tab ID (optional, uses default tab) |
+| `solver` | string | — | Solver name (optional, auto-detect) |
+| `maxAttempts`| int | 3 | Maximum solve attempts |
+| `timeout` | float | 30000 | Overall timeout in milliseconds |
+
+## Response
+
+```json
+{
+ "tabId": "DEADBEEF",
+ "solver": "cloudflare",
+ "solved": true,
+ "challengeType": "managed",
+ "attempts": 1,
+ "title": "thuisbezorgd.nl"
+}
+```
+
+| Field | Type | Description |
+|-----------------|--------|------------------------------------------------|
+| `tabId` | string | Tab the solve ran on |
+| `solver` | string | Which solver handled the challenge |
+| `solved` | bool | Whether the challenge was resolved |
+| `challengeType` | string | Challenge variant (e.g. `managed`, `embedded`) |
+| `attempts` | int | Number of attempts made |
+| `title` | string | Final page title |
+
+## Error Responses
+
+| Code | Meaning |
+|------|----------------------------------------|
+| 400 | Invalid body or unknown solver name |
+| 404 | Tab not found |
+| 423 | Tab locked by another owner |
+| 500 | CDP/Chrome error |
+
+## Built-In Solvers
+
+### Cloudflare (`cloudflare`)
+
+Handles Cloudflare Turnstile and interstitial challenges.
+
+**Detection**: Checks the page title for known Cloudflare indicators ("Just a moment...", "Attention Required", "Checking your browser").
+
+**Challenge types**:
+
+| Type | Handling |
+|-------------------|--------------------------------------------------------|
+| `non-interactive` | Waits for auto-resolution (up to 15s) |
+| `managed` | Locates Turnstile iframe, clicks checkbox |
+| `interactive` | Same as managed |
+| `embedded` | Detects via Turnstile script tag, clicks checkbox |
+
+**Click strategy**: The solver uses human-like mouse input (Bezier curve movement, random delays, press/release offset) to click the Turnstile checkbox. Click coordinates are computed relative to the widget dimensions (not hardcoded pixel offsets) with randomised jitter.
+
+## Writing a Custom Solver
+
+Implement the `solver.Solver` interface and register it during `init()`:
+
+```go
+package mygateway
+
+import (
+ "context"
+ "github.com/pinchtab/pinchtab/internal/solver"
+)
+
+func init() {
+ solver.MustRegister("mygateway", &MyGatewaySolver{})
+}
+
+type MyGatewaySolver struct{}
+
+func (s *MyGatewaySolver) Name() string { return "mygateway" }
+
+func (s *MyGatewaySolver) CanHandle(ctx context.Context) (bool, error) {
+ // Check page markers (title, DOM elements, etc.)
+ return false, nil
+}
+
+func (s *MyGatewaySolver) Solve(ctx context.Context, opts solver.Options) (*solver.Result, error) {
+ // Detect, interact, and resolve the challenge.
+ return &solver.Result{Solver: "mygateway", Solved: true}, nil
+}
+```
+
+The solver has access to the full chromedp context for CDP operations.
diff --git a/internal/bridge/cloudflare.go b/internal/bridge/cloudflare.go
index 4fc6b4a7..1c4cee60 100644
--- a/internal/bridge/cloudflare.go
+++ b/internal/bridge/cloudflare.go
@@ -7,32 +7,37 @@ import (
"time"
"github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/solver"
)
-// CloudflareResult holds the outcome of a Cloudflare solve attempt.
-type CloudflareResult struct {
- Solved bool `json:"solved"`
- ChallengeType string `json:"challengeType,omitempty"`
- Attempts int `json:"attempts"`
- Title string `json:"title"`
+func init() {
+ solver.MustRegister("cloudflare", &CloudflareSolver{})
}
-type cfBoundingBox struct {
- X float64
- Y float64
- Width float64
- Height float64
+// CloudflareSolver detects and solves Cloudflare Turnstile/Interstitial challenges.
+// It locates the Turnstile iframe, clicks the checkbox with human-like input,
+// and polls for resolution.
+type CloudflareSolver struct{}
+
+func (s *CloudflareSolver) Name() string { return "cloudflare" }
+
+// CanHandle checks the page title for known Cloudflare challenge indicators.
+func (s *CloudflareSolver) CanHandle(ctx context.Context) (bool, error) {
+ var title string
+ if err := chromedp.Run(ctx, chromedp.Title(&title)); err != nil {
+ return false, fmt.Errorf("get title: %w", err)
+ }
+ return isCFChallenge(title), nil
}
-// SolveCloudflare detects and solves Cloudflare Turnstile/Interstitial challenges.
-// It finds the Turnstile iframe and clicks the checkbox using human-like mouse input.
-// The caller is responsible for setting context deadlines.
-func SolveCloudflare(ctx context.Context, maxAttempts int) (*CloudflareResult, error) {
+// Solve attempts to resolve the Cloudflare challenge on the current page.
+func (s *CloudflareSolver) Solve(ctx context.Context, opts solver.Options) (*solver.Result, error) {
+ maxAttempts := opts.MaxAttempts
if maxAttempts <= 0 {
maxAttempts = 3
}
- result := &CloudflareResult{}
+ result := &solver.Result{Solver: "cloudflare"}
var title string
if err := chromedp.Run(ctx, chromedp.Title(&title)); err != nil {
@@ -74,8 +79,14 @@ func SolveCloudflare(ctx context.Context, maxAttempts int) (*CloudflareResult, e
continue
}
- clickX := box.X + float64(26+humanRand.Intn(3))
- clickY := box.Y + float64(25+humanRand.Intn(3))
+ // Click the checkbox area using relative positioning within the
+ // Turnstile widget. The checkbox sits in the left portion (~9% from
+ // the left edge, ~40% from the top). Wider random offsets (+-4px)
+ // make the click pattern harder to fingerprint.
+ checkboxX := box.X + box.Width*0.09
+ checkboxY := box.Y + box.Height*0.40
+ clickX := checkboxX + (humanRand.Float64()-0.5)*8
+ clickY := checkboxY + (humanRand.Float64()-0.5)*8
if err := Click(ctx, clickX, clickY); err != nil {
return result, fmt.Errorf("click turnstile: %w", err)
@@ -99,6 +110,17 @@ func SolveCloudflare(ctx context.Context, maxAttempts int) (*CloudflareResult, e
return result, nil
}
+// ---------------------------------------------------------------------------
+// Internal helpers
+// ---------------------------------------------------------------------------
+
+type cfBoundingBox struct {
+ X float64
+ Y float64
+ Width float64
+ Height float64
+}
+
func isCFChallenge(title string) bool {
lower := strings.ToLower(title)
return strings.Contains(lower, "just a moment") ||
@@ -200,7 +222,7 @@ func waitForCFSpinner(ctx context.Context, timeout time.Duration) {
}
}
-func waitForCFResolve(ctx context.Context, result *CloudflareResult, timeout time.Duration) (*CloudflareResult, error) {
+func waitForCFResolve(ctx context.Context, result *solver.Result, timeout time.Duration) (*solver.Result, error) {
deadline := time.After(timeout)
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
diff --git a/internal/bridge/cloudflare_test.go b/internal/bridge/cloudflare_test.go
new file mode 100644
index 00000000..4959f90c
--- /dev/null
+++ b/internal/bridge/cloudflare_test.go
@@ -0,0 +1,33 @@
+package bridge
+
+import "testing"
+
+func TestIsCFChallenge(t *testing.T) {
+ tests := []struct {
+ title string
+ want bool
+ }{
+ {"Just a moment...", true},
+ {"JUST A MOMENT...", true},
+ {"Attention Required | Cloudflare", true},
+ {"Checking your browser before accessing...", true},
+ {"Google", false},
+ {"", false},
+ {"My Cool Website", false},
+ {"just a moment", true},
+ {"Please wait - Checking Your Browser", true},
+ }
+ for _, tt := range tests {
+ got := isCFChallenge(tt.title)
+ if got != tt.want {
+ t.Errorf("isCFChallenge(%q) = %v, want %v", tt.title, got, tt.want)
+ }
+ }
+}
+
+func TestCloudflareSolverName(t *testing.T) {
+ s := &CloudflareSolver{}
+ if s.Name() != "cloudflare" {
+ t.Errorf("expected name 'cloudflare', got %q", s.Name())
+ }
+}
diff --git a/internal/handlers/cloudflare.go b/internal/handlers/cloudflare.go
deleted file mode 100644
index 870dd2eb..00000000
--- a/internal/handlers/cloudflare.go
+++ /dev/null
@@ -1,126 +0,0 @@
-package handlers
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "net/http"
- "time"
-
- "github.com/pinchtab/pinchtab/internal/activity"
- "github.com/pinchtab/pinchtab/internal/bridge"
- "github.com/pinchtab/pinchtab/internal/httpx"
-)
-
-// HandleSolveCloudflare attempts to solve a Cloudflare Turnstile challenge on the current page.
-//
-// @Endpoint POST /solve-cloudflare
-// @Description Detect and solve Cloudflare Turnstile/Interstitial challenges
-//
-// @Param tabId string body Tab ID (optional — uses default tab)
-// @Param maxAttempts int body Max solve attempts (optional, default: 3)
-// @Param timeout float64 body Timeout in ms (optional, default: 30000)
-//
-// @Response 200 application/json Returns {tabId, solved, challengeType, attempts, title}
-// @Response 400 application/json Invalid request body or parameters
-// @Response 423 application/json Tab is locked by another owner
-// @Response 500 application/json Chrome/CDP error
-//
-// @Example curl:
-//
-// curl -X POST http://localhost:9867/solve-cloudflare \
-// -H "Content-Type: application/json" \
-// -d '{"maxAttempts": 3, "timeout": 30000}'
-//
-// @Example cli:
-//
-// pinchtab solve-cf
-func (h *Handlers) HandleSolveCloudflare(w http.ResponseWriter, r *http.Request) {
- var req struct {
- TabID string `json:"tabId"`
- MaxAttempts int `json:"maxAttempts"`
- Timeout float64 `json:"timeout"`
- }
-
- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
- return
- }
-
- ctx, resolvedTabID, err := h.tabContext(r, req.TabID)
- if err != nil {
- httpx.Error(w, 404, err)
- return
- }
-
- owner := resolveOwner(r, "")
- if err := h.enforceTabLease(resolvedTabID, owner); err != nil {
- httpx.ErrorCode(w, 423, "tab_locked", err.Error(), false, nil)
- return
- }
-
- if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
- return
- }
-
- h.recordActivity(r, activity.Update{Action: "solve-cloudflare", TabID: resolvedTabID})
-
- timeout := 30 * time.Second
- if req.Timeout > 0 {
- timeout = time.Duration(req.Timeout) * time.Millisecond
- }
-
- tCtx, tCancel := context.WithTimeout(ctx, timeout)
- defer tCancel()
- go httpx.CancelOnClientDone(r.Context(), tCancel)
-
- result, err := bridge.SolveCloudflare(tCtx, req.MaxAttempts)
- if err != nil {
- httpx.Error(w, 500, fmt.Errorf("solve cloudflare: %w", err))
- return
- }
-
- httpx.JSON(w, 200, map[string]any{
- "tabId": resolvedTabID,
- "solved": result.Solved,
- "challengeType": result.ChallengeType,
- "attempts": result.Attempts,
- "title": result.Title,
- })
-}
-
-// HandleTabSolveCloudflare handles POST /tabs/{id}/solve-cloudflare.
-//
-// @Endpoint POST /tabs/{id}/solve-cloudflare
-// @Description Solve Cloudflare challenge on a specific tab
-func (h *Handlers) HandleTabSolveCloudflare(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- httpx.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- body := map[string]any{}
- dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))
- if err := dec.Decode(&body); err != nil && !errors.Is(err, io.EOF) {
- httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
- return
- }
-
- body["tabId"] = tabID
- payload, err := json.Marshal(body)
- if err != nil {
- httpx.Error(w, 500, fmt.Errorf("encode: %w", err))
- return
- }
-
- cloned := r.Clone(r.Context())
- cloned.Body = io.NopCloser(bytes.NewReader(payload))
- cloned.ContentLength = int64(len(payload))
- cloned.Header = r.Header.Clone()
- cloned.Header.Set("Content-Type", "application/json")
- h.HandleSolveCloudflare(w, cloned)
-}
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index ef60ce6a..48fa136f 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -137,8 +137,11 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {
mux.HandleFunc("POST /tabs/{id}/cookies", h.HandleTabSetCookies)
mux.HandleFunc("GET /cookies", h.HandleGetCookies)
mux.HandleFunc("POST /cookies", h.HandleSetCookies)
- mux.HandleFunc("POST /solve-cloudflare", h.HandleSolveCloudflare)
- mux.HandleFunc("POST /tabs/{id}/solve-cloudflare", h.HandleTabSolveCloudflare)
+ mux.HandleFunc("GET /solvers", h.HandleListSolvers)
+ mux.HandleFunc("POST /solve", h.HandleSolve)
+ mux.HandleFunc("POST /solve/{name}", h.HandleSolve)
+ mux.HandleFunc("POST /tabs/{id}/solve", h.HandleTabSolve)
+ mux.HandleFunc("POST /tabs/{id}/solve/{name}", h.HandleTabSolve)
mux.HandleFunc("POST /fingerprint/rotate", h.HandleFingerprintRotate)
mux.HandleFunc("GET /stealth/status", h.HandleStealthStatus)
mux.HandleFunc("GET /tabs/{id}/download", h.HandleTabDownload)
diff --git a/internal/handlers/solver.go b/internal/handlers/solver.go
new file mode 100644
index 00000000..1be0db2a
--- /dev/null
+++ b/internal/handlers/solver.go
@@ -0,0 +1,170 @@
+package handlers
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/activity"
+ "github.com/pinchtab/pinchtab/internal/httpx"
+ "github.com/pinchtab/pinchtab/internal/solver"
+
+ // Register built-in solvers via init().
+ _ "github.com/pinchtab/pinchtab/internal/bridge"
+)
+
+// HandleSolve attempts to solve a browser challenge on the current page.
+//
+// When "solver" is omitted from the request body, all registered solvers are
+// tried in order via auto-detection. When "solver" is set (e.g. "cloudflare"),
+// only that solver is invoked.
+//
+// @Endpoint POST /solve
+// @Description Auto-detect and solve browser challenges (Cloudflare, etc.)
+//
+// @Param tabId string body Tab ID (optional — uses default tab)
+// @Param solver string body Solver name (optional — auto-detect)
+// @Param maxAttempts int body Max solve attempts (optional, default: 3)
+// @Param timeout float64 body Timeout in ms (optional, default: 30000)
+//
+// @Response 200 application/json Returns {tabId, solver, solved, challengeType, attempts, title}
+// @Response 400 application/json Invalid request body or unknown solver
+// @Response 423 application/json Tab is locked by another owner
+// @Response 500 application/json Chrome/CDP error
+//
+// @Example curl:
+//
+// curl -X POST http://localhost:9867/solve \
+// -H "Content-Type: application/json" \
+// -d '{"maxAttempts": 3, "timeout": 30000}'
+//
+// @Example curl (specific solver):
+//
+// curl -X POST http://localhost:9867/solve \
+// -H "Content-Type: application/json" \
+// -d '{"solver": "cloudflare", "maxAttempts": 3}'
+func (h *Handlers) HandleSolve(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ TabID string `json:"tabId"`
+ Solver string `json:"solver"`
+ MaxAttempts int `json:"maxAttempts"`
+ Timeout float64 `json:"timeout"`
+ }
+
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
+
+ // If a solver name is provided in the path, use it.
+ if name := r.PathValue("name"); name != "" {
+ req.Solver = name
+ }
+
+ // Validate solver name early.
+ if req.Solver != "" {
+ if _, ok := solver.Get(req.Solver); !ok {
+ httpx.ErrorCode(w, 400, "unknown_solver",
+ fmt.Sprintf("unknown solver %q (available: %v)", req.Solver, solver.Names()),
+ false, nil)
+ return
+ }
+ }
+
+ ctx, resolvedTabID, err := h.tabContext(r, req.TabID)
+ if err != nil {
+ httpx.Error(w, 404, err)
+ return
+ }
+
+ owner := resolveOwner(r, "")
+ if err := h.enforceTabLease(resolvedTabID, owner); err != nil {
+ httpx.ErrorCode(w, 423, "tab_locked", err.Error(), false, nil)
+ return
+ }
+
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
+ return
+ }
+
+ action := "solve"
+ if req.Solver != "" {
+ action = "solve:" + req.Solver
+ }
+ h.recordActivity(r, activity.Update{Action: action, TabID: resolvedTabID})
+
+ timeout := 30 * time.Second
+ if req.Timeout > 0 {
+ timeout = time.Duration(req.Timeout) * time.Millisecond
+ }
+
+ tCtx, tCancel := context.WithTimeout(ctx, timeout)
+ defer tCancel()
+ go httpx.CancelOnClientDone(r.Context(), tCancel)
+
+ result, err := solver.Solve(tCtx, req.Solver, solver.Options{
+ MaxAttempts: req.MaxAttempts,
+ })
+ if err != nil {
+ httpx.Error(w, 500, fmt.Errorf("solve: %w", err))
+ return
+ }
+
+ httpx.JSON(w, 200, map[string]any{
+ "tabId": resolvedTabID,
+ "solver": result.Solver,
+ "solved": result.Solved,
+ "challengeType": result.ChallengeType,
+ "attempts": result.Attempts,
+ "title": result.Title,
+ })
+}
+
+// HandleTabSolve handles POST /tabs/{id}/solve and /tabs/{id}/solve/{name}.
+//
+// @Endpoint POST /tabs/{id}/solve
+// @Description Solve a browser challenge on a specific tab
+func (h *Handlers) HandleTabSolve(w http.ResponseWriter, r *http.Request) {
+ tabID := r.PathValue("id")
+ if tabID == "" {
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
+ return
+ }
+
+ body := map[string]any{}
+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))
+ if err := dec.Decode(&body); err != nil && !errors.Is(err, io.EOF) {
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
+
+ body["tabId"] = tabID
+ payload, err := json.Marshal(body)
+ if err != nil {
+ httpx.Error(w, 500, fmt.Errorf("encode: %w", err))
+ return
+ }
+
+ cloned := r.Clone(r.Context())
+ cloned.Body = io.NopCloser(bytes.NewReader(payload))
+ cloned.ContentLength = int64(len(payload))
+ cloned.Header = r.Header.Clone()
+ cloned.Header.Set("Content-Type", "application/json")
+ h.HandleSolve(w, cloned)
+}
+
+// HandleListSolvers returns the list of registered solver names.
+//
+// @Endpoint GET /solvers
+// @Description List available challenge solvers
+// @Response 200 application/json Returns {solvers: ["cloudflare", ...]}
+func (h *Handlers) HandleListSolvers(w http.ResponseWriter, r *http.Request) {
+ httpx.JSON(w, 200, map[string]any{
+ "solvers": solver.Names(),
+ })
+}
diff --git a/internal/handlers/solver_test.go b/internal/handlers/solver_test.go
new file mode 100644
index 00000000..9f710747
--- /dev/null
+++ b/internal/handlers/solver_test.go
@@ -0,0 +1,172 @@
+package handlers
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/solver"
+)
+
+func TestHandleListSolvers(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+
+ req := httptest.NewRequest("GET", "/solvers", nil)
+ w := httptest.NewRecorder()
+ h.HandleListSolvers(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+
+ var resp map[string][]string
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ solvers, ok := resp["solvers"]
+ if !ok {
+ t.Fatal("expected 'solvers' key in response")
+ }
+
+ // cloudflare solver is registered via bridge init
+ found := false
+ for _, s := range solvers {
+ if s == "cloudflare" {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Errorf("expected cloudflare in solvers list, got %v", solvers)
+ }
+}
+
+func TestHandleSolve_InvalidBody(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+
+ req := httptest.NewRequest("POST", "/solve", bytes.NewReader([]byte("not json")))
+ w := httptest.NewRecorder()
+ h.HandleSolve(w, req)
+
+ if w.Code != 400 {
+ t.Errorf("expected 400 for invalid body, got %d", w.Code)
+ }
+}
+
+func TestHandleSolve_UnknownSolver(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+
+ body := `{"solver": "nonexistent"}`
+ req := httptest.NewRequest("POST", "/solve", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ h.HandleSolve(w, req)
+
+ if w.Code != 400 {
+ t.Errorf("expected 400 for unknown solver, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleSolve_TabNotFound(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+
+ body := `{"tabId": "nonexistent"}`
+ req := httptest.NewRequest("POST", "/solve", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ h.HandleSolve(w, req)
+
+ if w.Code != 404 {
+ t.Errorf("expected 404 for bad tab, got %d", w.Code)
+ }
+}
+
+func TestHandleSolve_AutoDetect(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+
+ body := `{"maxAttempts": 1}`
+ req := httptest.NewRequest("POST", "/solve", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ h.HandleSolve(w, req)
+
+ // With a mock chromedp context the solver may fail inside chromedp.Run,
+ // but the handler should not panic. Accept 200 (no challenge on blank
+ // page) or 500 (CDP error with mock context).
+ if w.Code != 200 && w.Code != 500 {
+ t.Errorf("unexpected status %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleTabSolve(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ mux := http.NewServeMux()
+ h.RegisterRoutes(mux, nil)
+
+ body := `{"maxAttempts": 1}`
+ req := httptest.NewRequest("POST", "/tabs/tab1/solve", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 200 && w.Code != 500 {
+ t.Errorf("unexpected status %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleSolve_NamedSolver(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+
+ body := `{"solver": "cloudflare", "maxAttempts": 1}`
+ req := httptest.NewRequest("POST", "/solve", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ h.HandleSolve(w, req)
+
+ if w.Code != 200 && w.Code != 500 {
+ t.Errorf("unexpected status %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleSolve_PathSolver(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ mux := http.NewServeMux()
+ h.RegisterRoutes(mux, nil)
+
+ body := `{"maxAttempts": 1}`
+ req := httptest.NewRequest("POST", "/solve/cloudflare", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 200 && w.Code != 500 {
+ t.Errorf("unexpected status %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleSolve_PathUnknownSolver(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ mux := http.NewServeMux()
+ h.RegisterRoutes(mux, nil)
+
+ body := `{}`
+ req := httptest.NewRequest("POST", "/solve/bogus", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 400 {
+ t.Errorf("expected 400 for unknown path solver, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+// Verify solver.Names includes cloudflare (registered by bridge init).
+func TestCloudflareSolverRegistered(t *testing.T) {
+ names := solver.Names()
+ found := false
+ for _, n := range names {
+ if n == "cloudflare" {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Errorf("cloudflare solver not registered: %v", names)
+ }
+}
diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.go
index 637e9b3b..93fbbe56 100644
--- a/internal/orchestrator/handlers.go
+++ b/internal/orchestrator/handlers.go
@@ -78,7 +78,8 @@ func (o *Orchestrator) registerHandlers(mux *http.ServeMux, skipLaunch bool) {
"POST /tabs/{id}/forward",
"POST /tabs/{id}/reload",
"POST /tabs/{id}/wait",
- "POST /tabs/{id}/solve-cloudflare",
+ "POST /tabs/{id}/solve",
+ "POST /tabs/{id}/solve/{name}",
} {
mux.HandleFunc(route, o.proxyTabRequest)
}
diff --git a/internal/solver/solver.go b/internal/solver/solver.go
new file mode 100644
index 00000000..608a733c
--- /dev/null
+++ b/internal/solver/solver.go
@@ -0,0 +1,139 @@
+// Package solver defines the interface for pluggable challenge solvers.
+//
+// A Solver handles a specific class of browser challenge (CAPTCHA, interstitial,
+// bot gate, etc.). Solvers are registered by name and can be invoked explicitly
+// or auto-detected via CanHandle.
+//
+// Example registration (in init):
+//
+// solver.MustRegister("cloudflare", &CloudflareSolver{})
+package solver
+
+import (
+ "context"
+ "fmt"
+ "sync"
+)
+
+// Solver handles a specific type of browser challenge.
+type Solver interface {
+ // Name returns the solver identifier (e.g., "cloudflare").
+ Name() string
+
+ // CanHandle reports whether this solver recognises a challenge on the
+ // current page. Implementations should be lightweight (title check, DOM
+ // marker) and avoid side-effects.
+ CanHandle(ctx context.Context) (bool, error)
+
+ // Solve attempts to resolve the challenge on the current page.
+ Solve(ctx context.Context, opts Options) (*Result, error)
+}
+
+// Options configures a solve attempt.
+type Options struct {
+ MaxAttempts int `json:"maxAttempts,omitempty"`
+}
+
+// Result is the outcome of a solve attempt.
+type Result struct {
+ Solver string `json:"solver,omitempty"`
+ Solved bool `json:"solved"`
+ ChallengeType string `json:"challengeType,omitempty"`
+ Attempts int `json:"attempts"`
+ Title string `json:"title"`
+ Token string `json:"token,omitempty"`
+}
+
+// ---------------------------------------------------------------------------
+// Registry
+// ---------------------------------------------------------------------------
+
+var (
+ registry = make(map[string]Solver)
+ order []string // insertion order for deterministic auto-detect
+ mu sync.RWMutex
+)
+
+// Register adds a solver to the global registry.
+func Register(name string, s Solver) error {
+ mu.Lock()
+ defer mu.Unlock()
+ if _, exists := registry[name]; exists {
+ return fmt.Errorf("solver %q already registered", name)
+ }
+ registry[name] = s
+ order = append(order, name)
+ return nil
+}
+
+// MustRegister is like Register but panics on duplicate name.
+func MustRegister(name string, s Solver) {
+ if err := Register(name, s); err != nil {
+ panic(err)
+ }
+}
+
+// Get returns a solver by name.
+func Get(name string) (Solver, bool) {
+ mu.RLock()
+ defer mu.RUnlock()
+ s, ok := registry[name]
+ return s, ok
+}
+
+// Names returns all registered solver names in registration order.
+func Names() []string {
+ mu.RLock()
+ defer mu.RUnlock()
+ out := make([]string, len(order))
+ copy(out, order)
+ return out
+}
+
+// Solve invokes a named solver, or if name is empty, auto-detects the first
+// solver whose CanHandle returns true. When no challenge is detected, it
+// returns a Result with Solved=true and Attempts=0.
+func Solve(ctx context.Context, name string, opts Options) (*Result, error) {
+ if name != "" {
+ s, ok := Get(name)
+ if !ok {
+ return nil, fmt.Errorf("unknown solver: %s (available: %v)", name, Names())
+ }
+ return s.Solve(ctx, opts)
+ }
+
+ // Auto-detect: try each registered solver in order.
+ mu.RLock()
+ names := make([]string, len(order))
+ copy(names, order)
+ mu.RUnlock()
+
+ for _, n := range names {
+ s, _ := Get(n)
+ if s == nil {
+ continue
+ }
+ can, err := s.CanHandle(ctx)
+ if err != nil || !can {
+ continue
+ }
+ return s.Solve(ctx, opts)
+ }
+
+ // No challenge detected on the current page.
+ var title string
+ return &Result{Solved: true, Title: title}, nil
+}
+
+// Unregister removes a solver from the registry. Intended for tests only.
+func Unregister(name string) {
+ mu.Lock()
+ defer mu.Unlock()
+ delete(registry, name)
+ for i, n := range order {
+ if n == name {
+ order = append(order[:i], order[i+1:]...)
+ break
+ }
+ }
+}
diff --git a/internal/solver/solver_test.go b/internal/solver/solver_test.go
new file mode 100644
index 00000000..cb2282b6
--- /dev/null
+++ b/internal/solver/solver_test.go
@@ -0,0 +1,170 @@
+package solver
+
+import (
+ "context"
+ "testing"
+)
+
+type fakeSolver struct {
+ name string
+ canHandle bool
+ result *Result
+ err error
+}
+
+func (f *fakeSolver) Name() string { return f.name }
+func (f *fakeSolver) CanHandle(ctx context.Context) (bool, error) {
+ return f.canHandle, nil
+}
+func (f *fakeSolver) Solve(ctx context.Context, opts Options) (*Result, error) {
+ return f.result, f.err
+}
+
+func TestRegister(t *testing.T) {
+ defer cleanup("test-reg")
+
+ err := Register("test-reg", &fakeSolver{name: "test-reg"})
+ if err != nil {
+ t.Fatalf("Register failed: %v", err)
+ }
+
+ err = Register("test-reg", &fakeSolver{name: "test-reg"})
+ if err == nil {
+ t.Fatal("expected error for duplicate registration")
+ }
+}
+
+func TestMustRegisterPanicsOnDuplicate(t *testing.T) {
+ defer cleanup("test-must")
+
+ MustRegister("test-must", &fakeSolver{name: "test-must"})
+
+ defer func() {
+ if r := recover(); r == nil {
+ t.Fatal("expected panic for duplicate MustRegister")
+ }
+ }()
+ MustRegister("test-must", &fakeSolver{name: "test-must"})
+}
+
+func TestGet(t *testing.T) {
+ defer cleanup("test-get")
+
+ Register("test-get", &fakeSolver{name: "test-get"})
+
+ s, ok := Get("test-get")
+ if !ok || s == nil {
+ t.Fatal("expected solver to be found")
+ }
+ if s.Name() != "test-get" {
+ t.Errorf("expected name 'test-get', got %q", s.Name())
+ }
+
+ _, ok = Get("nonexistent")
+ if ok {
+ t.Error("expected false for unknown solver")
+ }
+}
+
+func TestNames(t *testing.T) {
+ defer cleanup("test-names-a")
+ defer cleanup("test-names-b")
+
+ Register("test-names-a", &fakeSolver{name: "a"})
+ Register("test-names-b", &fakeSolver{name: "b"})
+
+ names := Names()
+ found := map[string]bool{}
+ for _, n := range names {
+ found[n] = true
+ }
+ if !found["test-names-a"] {
+ t.Error("missing test-names-a")
+ }
+ if !found["test-names-b"] {
+ t.Error("missing test-names-b")
+ }
+}
+
+func TestSolve_Named(t *testing.T) {
+ defer cleanup("test-solve")
+
+ expected := &Result{Solver: "test-solve", Solved: true, Attempts: 1}
+ Register("test-solve", &fakeSolver{
+ name: "test-solve",
+ canHandle: true,
+ result: expected,
+ })
+
+ result, err := Solve(context.Background(), "test-solve", Options{MaxAttempts: 3})
+ if err != nil {
+ t.Fatalf("Solve failed: %v", err)
+ }
+ if !result.Solved {
+ t.Error("expected Solved=true")
+ }
+ if result.Solver != "test-solve" {
+ t.Errorf("expected solver 'test-solve', got %q", result.Solver)
+ }
+}
+
+func TestSolve_Unknown(t *testing.T) {
+ _, err := Solve(context.Background(), "does-not-exist", Options{})
+ if err == nil {
+ t.Fatal("expected error for unknown solver")
+ }
+}
+
+func TestSolve_AutoDetect(t *testing.T) {
+ defer cleanup("test-auto-no")
+ defer cleanup("test-auto-yes")
+
+ Register("test-auto-no", &fakeSolver{
+ name: "test-auto-no",
+ canHandle: false,
+ })
+ Register("test-auto-yes", &fakeSolver{
+ name: "test-auto-yes",
+ canHandle: true,
+ result: &Result{Solver: "test-auto-yes", Solved: true},
+ })
+
+ result, err := Solve(context.Background(), "", Options{})
+ if err != nil {
+ t.Fatalf("auto-detect Solve failed: %v", err)
+ }
+ if result.Solver != "test-auto-yes" {
+ t.Errorf("expected solver 'test-auto-yes', got %q", result.Solver)
+ }
+}
+
+func TestSolve_NoChallenge(t *testing.T) {
+ defer cleanup("test-noop")
+
+ Register("test-noop", &fakeSolver{
+ name: "test-noop",
+ canHandle: false,
+ })
+
+ result, err := Solve(context.Background(), "", Options{})
+ if err != nil {
+ t.Fatalf("Solve failed: %v", err)
+ }
+ if !result.Solved {
+ t.Error("expected Solved=true when no challenge detected")
+ }
+}
+
+func TestUnregister(t *testing.T) {
+ Register("test-unreg", &fakeSolver{name: "test-unreg"})
+ Unregister("test-unreg")
+
+ _, ok := Get("test-unreg")
+ if ok {
+ t.Error("expected solver to be gone after Unregister")
+ }
+}
+
+func cleanup(name string) {
+ Unregister(name)
+}
diff --git a/internal/strategy/autorestart/autorestart.go b/internal/strategy/autorestart/autorestart.go
index 8c8734e7..62af7a9b 100644
--- a/internal/strategy/autorestart/autorestart.go
+++ b/internal/strategy/autorestart/autorestart.go
@@ -188,7 +188,8 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
"GET /cookies", "POST /cookies",
"GET /stealth/status", "POST /fingerprint/rotate",
"POST /find",
- "POST /solve-cloudflare",
+ "GET /solvers",
+ "POST /solve", "POST /solve/{name}",
}
for _, route := range shorthandRoutes {
mux.HandleFunc(route, s.proxyToManaged)
diff --git a/internal/strategy/explicit/explicit.go b/internal/strategy/explicit/explicit.go
index f825498a..fe277b5f 100644
--- a/internal/strategy/explicit/explicit.go
+++ b/internal/strategy/explicit/explicit.go
@@ -51,7 +51,8 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
"GET /cookies", "POST /cookies",
"GET /stealth/status", "POST /fingerprint/rotate",
"POST /find",
- "POST /solve-cloudflare",
+ "GET /solvers",
+ "POST /solve", "POST /solve/{name}",
}
for _, route := range shorthandRoutes {
mux.HandleFunc(route, s.proxyToFirst)
diff --git a/internal/strategy/noinstance/noinstance.go b/internal/strategy/noinstance/noinstance.go
index 2c9096a3..8d5e2c43 100644
--- a/internal/strategy/noinstance/noinstance.go
+++ b/internal/strategy/noinstance/noinstance.go
@@ -47,7 +47,8 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
"GET /cookies", "POST /cookies",
"GET /stealth/status", "POST /fingerprint/rotate",
"POST /find",
- "POST /solve-cloudflare",
+ "GET /solvers",
+ "POST /solve", "POST /solve/{name}",
}
for _, route := range shorthandRoutes {
mux.HandleFunc(route, s.proxyToFirst)
diff --git a/internal/strategy/simple/simple.go b/internal/strategy/simple/simple.go
index 415e1884..188577bc 100644
--- a/internal/strategy/simple/simple.go
+++ b/internal/strategy/simple/simple.go
@@ -62,7 +62,8 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
"GET /cookies", "POST /cookies",
"GET /stealth/status", "POST /fingerprint/rotate",
"POST /find",
- "POST /solve-cloudflare",
+ "GET /solvers",
+ "POST /solve", "POST /solve/{name}",
}
for _, route := range shorthandRoutes {
mux.HandleFunc(route, s.proxyToFirst)