High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactor(autosolver): fold the shared external solver skeleton into one base
Luigi Agosti23a58a3594f6
diff --git a/internal/autosolver/external/capsolver.go b/internal/autosolver/external/capsolver.goindex c67b48e7..755af796 100644--- a/internal/autosolver/external/capsolver.go+++ b/internal/autosolver/external/capsolver.go@@ -1,12 +1,8 @@-// Package external provides skeleton implementations for third-party-// CAPTCHA solving services (Capsolver, 2Captcha). These are designed-// as pluggable solvers enabled via configuration.package externalimport ("context""fmt"- "strings""github.com/pinchtab/pinchtab/internal/autosolver")@@ -20,7 +16,7 @@ type CapsolverConfig struct {// Capsolver implements autosolver.Solver using the Capsolver API.// It supports reCAPTCHA v2/v3, hCaptcha, and Cloudflare Turnstile.type Capsolver struct {- config CapsolverConfig+ externalSolver}// NewCapsolver creates a Capsolver solver with the given configuration.@@ -28,37 +24,13 @@ func NewCapsolver(cfg CapsolverConfig) *Capsolver {if cfg.BaseURL == "" {cfg.BaseURL = "https://api.capsolver.com"}- return &Capsolver{config: cfg}-}--func (c *Capsolver) Name() string { return autosolver.CapsolverSolverName }-func (c *Capsolver) Priority() int { return 200 }--// CanHandle checks if the page contains a supported CAPTCHA type.-func (c *Capsolver) CanHandle(ctx context.Context, page autosolver.Page) (bool, error) {- if c.config.APIKey == "" {- return false, nil- }-- html, err := page.HTML()- if err != nil {- return false, nil- }-- lower := strings.ToLower(html)- captchaPatterns := []string{- "recaptcha",- "hcaptcha",- "challenges.cloudflare.com/turnstile",- "g-recaptcha",- "h-captcha",- }- for _, p := range captchaPatterns {- if strings.Contains(lower, p) {- return true, nil- }- }- return false, nil+ return &Capsolver{externalSolver{+ name: autosolver.CapsolverSolverName,+ label: "capsolver",+ apiKey: cfg.APIKey,+ baseURL: cfg.BaseURL,+ priority: 200,+ }}}// Solve submits the CAPTCHA to the Capsolver API and injects the result.@@ -67,31 +39,11 @@ func (c *Capsolver) CanHandle(ctx context.Context, page autosolver.Page) (bool,// (create task → poll result → inject token) must be filled in// with the Capsolver API v1 protocol.func (c *Capsolver) Solve(ctx context.Context, page autosolver.Page, executor autosolver.ActionExecutor) (*autosolver.Result, error) {- result := &autosolver.Result{SolverUsed: c.Name()}-- if c.config.APIKey == "" {- result.Error = "capsolver API key not configured"- return result, fmt.Errorf("capsolver API key not configured")- }-- html, err := page.HTML()+ sitekey, result, err := c.prepare(page)if err != nil {- result.Error = fmt.Sprintf("get HTML: %v", err)return result, err}- captchaType := detectCaptchaType(html)- if captchaType == "" {- result.Error = "no supported CAPTCHA detected"- return result, fmt.Errorf("no supported CAPTCHA detected on page")- }-- sitekey := extractSitekey(html, captchaType)- if sitekey == "" {- result.Error = "sitekey not found"- return result, fmt.Errorf("could not extract sitekey from page")- }-// TODO: Implement HTTP client for Capsolver API v1.// POST /createTask with task type + sitekey + page URL._ = sitekey@@ -100,49 +52,3 @@ func (c *Capsolver) Solve(ctx context.Context, page autosolver.Page, executor auresult.Error = "capsolver API client not yet implemented"return result, fmt.Errorf("capsolver: API client not yet implemented — skeleton only")}--func detectCaptchaType(html string) string {- lower := strings.ToLower(html)- switch {- case strings.Contains(lower, "g-recaptcha") || strings.Contains(lower, "recaptcha"):- return "recaptcha"- case strings.Contains(lower, "h-captcha") || strings.Contains(lower, "hcaptcha"):- return "hcaptcha"- case strings.Contains(lower, "challenges.cloudflare.com/turnstile"):- return "turnstile"- default:- return ""- }-}--func extractSitekey(html, captchaType string) string {- var attrNames []string- switch captchaType {- case "recaptcha":- attrNames = []string{"data-sitekey"}- case "hcaptcha":- attrNames = []string{"data-sitekey"}- case "turnstile":- attrNames = []string{"data-sitekey"}- default:- return ""- }-- for _, attr := range attrNames {- idx := strings.Index(html, attr+`="`)- if idx == -1 {- idx = strings.Index(html, attr+`='`)- }- if idx == -1 {- continue- }- start := idx + len(attr) + 2- quote := html[start-1]- end := strings.IndexByte(html[start:], quote)- if end == -1 {- continue- }- return html[start : start+end]- }- return ""-}diff --git a/internal/autosolver/external/external.go b/internal/autosolver/external/external.gonew file mode 100644index 00000000..c334f928--- /dev/null+++ b/internal/autosolver/external/external.go@@ -0,0 +1,127 @@+// Package external provides skeleton implementations for third-party+// CAPTCHA solving services (Capsolver, 2Captcha). These are designed+// as pluggable solvers enabled via configuration.+package external++import (+ "context"+ "fmt"+ "strings"++ "github.com/pinchtab/pinchtab/internal/autosolver"+)++// externalSolver is everything the third-party providers share: the same key+// check, page read, CAPTCHA detection and sitekey extraction. Only identity and+// the API call differ, and the API call deliberately stays a per-provider+// method — the two wire protocols must not be merged when they are implemented.+type externalSolver struct {+ name string+ // label is the spelling used in operator-facing errors. 2Captcha registers+ // as "twocaptcha" but has always reported itself as "2captcha", so this is+ // not derivable from name.+ label string+ apiKey string+ baseURL string+ priority int+}++func (s externalSolver) Name() string { return s.name }+func (s externalSolver) Priority() int { return s.priority }++var captchaPatterns = []string{+ "recaptcha",+ "hcaptcha",+ "challenges.cloudflare.com/turnstile",+ "g-recaptcha",+ "h-captcha",+}++// CanHandle checks if the page contains a supported CAPTCHA type.+func (s externalSolver) CanHandle(ctx context.Context, page autosolver.Page) (bool, error) {+ if s.apiKey == "" {+ return false, nil+ }++ html, err := page.HTML()+ if err != nil {+ return false, nil+ }++ lower := strings.ToLower(html)+ for _, p := range captchaPatterns {+ if strings.Contains(lower, p) {+ return true, nil+ }+ }+ return false, nil+}++// prepare runs everything both providers do before their API call and returns+// the sitekey to submit, or the Result and error to hand straight back. The+// key check comes first so a solver with no key never touches the page.+func (s externalSolver) prepare(page autosolver.Page) (string, *autosolver.Result, error) {+ result := &autosolver.Result{SolverUsed: s.name}++ if s.apiKey == "" {+ result.Error = s.label + " API key not configured"+ return "", result, fmt.Errorf("%s API key not configured", s.label)+ }++ html, err := page.HTML()+ if err != nil {+ result.Error = fmt.Sprintf("get HTML: %v", err)+ return "", result, err+ }++ if detectCaptchaType(html) == "" {+ result.Error = "no supported CAPTCHA detected"+ return "", result, fmt.Errorf("no supported CAPTCHA detected on page")+ }++ sitekey := extractSitekey(html)+ if sitekey == "" {+ result.Error = "sitekey not found"+ return "", result, fmt.Errorf("could not extract sitekey from page")+ }++ return sitekey, result, nil+}++func detectCaptchaType(html string) string {+ lower := strings.ToLower(html)+ switch {+ case strings.Contains(lower, "g-recaptcha") || strings.Contains(lower, "recaptcha"):+ return "recaptcha"+ case strings.Contains(lower, "h-captcha") || strings.Contains(lower, "hcaptcha"):+ return "hcaptcha"+ case strings.Contains(lower, "challenges.cloudflare.com/turnstile"):+ return "turnstile"+ default:+ return ""+ }+}++// extractSitekey reads the sitekey attribute out of the page HTML. It used to+// switch on the detected CAPTCHA type, but all three arms named the same+// attribute, so the type only separated known from unknown — a question+// prepare has already answered before it calls this.+func extractSitekey(html string) string {+ const attr = "data-sitekey"++ idx := strings.Index(html, attr+`="`)+ if idx == -1 {+ idx = strings.Index(html, attr+`='`)+ }+ if idx == -1 {+ return ""+ }++ start := idx + len(attr) + 2+ quote := html[start-1]+ end := strings.IndexByte(html[start:], quote)+ if end == -1 {+ return ""+ }+ return html[start : start+end]+}diff --git a/internal/autosolver/external/external_test.go b/internal/autosolver/external/external_test.goindex bb956bf9..23062d49 100644--- a/internal/autosolver/external/external_test.go+++ b/internal/autosolver/external/external_test.go@@ -2,7 +2,9 @@ package externalimport ("context"+ "errors""testing"+ "time""github.com/pinchtab/pinchtab/internal/autosolver")@@ -31,3 +33,145 @@ func TestSolverUsedMatchesTheRegisteredName(t *testing.T) {})}}++// stubPage is the smallest Page the external solvers touch: they read HTML and+// URL and nothing else.+type stubPage struct {+ html string+ htmlErr error+}++func (p stubPage) URL() string { return "https://example.test/challenge" }+func (p stubPage) Title() string { return "" }+func (p stubPage) HTML() (string, error) {+ return p.html, p.htmlErr+}+func (p stubPage) HTMLWithin(time.Duration) (string, error) { return p.HTML() }+func (p stubPage) Screenshot() ([]byte, error) { return nil, nil }++const recaptchaHTML = `<div class="g-recaptcha" data-sitekey="6LtestKEY"></div>`++// Every branch of Solve is pinned by exact string, because folding the shared+// prologue into a base moved these messages across a file boundary and the+// providers spell their own label differently from their registered name.+func TestSolveMessagesAreUnchangedOnEveryPath(t *testing.T) {+ for _, provider := range []struct {+ label string+ build func(key string) autosolver.Solver+ wantPri int+ }{+ {"capsolver", func(key string) autosolver.Solver { return NewCapsolver(CapsolverConfig{APIKey: key}) }, 200},+ {"2captcha", func(key string) autosolver.Solver { return NewTwoCaptcha(TwoCaptchaConfig{APIKey: key}) }, 210},+ } {+ t.Run(provider.label, func(t *testing.T) {+ keyed := provider.build("key")++ for _, tc := range []struct {+ name string+ solver autosolver.Solver+ page autosolver.Page+ wantResult string+ wantErr string+ }{+ {+ name: "no api key",+ solver: provider.build(""),+ page: stubPage{html: recaptchaHTML},+ wantResult: provider.label + " API key not configured",+ wantErr: provider.label + " API key not configured",+ },+ {+ name: "page read fails",+ solver: keyed,+ page: stubPage{htmlErr: errors.New("boom")},+ wantResult: "get HTML: boom",+ wantErr: "boom",+ },+ {+ name: "no captcha on page",+ solver: keyed,+ page: stubPage{html: "<html><body>nothing here</body></html>"},+ wantResult: "no supported CAPTCHA detected",+ wantErr: "no supported CAPTCHA detected on page",+ },+ {+ name: "captcha without a sitekey",+ solver: keyed,+ page: stubPage{html: `<div class="g-recaptcha"></div>`},+ wantResult: "sitekey not found",+ wantErr: "could not extract sitekey from page",+ },+ {+ name: "reaches the unimplemented api call",+ solver: keyed,+ page: stubPage{html: recaptchaHTML},+ wantResult: provider.label + " API client not yet implemented",+ wantErr: provider.label + ": API client not yet implemented — skeleton only",+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ result, err := tc.solver.Solve(context.Background(), tc.page, nil)+ if err == nil {+ t.Fatal("Solve reported success; every path here is an error path")+ }+ if err.Error() != tc.wantErr {+ t.Errorf("error = %q, want %q", err, tc.wantErr)+ }+ if result == nil {+ t.Fatal("Solve returned no Result")+ }+ if result.Error != tc.wantResult {+ t.Errorf("Result.Error = %q, want %q", result.Error, tc.wantResult)+ }+ if result.SolverUsed != tc.solver.Name() {+ t.Errorf("Result.SolverUsed = %q, want %q", result.SolverUsed, tc.solver.Name())+ }+ })+ }++ if got := keyed.Priority(); got != provider.wantPri {+ t.Errorf("Priority() = %d, want %d; the external stubs must keep sorting behind the real solvers", got, provider.wantPri)+ }+ })+ }+}++func TestCanHandleIsSharedAndKeyGated(t *testing.T) {+ for _, tc := range []struct {+ name string+ solver autosolver.Solver+ page autosolver.Page+ want bool+ }{+ {"no key never handles", NewCapsolver(CapsolverConfig{}), stubPage{html: recaptchaHTML}, false},+ {"keyed handles a captcha page", NewCapsolver(CapsolverConfig{APIKey: "k"}), stubPage{html: recaptchaHTML}, true},+ {"keyed declines a plain page", NewCapsolver(CapsolverConfig{APIKey: "k"}), stubPage{html: "<p>hi</p>"}, false},+ {"page read failure declines", NewCapsolver(CapsolverConfig{APIKey: "k"}), stubPage{htmlErr: errors.New("boom")}, false},+ {"twocaptcha agrees with capsolver", NewTwoCaptcha(TwoCaptchaConfig{APIKey: "k"}), stubPage{html: recaptchaHTML}, true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ got, err := tc.solver.CanHandle(context.Background(), tc.page)+ if err != nil {+ t.Fatalf("CanHandle() error = %v", err)+ }+ if got != tc.want {+ t.Errorf("CanHandle() = %v, want %v", got, tc.want)+ }+ })+ }+}++func TestExtractSitekeyReadsBothQuoteStyles(t *testing.T) {+ for _, tc := range []struct{ name, html, want string }{+ {"double quotes", `<div data-sitekey="abc"></div>`, "abc"},+ {"single quotes", `<div data-sitekey='abc'></div>`, "abc"},+ {"absent", `<div class="g-recaptcha"></div>`, ""},+ {"unterminated", `<div data-sitekey="abc`, ""},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got := extractSitekey(tc.html); got != tc.want {+ t.Errorf("extractSitekey(%q) = %q, want %q", tc.html, got, tc.want)+ }+ })+ }+}diff --git a/internal/autosolver/external/twocaptcha.go b/internal/autosolver/external/twocaptcha.goindex 71f53969..155cda95 100644--- a/internal/autosolver/external/twocaptcha.go+++ b/internal/autosolver/external/twocaptcha.go@@ -3,7 +3,6 @@ package externalimport ("context""fmt"- "strings""github.com/pinchtab/pinchtab/internal/autosolver")@@ -17,7 +16,7 @@ type TwoCaptchaConfig struct {// TwoCaptcha implements autosolver.Solver using the 2Captcha API.// It supports reCAPTCHA v2/v3, hCaptcha, and Cloudflare Turnstile.type TwoCaptcha struct {- config TwoCaptchaConfig+ externalSolver}// NewTwoCaptcha creates a 2Captcha solver with the given configuration.@@ -25,37 +24,13 @@ func NewTwoCaptcha(cfg TwoCaptchaConfig) *TwoCaptcha {if cfg.BaseURL == "" {cfg.BaseURL = "https://2captcha.com"}- return &TwoCaptcha{config: cfg}-}--func (t *TwoCaptcha) Name() string { return autosolver.TwoCaptchaSolverName }-func (t *TwoCaptcha) Priority() int { return 210 }--// CanHandle checks if the page contains a supported CAPTCHA type.-func (t *TwoCaptcha) CanHandle(ctx context.Context, page autosolver.Page) (bool, error) {- if t.config.APIKey == "" {- return false, nil- }-- html, err := page.HTML()- if err != nil {- return false, nil- }-- lower := strings.ToLower(html)- captchaPatterns := []string{- "recaptcha",- "hcaptcha",- "challenges.cloudflare.com/turnstile",- "g-recaptcha",- "h-captcha",- }- for _, p := range captchaPatterns {- if strings.Contains(lower, p) {- return true, nil- }- }- return false, nil+ return &TwoCaptcha{externalSolver{+ name: autosolver.TwoCaptchaSolverName,+ label: "2captcha",+ apiKey: cfg.APIKey,+ baseURL: cfg.BaseURL,+ priority: 210,+ }}}// Solve submits the CAPTCHA to the 2Captcha API and injects the result.@@ -63,31 +38,11 @@ func (t *TwoCaptcha) CanHandle(ctx context.Context, page autosolver.Page) (bool,// This is a skeleton implementation. The actual HTTP client logic// (submit → poll → inject) must be filled in with the 2Captcha API protocol.func (t *TwoCaptcha) Solve(ctx context.Context, page autosolver.Page, executor autosolver.ActionExecutor) (*autosolver.Result, error) {- result := &autosolver.Result{SolverUsed: t.Name()}-- if t.config.APIKey == "" {- result.Error = "2captcha API key not configured"- return result, fmt.Errorf("2captcha API key not configured")- }-- html, err := page.HTML()+ sitekey, result, err := t.prepare(page)if err != nil {- result.Error = fmt.Sprintf("get HTML: %v", err)return result, err}- captchaType := detectCaptchaType(html)- if captchaType == "" {- result.Error = "no supported CAPTCHA detected"- return result, fmt.Errorf("no supported CAPTCHA detected on page")- }-- sitekey := extractSitekey(html, captchaType)- if sitekey == "" {- result.Error = "sitekey not found"- return result, fmt.Errorf("could not extract sitekey from page")- }-// TODO: Implement HTTP client for 2Captcha API.// POST in.php with method + sitekey + pageurl → get task ID// GET res.php with id → poll until ready → inject token