captcha

package
v1.5.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 31, 2026 License: MIT Imports: 17 Imported by: 0

README

Captcha Plugin for Nimbus (CapSolver Alternative)

The Nimbus Captcha Plugin (plugins/captcha) is an enterprise-grade captcha plugin for the Nimbus Go framework. Powered by the Nimbus Cloud Paid Plan, it delivers high-speed AI captcha solving and server-side request verification.


Features

  • CapSolver Alternative (Automated Solving): Solve Cloudflare Turnstile, Google reCAPTCHA (v2/v3/Enterprise), hCaptcha, GeeTest, AWS WAF, and Image OCR via the Nimbus Cloud API.
  • Bot Defense Middleware: Expressive captcha.Protect() middleware for protecting HTTP routes and form submissions.
  • Server Verification: Server-side verification for Turnstile, reCAPTCHA, and hCaptcha tokens.
  • Mock Mode: Built-in mock solver and verifier for local development and unit testing without network calls or cloud costs.
  • Container Integration: Standard Nimbus IoC bindings and facade pattern (captcha.Solve, captcha.Verify).

Installation

go get github.com/CodeSyncr/nimbus/plugins/captcha

Register the plugin in your bin/server.go:

package main

import (
    "github.com/CodeSyncr/nimbus"
    "github.com/CodeSyncr/nimbus/plugins/captcha"
)

func main() {
    app := nimbus.New()

    // Register Captcha plugin
    app.Use(captcha.New())

    app.Run()
}

Environment Configuration (.env)

# Nimbus Cloud API Credentials (Paid Plan)
NIMBUS_CLOUD_API_KEY=nc_live_your_api_key_here

# Local Development / Testing (Auto-approves without cloud API calls)
NIMBUS_CAPTCHA_MOCK=true

# Provider Verification Secret Keys (for server-side token validation)
TURNSTILE_SECRET_KEY=0x4AAAAAA...
RECAPTCHA_SECRET_KEY=6LeIx...
HCAPTCHA_SECRET_KEY=0x000000...

Usage Examples

1. Automated Captcha Solving (Scrapers / Automation)
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/CodeSyncr/nimbus/plugins/captcha"
)

func solveTurnstile() {
    ctx := context.Background()

    // Solve Turnstile Challenge
    solution, err := captcha.Solve(ctx, captcha.TaskPayload{
        Type:       captcha.TaskTypeTurnstileProxyless,
        WebsiteURL: "https://example.com/login",
        WebsiteKey: "0x4AAAAAAAJn_...",
    })
    if err != nil {
        log.Fatalf("Solving failed: %v", err)
    }

    fmt.Printf("Solved Token: %s (Time: %s)\n", solution.Token, solution.SolveTime)
}
2. Protecting Routes with Middleware

Protect forms and login routes against automated bots:

package routes

import (
    "github.com/CodeSyncr/nimbus/router"
    "github.com/CodeSyncr/nimbus/plugins/captcha"
)

func Register(r *router.Router) {
    // Protect /register POST route using default Turnstile token check
    r.Post("/register", captcha.Protect(), RegisterController)

    // Protect with specific options
    r.Post("/login", captcha.ProtectWithOptions(captcha.MiddlewareOptions{
        Provider:       "recaptcha",
        TokenFormField: "g-recaptcha-response",
    }), LoginController)
}
3. Server-Side Token Verification

Manual token verification in custom HTTP handlers:

func VerifySubmission(c *nhttp.Context) error {
    token := c.FormValue("cf-turnstile-response")

    result, err := captcha.Verify(c.Request().Context(), "turnstile", token, c.IP())
    if err != nil || !result.Success {
        return c.JSON(400, map[string]string{"error": "Invalid captcha token"})
    }

    return c.JSON(200, map[string]string{"status": "verified"})
}
4. Image OCR (Base64)
solution, err := captcha.Solve(ctx, captcha.TaskPayload{
    Type: captcha.TaskTypeImageToText,
    Body: "base64_encoded_image_string...",
})
fmt.Println("OCR Result:", solution.Text)

