Skip to content

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

refactor: delete the dead legacy solver registry and its duplicate Cloudflare solver, which nothing can reach yet every solver refactor still pays for (PIN-147)

Luigi Agosti2c1cdf6d8068
diff --git a/docs/architecture/autosolver.md b/docs/architecture/autosolver.md
index e1850315..10143a70 100644
--- a/docs/architecture/autosolver.md
+++ b/docs/architecture/autosolver.md
@@ -2,7 +2,7 @@
## Overview
-The AutoSolver system provides modular, semantic-first browser automation for PinchTab. It evolves the existing `internal/solver` framework (PR #395) into a general-purpose automation agent capable of handling CAPTCHAs, login flows, signup flows, multi-step navigation, and onboarding sequences.
+The AutoSolver system provides modular, semantic-first browser automation for PinchTab. It grew out of an earlier single-purpose challenge-solver framework into a general-purpose automation agent capable of handling CAPTCHAs, login flows, signup flows, multi-step navigation, and onboarding sequences.
### Design Principles
@@ -240,4 +240,4 @@ if result.Solved {
## Backward Compatibility
-The existing `internal/solver` package (PR #395) is still present for compatibility, but challenge APIs are now backed by `internal/autosolver`. The `CloudflareSolver` in `bridge/cloudflare.go` remains available, and a `LegacyAdapter` shim (`solvers/legacy.go`) can wrap legacy `solver.Solver` implementations into the new `autosolver.Solver` interface.
+`internal/autosolver` is the only solver framework. The predecessor package, its duplicate Cloudflare solver in `bridge/cloudflare.go` and the `LegacyAdapter` shim that was to bridge them are all deleted: nothing ever wired the adapter up, so the second registry had no readers while every solver-wide refactor still had to edit its copy of each solver.
diff --git a/internal/autosolver/challenge_detection_test.go b/internal/autosolver/challenge_detection_test.go
index 9cec8789..a6e7ade1 100644
--- a/internal/autosolver/challenge_detection_test.go
+++ b/internal/autosolver/challenge_detection_test.go
@@ -22,8 +22,8 @@ var cloudflareTriggerTitles = []string{
// block revived after the canonical call can set it by assignment instead, and
// that shape is invisible twice over: unreachable, so no behavioural test sees
// it, and colon-free, so a literal search does not either. Assignment is checked
-// only under the Intent-owning tree — internal/solver's Result has its own
-// ChallengeType field, and internal/bridge legitimately assigns THAT one.
+// only under the Intent-owning tree, so a same-named field on another package's
+// own result type cannot be mistaken for this one.
func assignsIntentChallengeType(path, src string) bool {
if !strings.Contains(path, "internal/autosolver/") {
return false
diff --git a/internal/autosolver/solvers/cloudflare.go b/internal/autosolver/solvers/cloudflare.go
index 3da5a853..265ad454 100644
--- a/internal/autosolver/solvers/cloudflare.go
+++ b/internal/autosolver/solvers/cloudflare.go
@@ -6,6 +6,7 @@ package solvers
import (
"context"
"fmt"
+ "math/rand"
"strings"
"time"
@@ -42,6 +43,17 @@ func (s *Cloudflare) Solve(ctx context.Context, page autosolver.Page, executor a
return result, fmt.Errorf("detect challenge type: %w", err)
}
+ // Re-detect once after a pause when the first read finds no type. Cloudflare
+ // writes cType into the document after the interstitial paints, so an early
+ // read sees nothing and a non-interactive challenge would be driven down the
+ // clicking path instead of simply being waited out.
+ if challengeType == "" {
+ time.Sleep(cfRedetectDelay)
+ if retried, retryErr := detectCFChallengeType(ctx, executor); retryErr == nil {
+ challengeType = retried
+ }
+ }
+
// Non-interactive challenges resolve automatically.
if challengeType == "non-interactive" {
return waitForCFResolve(ctx, page, result, 15*time.Second)
@@ -64,9 +76,11 @@ func (s *Cloudflare) Solve(ctx context.Context, page autosolver.Page, executor a
continue
}
- // Click the checkbox area (left portion of the widget).
- checkboxX := box.x + box.width*0.09
- checkboxY := box.y + box.height*0.40
+ // Click the checkbox area (left portion of the widget), jittered: an
+ // exact-centre click on every attempt is a fingerprint, and this solver
+ // exists to get past fingerprinting.
+ checkboxX := box.x + box.width*0.09 + cfClickJitter()
+ checkboxY := box.y + box.height*0.40 + cfClickJitter()
if err := executor.Click(ctx, checkboxX, checkboxY); err != nil {
return result, fmt.Errorf("click turnstile: %w", err)
@@ -89,6 +103,20 @@ type boundingBox struct {
x, y, width, height float64
}
+const (
+ // cfRedetectDelay is how long to wait before re-reading the challenge type.
+ cfRedetectDelay = 2 * time.Second
+ // cfClickJitterPx is the full width of the click-position jitter window.
+ cfClickJitterPx = 8
+)
+
+var cfRand = rand.New(rand.NewSource(time.Now().UnixNano())) // #nosec G404 -- input humanisation, not cryptography.
+
+// cfClickJitter returns a signed offset within half the jitter window either way.
+func cfClickJitter() float64 {
+ return (cfRand.Float64() - 0.5) * cfClickJitterPx
+}
+
func isCFChallenge(title string) bool {
return cfchallenge.IsChallengeTitle(title)
}
diff --git a/internal/autosolver/solvers/legacy.go b/internal/autosolver/solvers/legacy.go
deleted file mode 100644
index 94f47130..00000000
--- a/internal/autosolver/solvers/legacy.go
+++ /dev/null
@@ -1,56 +0,0 @@
-package solvers
-
-import (
- "context"
-
- "github.com/pinchtab/pinchtab/internal/autosolver"
- legacySolver "github.com/pinchtab/pinchtab/internal/solver"
-)
-
-// LegacyAdapter wraps an existing solver.Solver (PR #395 interface) to
-// work with the new autosolver.Solver interface. This allows the existing
-// CloudflareSolver in bridge/cloudflare.go to be used alongside new
-// autosolver implementations during the migration period.
-//
-// Because the legacy Solver interface requires a chromedp context directly
-// (via ctx), this adapter only works when the ActionExecutor is backed by
-// a chromedp context (i.e., the PinchtabExecutor from the adapters package).
-type LegacyAdapter struct {
- solver legacySolver.Solver
- priority int
-}
-
-// NewLegacyAdapter wraps a legacy solver.Solver.
-func NewLegacyAdapter(s legacySolver.Solver, priority int) *LegacyAdapter {
- return &LegacyAdapter{solver: s, priority: priority}
-}
-
-func (a *LegacyAdapter) Name() string { return a.solver.Name() }
-func (a *LegacyAdapter) Priority() int { return a.priority }
-
-// CanHandle delegates to the legacy solver's CanHandle.
-// Note: The legacy interface passes ctx directly (which must be a chromedp context).
-// This adapter uses the same ctx, which works when the Page is backed by chromedp.
-func (a *LegacyAdapter) CanHandle(ctx context.Context, _ autosolver.Page) (bool, error) {
- return a.solver.CanHandle(ctx)
-}
-
-// Solve delegates to the legacy solver's Solve method. Both paths report
-// a.Name() as the solver identity: legacyResult.Solver is json:"omitempty" and a
-// legacy solver may leave it unset, which reported an empty name on success.
-func (a *LegacyAdapter) Solve(ctx context.Context, page autosolver.Page, _ autosolver.ActionExecutor) (*autosolver.Result, error) {
- legacyResult, err := a.solver.Solve(ctx, legacySolver.Options{MaxAttempts: 3})
- if err != nil {
- return &autosolver.Result{
- SolverUsed: a.Name(),
- Error: err.Error(),
- }, err
- }
-
- return &autosolver.Result{
- Solved: legacyResult.Solved,
- SolverUsed: a.Name(),
- Attempts: legacyResult.Attempts,
- FinalTitle: legacyResult.Title,
- }, nil
-}
diff --git a/internal/autosolver/solvers/legacy_test.go b/internal/autosolver/solvers/legacy_test.go
deleted file mode 100644
index 7e61c612..00000000
--- a/internal/autosolver/solvers/legacy_test.go
+++ /dev/null
@@ -1,65 +0,0 @@
-package solvers
-
-import (
- "context"
- "errors"
- "testing"
-
- legacySolver "github.com/pinchtab/pinchtab/internal/solver"
-)
-
-// stubLegacySolver reports a Result whose Solver field is unset, which
-// json:"solver,omitempty" makes a legitimate shape for a legacy solver.
-type stubLegacySolver struct {
- name string
- result *legacySolver.Result
- solveErr error
-}
-
-func (s *stubLegacySolver) Name() string { return s.name }
-func (s *stubLegacySolver) CanHandle(context.Context) (bool, error) { return true, nil }
-func (s *stubLegacySolver) Solve(context.Context, legacySolver.Options) (*legacySolver.Result, error) {
- return s.result, s.solveErr
-}
-
-func TestLegacyAdapterReportsItsOwnNameOnBothPaths(t *testing.T) {
- tests := []struct {
- name string
- stub *stubLegacySolver
- wantErr bool
- }{
- {
- name: "success with an unset Solver field",
- stub: &stubLegacySolver{name: "legacy-cf", result: &legacySolver.Result{Solved: true, Title: "done"}},
- },
- {
- name: "success with a Solver field the legacy solver did fill in",
- stub: &stubLegacySolver{name: "legacy-cf", result: &legacySolver.Result{Solved: true, Solver: "legacy-cf"}},
- },
- {
- name: "failure",
- stub: &stubLegacySolver{name: "legacy-cf", solveErr: errors.New("boom")},
- wantErr: true,
- },
- }
-
- for _, tc := range tests {
- t.Run(tc.name, func(t *testing.T) {
- adapter := NewLegacyAdapter(tc.stub, 5)
- result, err := adapter.Solve(context.Background(), nil, nil)
- if tc.wantErr != (err != nil) {
- t.Fatalf("Solve() error = %v, wantErr %v", err, tc.wantErr)
- }
- if result == nil {
- t.Fatal("Solve returned no Result to check")
- }
- // The oracle is a literal, not adapter.Name(): production reads that same
- // accessor for this field, so comparing against it pins only WHERE the
- // value comes from. A Name() returning "" satisfied the accessor form on
- // all three cases while every legacy result reported an empty identity.
- if result.SolverUsed != "legacy-cf" {
- t.Errorf("Result.SolverUsed = %q, want %q — the adapter must report its own identity on every path", result.SolverUsed, "legacy-cf")
- }
- })
- }
-}
diff --git a/internal/bridge/cloudflare.go b/internal/bridge/cloudflare.go
deleted file mode 100644
index 54a7c57b..00000000
--- a/internal/bridge/cloudflare.go
+++ /dev/null
@@ -1,243 +0,0 @@
-package bridge
-
-import (
- "context"
- "fmt"
- "strings"
- "time"
-
- "github.com/chromedp/chromedp"
- "github.com/pinchtab/pinchtab/internal/cfchallenge"
- "github.com/pinchtab/pinchtab/internal/solver"
-)
-
-// cloudflareSolverName is this package's owner of the legacy registry identity:
-// the registration key, Name() and Result.Solver all read it. autosolver's
-// solvers.Cloudflare answers to the same spelling in the other registry, and that
-// equality is deliberately uncoupled — two registries with two Solver interfaces
-// means renaming one must not rename the other.
-const cloudflareSolverName = "cloudflare"
-
-func init() {
- solver.MustRegister(cloudflareSolverName, &CloudflareSolver{})
-}
-
-// 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 cloudflareSolverName }
-
-// 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
-}
-
-// 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 := &solver.Result{Solver: s.Name()}
-
- 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
- }
-
- // 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)
- }
-
- 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
-}
-
-type cfBoundingBox struct {
- X float64
- Y float64
- Width float64
- Height float64
-}
-
-func isCFChallenge(title string) bool {
- return cfchallenge.IsChallengeTitle(title)
-}
-
-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 cfchallenge.CTypeTokens {
- if strings.Contains(content, fmt.Sprintf("cType: '%s'", ct)) {
- return ct
- }
- }
-
- var hasEmbedded bool
- if err := chromedp.Run(ctx, chromedp.Evaluate(
- cfchallenge.EmbeddedTurnstileScriptJS,
- &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(cfchallenge.TurnstileBoxJS, &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, cfchallenge.SpinnerText) {
- return
- }
- }
- }
-}
-
-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()
-
- 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/bridge/cloudflare_test.go b/internal/bridge/cloudflare_test.go
deleted file mode 100644
index 4959f90c..00000000
--- a/internal/bridge/cloudflare_test.go
+++ /dev/null
@@ -1,33 +0,0 @@
-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/solver/solver.go b/internal/solver/solver.go
deleted file mode 100644
index 5a9a2892..00000000
--- a/internal/solver/solver.go
+++ /dev/null
@@ -1,133 +0,0 @@
-// 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"`
-}
-
-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)
- }
-
- 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)
- }
-
- 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
deleted file mode 100644
index bcc437a6..00000000
--- a/internal/solver/solver_test.go
+++ /dev/null
@@ -1,184 +0,0 @@
-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")
-
- if err := Register("test-get", &fakeSolver{name: "test-get"}); err != nil {
- t.Fatalf("Register failed: %v", err)
- }
-
- 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")
-
- if err := Register("test-names-a", &fakeSolver{name: "a"}); err != nil {
- t.Fatalf("Register failed: %v", err)
- }
- if err := Register("test-names-b", &fakeSolver{name: "b"}); err != nil {
- t.Fatalf("Register failed: %v", err)
- }
-
- 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}
- if err := Register("test-solve", &fakeSolver{
- name: "test-solve",
- canHandle: true,
- result: expected,
- }); err != nil {
- t.Fatalf("Register failed: %v", err)
- }
-
- 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")
-
- if err := Register("test-auto-no", &fakeSolver{
- name: "test-auto-no",
- canHandle: false,
- }); err != nil {
- t.Fatalf("Register failed: %v", err)
- }
- if err := Register("test-auto-yes", &fakeSolver{
- name: "test-auto-yes",
- canHandle: true,
- result: &Result{Solver: "test-auto-yes", Solved: true},
- }); err != nil {
- t.Fatalf("Register failed: %v", err)
- }
-
- 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")
-
- if err := Register("test-noop", &fakeSolver{
- name: "test-noop",
- canHandle: false,
- }); err != nil {
- t.Fatalf("Register failed: %v", err)
- }
-
- 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)
-}