captcha

package
v0.27.2 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const DefaultMinScore = 0.5

DefaultMinScore defines the default minimum passing score for Google reCAPTCHA v3.

View Source
const DefaultVerifyTimeout = 10 * time.Second

DefaultVerifyTimeout specifies the maximum duration allowed for outgoing verification requests.

View Source
const HeaderCaptchaResponse = "x-captcha-response"

HeaderCaptchaResponse is the standard HTTP header used by client applications to submit the captcha token.

View Source
const PluginID = "captcha"

PluginID is the unique string identifier for the Captcha plugin ("captcha").

Variables

View Source
var (
	// ErrMissingSecretKey is returned when the SecretKey option is not configured.
	ErrMissingSecretKey = errors.New("captcha: missing secret key")

	// ErrMissingCaptchaResponse is returned when incoming request lacks the x-captcha-response header.
	ErrMissingCaptchaResponse = errors.New("captcha: missing captcha response header")

	// ErrVerificationFailed is returned when the captcha provider rejects the token.
	ErrVerificationFailed = errors.New("captcha: verification failed")

	// ErrServiceUnavailable is returned when outgoing request to provider fails or times out.
	ErrServiceUnavailable = errors.New("captcha: service unavailable or timeout")

	// ErrInvalidProvider is returned when an unsupported captcha provider is specified.
	ErrInvalidProvider = errors.New("captcha: unsupported captcha provider")

	// ErrScoreTooLow is returned when reCAPTCHA v3 score is lower than MinScore threshold.
	ErrScoreTooLow = errors.New("captcha: recaptcha score below required minimum")

	// ErrActionMismatch is returned when returned captcha action does not match ExpectedAction.
	ErrActionMismatch = errors.New("captcha: action does not match expected action")

	// ErrHostnameMismatch is returned when returned captcha hostname is not in AllowedHostnames.
	ErrHostnameMismatch = errors.New("captcha: hostname not in allowed list")
)
View Source
var DefaultEndpoints = []string{
	"/sign-up/email",
	"/sign-in/email",
	"/request-password-reset",
}

DefaultEndpoints lists the default authentication endpoints protected by captcha verification.

View Source
var DefaultExemptEndpoints = []string{
	"/sign-in/email-otp",
}

DefaultExemptEndpoints lists endpoints that are exempted from captcha verification.

View Source
var DefaultSiteVerifyURLs = map[Provider]string{
	ProviderCloudflareTurnstile: "https://challenges.cloudflare.com/turnstile/v0/siteverify",
	ProviderGoogleRecaptcha:     "https://www.google.com/recaptcha/api/siteverify",
	ProviderHCaptcha:            "https://api.hcaptcha.com/siteverify",
	ProviderCaptchaFox:          "https://api.captchafox.com/siteverify",
}

DefaultSiteVerifyURLs maps each captcha provider to its official verification endpoint URL.

Functions

func DefaultIPExtractor

func DefaultIPExtractor(r *http.Request) string

DefaultIPExtractor extracts remote client IP address from request headers or RemoteAddr.

Types

type Config

type Config struct {
	// Provider specifies the active captcha provider (Turnstile, reCAPTCHA, hCaptcha, CaptchaFox).
	Provider Provider

	// SecretKey is the private secret key obtained from the captcha provider dashboard.
	SecretKey string

	// SiteKey is the public site key (required by hCaptcha and CaptchaFox verification endpoints).
	SiteKey string

	// Endpoints defines the list of HTTP request path URIs protected by captcha verification.
	Endpoints []string

	// ExemptEndpoints defines paths explicitly exempted from captcha verification.
	ExemptEndpoints []string

	// SiteVerifyURLOverride allows overriding the official provider siteverify URL (useful for testing or enterprise endpoints).
	SiteVerifyURLOverride string

	// MinScore sets minimum score threshold for Google reCAPTCHA v3 (default: 0.5).
	MinScore float64

	// ExpectedAction validates expected action parameter for Turnstile or reCAPTCHA v3 responses.
	ExpectedAction string

	// AllowedHostnames restricts valid captcha tokens to specified hostnames/domains.
	AllowedHostnames []string

	// HTTPClient allows injecting custom *http.Client for outgoing verification requests.
	HTTPClient *http.Client

	// Timeout specifies maximum duration allowed for outgoing verification HTTP call (default: 10s).
	Timeout time.Duration

	// IPExtractor function to extract remote IP address from incoming requests.
	IPExtractor IPExtractorFunc
}