Running Plugin Tests

cd plugins/captcha
go test -v ./...

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrMockSolveFailed is returned when mock solver fails intentionally in tests.
	ErrMockSolveFailed = errors.New("captcha: mock solve failed")
	// ErrPluginNotRegistered is returned when captcha facade is called before plugin registration.
	ErrPluginNotRegistered = errors.New("captcha: plugin not registered. Call app.Use(captcha.New())")
)

Functions

func Bindings

func Bindings(c *container.Container, m *Manager)

Bindings registers captcha manager into container.

func GetBalance

func GetBalance(ctx context.Context) (float64, error)

GetBalance checks remaining credits on Nimbus Cloud.

func Protect

func Protect() router.Middleware

Protect returns a Nimbus HTTP middleware that verifies incoming captchas.

Usage:

app.Router.Post("/submit", captcha.Protect(), SubmitHandler)
app.Router.Post("/register", captcha.ProtectWithOptions(captcha.MiddlewareOptions{Provider: "recaptcha"}), RegisterHandler)

func ProtectWithOptions

func ProtectWithOptions(opts MiddlewareOptions) router.Middleware

ProtectWithOptions returns middleware configured with custom options.

Types

type BalanceResponse

type BalanceResponse struct {
	ErrorId          int     `json:"errorId"`
	ErrorCode        string  `json:"errorCode,omitempty"`
	ErrorDescription string  `json:"errorDescription,omitempty"`
	Balance          float64 `json:"balance"`
}

BalanceResponse returns remaining user credit or quota on Nimbus Cloud.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client handles interaction with the Nimbus Cloud Captcha API (CapSolver alternative).

func NewClient

func NewClient(cfg *Config) (*Client, error)

NewClient initializes a new Captcha API Client.

func (*Client) CreateTask

func (c *Client) CreateTask(ctx context.Context, payload TaskPayload) (*CreateTaskResponse, error)

CreateTask submits a new captcha task to Nimbus Cloud.

func (*Client) GetBalance

func (c *Client) GetBalance(ctx context.Context) (float64, error)

GetBalance checks the remaining credit on the Nimbus Cloud API key.

func (*Client) GetTaskResult

func (c *Client) GetTaskResult(ctx context.Context, taskID string) (*GetTaskResultResponse, error)

GetTaskResult queries the current status and solution for a task ID.

func (*Client) Solve

func (c *Client) Solve(ctx context.Context, payload TaskPayload) (*Solution, error)

Solve is a high-level helper that creates a task and polls until solved or timed out.

type Config

type Config struct {
	// APIKey for Nimbus Cloud Captcha API (or CapSolver fallback).
	APIKey string

	// Endpoint base URL for Nimbus Cloud Captcha API.
	// Default: "https://api.nimbuscloud.io/v1/captcha"
	Endpoint string

	// DefaultProvider for verification (e.g. "turnstile", "recaptcha", "hcaptcha", "nimbus").
	DefaultProvider string

	// ProviderSecretKeys maps provider names to secret keys used for server verification.
	// e.g. {"turnstile": "0x4AAAAAA...", "recaptcha": "6LeIx..."}
	ProviderSecretKeys map[string]string

	// MockMode when set to true will auto-solve tasks and approve verification
	// without reaching out to external networks (useful in dev/tests).
	MockMode bool

	// Timeout for captcha solving requests. Default: 60s.
	Timeout time.Duration

	// PollingInterval for checking task status. Default: 1s.
	PollingInterval time.Duration

	// MaxRetries for task polling. Default: 60.
	MaxRetries int
}

Config defines settings for the Captcha plugin.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns the standard default settings.

type CreateTaskRequest

