Skip to content

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

feat: add Cloudflare Turnstile solver endpoint

Ariaaba89a2b67c5
diff --git a/internal/bridge/cloudflare.go b/internal/bridge/cloudflare.go
new file mode 100644
index 00000000..4fc6b4a7
--- /dev/null
+++ b/internal/bridge/cloudflare.go
@@ -0,0 +1,250 @@
+package bridge
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/chromedp/chromedp"
+)
+
+// 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"`
+}
+
+type cfBoundingBox struct {
+ X float64
+ Y float64
+ Width float64
+ Height float64
+}
+
+// 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) {
+ if maxAttempts <= 0 {
+ maxAttempts = 3
+ }
+
+ result := &CloudflareResult{}
+
+ var title string
+ if err := chromedp.Run(ctx, chromedp.Title(&title)); err != nil {
+ return result, fmt.Errorf("get title: %w", err)
+ }
+ result.Title = title
+
+ if !isCFChallenge(title) {
+ result.Solved = true
+ return result, nil
+ }
+
+ challengeType := detectCFType(ctx)
+ result.ChallengeType = challengeType
+
+ if challengeType == "" {
+ time.Sleep(2 * time.Second)
+ challengeType = detectCFType(ctx)
+ result.ChallengeType = challengeType
+ }
+
+ if challengeType == "non-interactive" {
+ return waitForCFResolve(ctx, result, 15*time.Second)
+ }
+
+ for attempt := 0; attempt < maxAttempts; attempt++ {
+ result.Attempts = attempt + 1
+
+ waitForCFSpinner(ctx, 10*time.Second)
+
+ box, err := findTurnstileBox(ctx)
+ if err != nil {
+ if err := chromedp.Run(ctx, chromedp.Title(&title)); err == nil && !isCFChallenge(title) {
+ result.Solved = true
+ result.Title = title
+ return result, nil
+ }
+ time.Sleep(1 * time.Second)
+ continue
+ }
+
+ clickX := box.X + float64(26+humanRand.Intn(3))
+ clickY := box.Y + float64(25+humanRand.Intn(3))
+
+ if err := Click(ctx, clickX, clickY); err != nil {
+ return result, fmt.Errorf("click turnstile: %w", err)
+ }
+
+ resolved := pollCFResolution(ctx, 15*time.Second)
+ if resolved {
+ if err := chromedp.Run(ctx, chromedp.Title(&title)); err == nil {
+ result.Title = title
+ }
+ result.Solved = true
+ return result, nil
+ }
+ }
+
+ if err := chromedp.Run(ctx, chromedp.Title(&title)); err == nil {
+ result.Title = title
+ result.Solved = !isCFChallenge(title)
+ }
+
+ return result, nil
+}
+
+func isCFChallenge(title string) bool {
+ lower := strings.ToLower(title)
+ return strings.Contains(lower, "just a moment") ||
+ strings.Contains(lower, "attention required") ||
+ strings.Contains(lower, "checking your browser")
+}
+
+func detectCFType(ctx context.Context) string {
+ var content string
+ if err := chromedp.Run(ctx, chromedp.Evaluate(`document.documentElement.outerHTML`, &content)); err != nil {
+ return ""
+ }
+
+ for _, ct := range []string{"non-interactive", "managed", "interactive"} {
+ if strings.Contains(content, fmt.Sprintf("cType: '%s'", ct)) {
+ return ct
+ }
+ }
+
+ var hasEmbedded bool
+ if err := chromedp.Run(ctx, chromedp.Evaluate(
+ `!!document.querySelector('script[src*="challenges.cloudflare.com/turnstile/v"]')`,
+ &hasEmbedded,
+ )); err == nil && hasEmbedded {
+ return "embedded"
+ }
+
+ return ""
+}
+
+func findTurnstileBox(ctx context.Context) (*cfBoundingBox, error) {
+ var rawBox map[string]float64
+ err := chromedp.Run(ctx, chromedp.Evaluate(`
+ (() => {
+ const patterns = [
+ 'iframe[src*="challenges.cloudflare.com/cdn-cgi/challenge-platform"]',
+ 'iframe[src*="challenges.cloudflare.com"]',
+ ];
+ for (const sel of patterns) {
+ const iframe = document.querySelector(sel);
+ if (iframe) {
+ const r = iframe.getBoundingClientRect();
+ if (r.width > 0 && r.height > 0) {
+ return {x: r.x, y: r.y, width: r.width, height: r.height};
+ }
+ }
+ }
+ const containers = [
+ '#cf_turnstile div', '#cf-turnstile div', '.turnstile>div>div',
+ '.main-content p+div>div>div',
+ ];
+ for (const sel of containers) {
+ const el = document.querySelector(sel);
+ if (el) {
+ const r = el.getBoundingClientRect();
+ if (r.width > 0 && r.height > 0) {
+ return {x: r.x, y: r.y, width: r.width, height: r.height};
+ }
+ }
+ }
+ return null;
+ })()
+ `, &rawBox))
+ if err != nil {
+ return nil, fmt.Errorf("evaluate turnstile box: %w", err)
+ }
+ if rawBox == nil {
+ return nil, fmt.Errorf("turnstile element not found")
+ }
+
+ return &cfBoundingBox{
+ X: rawBox["x"],
+ Y: rawBox["y"],
+ Width: rawBox["width"],
+ Height: rawBox["height"],
+ }, nil
+}
+
+func waitForCFSpinner(ctx context.Context, timeout time.Duration) {
+ deadline := time.After(timeout)
+ ticker := time.NewTicker(500 * time.Millisecond)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-deadline:
+ return
+ case <-ticker.C:
+ var text string
+ if err := chromedp.Run(ctx, chromedp.Evaluate(`document.body.innerText`, &text)); err != nil {
+ continue
+ }
+ if !strings.Contains(text, "Verifying you are human") {
+ return
+ }
+ }
+ }
+}
+
+func waitForCFResolve(ctx context.Context, result *CloudflareResult, timeout time.Duration) (*CloudflareResult, error) {
+ deadline := time.After(timeout)
+ ticker := time.NewTicker(1 * time.Second)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return result, ctx.Err()
+ case <-deadline:
+ return result, nil
+ case <-ticker.C:
+ var title string
+ if err := chromedp.Run(ctx, chromedp.Title(&title)); err != nil {
+ continue
+ }
+ if !isCFChallenge(title) {
+ result.Solved = true
+ result.Title = title
+ return result, nil
+ }
+ }
+ }
+}
+
+func pollCFResolution(ctx context.Context, timeout time.Duration) bool {
+ deadline := time.After(timeout)
+ ticker := time.NewTicker(500 * time.Millisecond)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return false
+ case <-deadline:
+ return false
+ case <-ticker.C:
+ var title string
+ if err := chromedp.Run(ctx, chromedp.Title(&title)); err != nil {
+ continue
+ }
+ if !isCFChallenge(title) {
+ time.Sleep(1 * time.Second)
+ return true
+ }
+ }
+ }
+}
diff --git a/internal/handlers/cloudflare.go b/internal/handlers/cloudflare.go
new file mode 100644
index 00000000..870dd2eb
--- /dev/null
+++ b/internal/handlers/cloudflare.go
@@ -0,0 +1,126 @@
+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 0da45cf0..ef60ce6a 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -137,6 +137,8 @@ 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("POST /fingerprint/rotate", h.HandleFingerprintRotate)
mux.HandleFunc("GET /stealth/status", h.HandleStealthStatus)
mux.HandleFunc("GET /tabs/{id}/download", h.HandleTabDownload)
diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.go
index a9495676..637e9b3b 100644
--- a/internal/orchestrator/handlers.go
+++ b/internal/orchestrator/handlers.go
@@ -78,6 +78,7 @@ 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",
} {
mux.HandleFunc(route, o.proxyTabRequest)
}
diff --git a/internal/strategy/autorestart/autorestart.go b/internal/strategy/autorestart/autorestart.go
index 219ad092..8c8734e7 100644
--- a/internal/strategy/autorestart/autorestart.go
+++ b/internal/strategy/autorestart/autorestart.go
@@ -188,6 +188,7 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
"GET /cookies", "POST /cookies",
"GET /stealth/status", "POST /fingerprint/rotate",
"POST /find",
+ "POST /solve-cloudflare",
}
for _, route := range shorthandRoutes {
mux.HandleFunc(route, s.proxyToManaged)
diff --git a/internal/strategy/explicit/explicit.go b/internal/strategy/explicit/explicit.go
index 8eb893fb..f825498a 100644
--- a/internal/strategy/explicit/explicit.go
+++ b/internal/strategy/explicit/explicit.go
@@ -51,6 +51,7 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
"GET /cookies", "POST /cookies",
"GET /stealth/status", "POST /fingerprint/rotate",
"POST /find",
+ "POST /solve-cloudflare",
}
for _, route := range shorthandRoutes {
mux.HandleFunc(route, s.proxyToFirst)
diff --git a/internal/strategy/noinstance/noinstance.go b/internal/strategy/noinstance/noinstance.go
index dfc2303a..2c9096a3 100644
--- a/internal/strategy/noinstance/noinstance.go
+++ b/internal/strategy/noinstance/noinstance.go
@@ -47,6 +47,7 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
"GET /cookies", "POST /cookies",
"GET /stealth/status", "POST /fingerprint/rotate",
"POST /find",
+ "POST /solve-cloudflare",
}
for _, route := range shorthandRoutes {
mux.HandleFunc(route, s.proxyToFirst)
diff --git a/internal/strategy/simple/simple.go b/internal/strategy/simple/simple.go
index afc06fab..415e1884 100644
--- a/internal/strategy/simple/simple.go
+++ b/internal/strategy/simple/simple.go
@@ -62,6 +62,7 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
"GET /cookies", "POST /cookies",
"GET /stealth/status", "POST /fingerprint/rotate",
"POST /find",
+ "POST /solve-cloudflare",
}
for _, route := range shorthandRoutes {
mux.HandleFunc(route, s.proxyToFirst)