Config structures all operational settings for the Captcha plugin.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns default operational configuration for the Captcha plugin.

type IPExtractorFunc

type IPExtractorFunc func(r *http.Request) string

IPExtractorFunc extracts the client's remote IP address from an incoming HTTP request.

type Option

type Option func(*Config)

Option configures functional options for the Captcha plugin.

func WithAllowedHostnames

func WithAllowedHostnames(hostnames []string) Option

WithAllowedHostnames sets allowed hostnames list.

func WithEndpoints

func WithEndpoints(endpoints []string) Option

WithEndpoints configures protected endpoint URIs.

func WithExemptEndpoints

func WithExemptEndpoints(exempt []string) Option

WithExemptEndpoints configures exempted endpoint URIs.

func WithExpectedAction

func WithExpectedAction(action string) Option

WithExpectedAction sets expected action string for Turnstile or reCAPTCHA v3.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient configures custom HTTP client for verification calls.

func WithIPExtractor

func WithIPExtractor(fn IPExtractorFunc) Option

WithIPExtractor configures custom client IP extractor function.

func WithMinScore

func WithMinScore(score float64) Option

WithMinScore sets minimum score threshold for Google reCAPTCHA v3.

func WithProvider

func WithProvider(p Provider) Option

WithProvider sets the captcha provider.

func WithSecretKey

func WithSecretKey(key string) Option

WithSecretKey sets the provider secret key.

func WithSiteKey

func WithSiteKey(key string) Option

WithSiteKey sets the provider site key.

func WithSiteVerifyURLOverride

func WithSiteVerifyURLOverride(urlStr string) Option

WithSiteVerifyURLOverride overrides provider default siteverify URL.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets maximum timeout for verification HTTP call.

type Plugin

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

Plugin implements Captcha verification middleware for go-modular-auth.

func New

func New(opts ...Option) *Plugin

New instantiates a new Captcha plugin configured with functional options.

func (*Plugin) Config

func (p *Plugin) Config() Config

Config returns a copy of active plugin configuration settings.

func (*Plugin) ID

func (p *Plugin) ID() string

ID returns the unique string identifier for the plugin ("captcha").

func (*Plugin) Init

func (p *Plugin) Init(ctx *plugin.Context) error

Init initializes the plugin within the global GoModularAuth context.

func (*Plugin) IsProtectedPath

func (p *Plugin) IsProtectedPath(path string) bool

IsProtectedPath determines whether a request path requires captcha verification.

func (*Plugin) Protect added in v0.20.0

func (p *Plugin) Protect() func(next http.Handler) http.Handler

Protect returns a standard net/http middleware handler to intercept and validate captcha tokens on protected endpoints.

func (*Plugin) VerifyToken

func (p *Plugin) VerifyToken(ctx context.Context, token string, remoteIP string) error

VerifyToken validates a captcha response token against the configured provider.

type Provider

type Provider string

Provider identifies a supported captcha verification provider.

const (
	// ProviderCloudflareTurnstile represents Cloudflare Turnstile captcha service.
	ProviderCloudflareTurnstile Provider = "cloudflare-turnstile"

	// ProviderGoogleRecaptcha represents Google reCAPTCHA v2 / v3 service.
	ProviderGoogleRecaptcha Provider = "google-recaptcha"

	// ProviderHCaptcha represents hCaptcha verification service.
	ProviderHCaptcha Provider = "hcaptcha"

	// ProviderCaptchaFox represents CaptchaFox verification service.
	ProviderCaptchaFox Provider = "captchafox"
)

type Verifier

type Verifier struct{}

Verifier handles outgoing HTTP verification requests to captcha provider APIs.

func NewVerifier

func NewVerifier() *Verifier

NewVerifier returns a new Verifier instance.

func (*Verifier) Verify

func (v *Verifier) Verify(ctx context.Context, cfg Config, token string, remoteIP string) error

Verify executes verification for the configured captcha provider.

Jump to

Keyboard shortcuts

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