type CreateTaskRequest struct {
	ClientKey string      `json:"clientKey"`
	Task      TaskPayload `json:"task"`
	AppID     string      `json:"appID,omitempty"`
}

CreateTaskRequest is the request sent to Nimbus Cloud API.

type CreateTaskResponse

type CreateTaskResponse struct {
	ErrorId          int    `json:"errorId"`
	ErrorCode        string `json:"errorCode,omitempty"`
	ErrorDescription string `json:"errorDescription,omitempty"`
	Status           string `json:"status,omitempty"` // "idle", "processing", "ready"
	TaskID           string `json:"taskId,omitempty"`
}

CreateTaskResponse is returned after task submission.

func CreateTask

func CreateTask(ctx context.Context, payload TaskPayload) (*CreateTaskResponse, error)

CreateTask submits a captcha task to Nimbus Cloud.

type GetTaskResultRequest

type GetTaskResultRequest struct {
	ClientKey string `json:"clientKey"`
	TaskID    string `json:"taskId"`
}

GetTaskResultRequest requests the outcome of an async captcha task.

type GetTaskResultResponse

type GetTaskResultResponse struct {
	ErrorId          int      `json:"errorId"`
	ErrorCode        string   `json:"errorCode,omitempty"`
	ErrorDescription string   `json:"errorDescription,omitempty"`
	Status           string   `json:"status"` // "processing" or "ready"
	Solution         Solution `json:"solution,omitempty"`
}

GetTaskResultResponse returns status and solution of a captcha task.

func GetTaskResult

func GetTaskResult(ctx context.Context, taskID string) (*GetTaskResultResponse, error)

GetTaskResult gets status or solution of an async task.

type Manager

type Manager struct {
	Client   *Client
	Verifier *Verifier
	// contains filtered or unexported fields
}

Manager coordinates Captcha Client and Verifier operations.

func GetManager

func GetManager() *Manager

GetManager returns global manager instance.

func NewManager

func NewManager(cfg *Config) (*Manager, error)

NewManager creates a Manager instance from configuration.

type MiddlewareOptions

type MiddlewareOptions struct {
	Provider       string
	TokenFormField string
	TokenHeader    string
}

MiddlewareOptions configures captcha protection middleware behavior.

func DefaultMiddlewareOptions

func DefaultMiddlewareOptions() MiddlewareOptions

DefaultMiddlewareOptions provides sensible default form/header field names.

type MockSolver

type MockSolver struct {
	ShouldFail bool
	MockToken  string
}

MockSolver provides mock responses for unit testing without external network calls.

func NewMockSolver

func NewMockSolver() *MockSolver

NewMockSolver creates a new MockSolver.

func (*MockSolver) Solve

func (m *MockSolver) Solve(ctx context.Context, payload TaskPayload) (*Solution, error)

Solve returns a pre-configured mock Solution.

type Plugin

type Plugin struct {
	nimbus.BasePlugin
	// contains filtered or unexported fields
}

Plugin integrates Nimbus Cloud Captcha solver & verifier into Nimbus apps.

func New

func New(cfg ...*Config) *Plugin

New creates a new Captcha plugin instance. Options may optionally pass custom Config.

func (*Plugin) Bindings

func (p *Plugin) Bindings(c *container.Container)

Bindings binds Services into Nimbus Container.

func (*Plugin) Boot

func (p *Plugin) Boot(app *nimbus.App) error

Boot satisfies the nimbus.Plugin interface.

func (*Plugin) DefaultConfig

func (p *Plugin) DefaultConfig() map[string]any

DefaultConfig returns default configuration parameters.

func (*Plugin) Middleware

func (p *Plugin) Middleware() map[string]router.Middleware

Middleware exposes named middleware for application router.

func (*Plugin) Register

func (p *Plugin) Register(app *nimbus.App) error

Register initializes configuration, builds Manager, and registers IoC bindings.

type Solution

type Solution struct {
	Token              string         `json:"token,omitempty"`
	GRecaptchaResponse string         `json:"gRecaptchaResponse,omitempty"`
	Text               string         `json:"text,omitempty"` // OCR result
	UserAgent          string         `json:"userAgent,omitempty"`
	RespKey            string         `json:"respKey,omitempty"`
	SolveTime          time.Duration  `json:"solveTime,omitempty"`
	Extra              map[string]any `json:"extra,omitempty"`
}

Solution contains the resulting token or solved output.

func Solve

func Solve(ctx context.Context, payload TaskPayload) (*Solution, error)

Solve solves a captcha challenge task programmatically via Nimbus Cloud (CapSolver alternative).

type TaskPayload

type TaskPayload struct {
	Type        TaskType          `json:"type"`
	WebsiteURL  string            `json:"websiteURL,omitempty"`
	WebsiteKey  string            `json:"websiteKey,omitempty"`
	PageAction  string            `json:"pageAction,omitempty"`
	MinScore    float64           `json:"minScore,omitempty"`
	Body        string            `json:"body,omitempty"` // For ImageToText base64 string
	Proxy       string            `json:"proxy,omitempty"`
	UserAgent   string            `json:"userAgent,omitempty"`
	MetaData    map[string]any    `json:"metadata,omitempty"`
	ExtraParams map[string]string `json:"extraParams,omitempty"`
}

TaskPayload defines parameters required to solve a captcha.

type TaskType

type TaskType string

TaskType represents the kind of Captcha challenge to solve.

const (
	// TurnstileTaskTypes
	TaskTypeTurnstile          TaskType = "TurnstileTask"
	TaskTypeTurnstileProxyless TaskType = "TurnstileTaskProxyless"

	// ReCaptchaTaskTypes
	TaskTypeReCaptchaV2          TaskType = "ReCaptchaV2Task"
	TaskTypeReCaptchaV2Proxyless TaskType = "ReCaptchaV2TaskProxyless"
	TaskTypeReCaptchaV3          TaskType = "ReCaptchaV3Task"
	TaskTypeReCaptchaV3Proxyless TaskType = "ReCaptchaV3TaskProxyless"
	TaskTypeReCaptchaEnterprise  TaskType = "ReCaptchaV2EnterpriseTask"

	// HCaptchaTaskTypes
	TaskTypeHCaptcha          TaskType = "HCaptchaTask"
	TaskTypeHCaptchaProxyless TaskType = "HCaptchaTaskProxyless"

	// Vision & OCR
	TaskTypeImageToText TaskType = "ImageToTextTask"

	// Advanced
	TaskTypeGeeTest   TaskType = "GeeTestTask"
	TaskTypeAmazonWAF TaskType = "AmazonWAFTask"
)

type VerificationResult

type VerificationResult struct {
	Success     bool      `json:"success"`
	ChallengeTS time.Time `json:"challenge_ts,omitempty"`
	Hostname    string    `json:"hostname,omitempty"`
	Score       float64   `json:"score,omitempty"`
	Action      string    `json:"action,omitempty"`
	ErrorCodes  []string  `json:"error-codes,omitempty"`
}

VerificationResult contains the result of validating a user's submitted token (Turnstile/reCAPTCHA).

func Verify

func Verify(ctx context.Context, provider, token, remoteIP string) (*VerificationResult, error)

Verify validates a submitted user captcha token.

type Verifier

type Verifier struct {
	// contains filtered or unexported fields
}

Verifier interface handles server-side token validation.

func NewVerifier

func NewVerifier(cfg *Config) *Verifier

NewVerifier creates a new Verifier instance.

func (*Verifier) VerifyToken

func (v *Verifier) VerifyToken(ctx context.Context, provider, token, remoteIP string) (*VerificationResult, error)

VerifyToken validates a token submitted by a client frontend against the designated provider.

Directories

Path Synopsis
cmd
server command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL