Documentation
¶
Overview ¶
Package captcha issues and checks self-hosted image captcha challenges.
It wraps github.com/mojocn/base64Captcha's digit-image driver behind two small, pluggable interfaces — Generator and Store — instead of building a challenge/response scheme from scratch. The package knows nothing about who is solving a challenge: a caller that needs to bind a challenge to a request, a session or a rate-limit key does so on its own side, by holding on to the opaque Challenge.ID it gets back from Generate. This package only ever sees ids and answers.
A challenge is single-use: once Verify has been called for an id, that id can never be verified again, whether the answer was right or wrong. This is what makes a captcha resistant to being brute-forced — an attacker gets exactly one guess per issued challenge, not unlimited guesses against one image.
This file covers only "generate an id and an image" / "check an id and an answer" — the self-hosted image captcha. Verifying a third-party token captcha (Cloudflare Turnstile, Google reCAPTCHA, hCaptcha) is a different mechanism — an HTTP call to that provider's siteverify endpoint, plus hostname pinning against the result — and lives alongside this in token.go, as TokenVerifier. The two share a package because they are both "captcha verification" from a caller's point of view, but neither depends on the other's types.
This file covers third-party token captcha verification: Cloudflare Turnstile, Google reCAPTCHA and hCaptcha all render a client-side widget (with a public site key) that hands the caller's page a one-time token, and all three are checked the same way server-side — POST the token and a secret key to the provider's "siteverify" endpoint, and read back a JSON verdict. TokenVerifier is that one HTTP round trip plus the hostname check that goes with it, shared by all three providers instead of copied once per provider or once per calling service.
TokenVerifier knows nothing about who is presenting the token — no user, account, session or request concept. It only ever sees a token, an optional client IP to forward, and the provider's reply.
Index ¶
Constants ¶
const ( DefaultMemoryStoreTTL = 5 * time.Minute DefaultMemoryStoreCapacity = 10_000 )
DefaultMemoryStoreTTL and DefaultMemoryStoreCapacity are the bounds DefaultMemoryStore uses.
const ( TurnstileEndpoint = "https://challenges.cloudflare.com/turnstile/v0/siteverify" RecaptchaEndpoint = "https://www.google.com/recaptcha/api/siteverify" HCaptchaEndpoint = "https://hcaptcha.com/siteverify" )
Public siteverify endpoints for the known providers. Exported as constants so a caller can build on them (e.g. to assert which one a Provider maps to) even though NewTokenVerifier already wires them up by default.
const DefaultTokenTimeout = 10 * time.Second
DefaultTokenTimeout is the request timeout NewTokenVerifier applies when WithTimeout is not given.
Variables ¶
var ( ErrRequest = errors.New("captcha: could not build siteverify request") ErrNetwork = errors.New("captcha: siteverify request failed") ErrBadStatus = errors.New("captcha: siteverify returned a non-200 status") ErrDecodeResponse = errors.New("captcha: could not decode siteverify response") )
Sentinel errors Verify's returned error wraps, so a caller can tell the four failure shapes of a siteverify call apart with errors.Is instead of string-matching:
- ErrRequest: the outgoing request could not even be built (a malformed endpoint override). Practically unreachable with the built-in endpoints.
- ErrNetwork: the request was sent but no response came back — DNS failure, connection refused, TLS error, or the context's timeout or cancellation firing first. Wraps the underlying network/context error too, so errors.Is(err, context.DeadlineExceeded) also works.
- ErrBadStatus: a response came back, but its HTTP status was not 200.
- ErrDecodeResponse: the response was 200 but its body was not the JSON shape siteverify replies with.
A provider reply of {"success": false, ...} is deliberately NOT one of these — it is not a failure of the verification mechanism, it is the mechanism working and reporting a bad token. That comes back as (Result{ Success: false, ErrorCodes: ...}, nil): see Verify's doc comment.
Functions ¶
func HostOf ¶
HostOf extracts the bare hostname (no scheme, no port) from a base URL like "https://panel.example.com:8443/". Returns "" for an empty or unparseable URL. It exists so a caller can build the WithAllowedHostnames list straight from a configured public base URL without duplicating this parsing at each call site.
Types ¶
type Challenge ¶
type Challenge struct {
// ID identifies this challenge to a later Verify call. Treat it as
// opaque; its format is not part of this package's API.
ID string
// Image is a "data:image/...;base64,..." URL, ready for an <img src>.
Image string
}
Challenge is an issued, unsolved captcha: an opaque id and a ready-to-embed image. It carries no information about who requested it or what it will be used for.
type Generator ¶
type Generator interface {
// Generate creates and stores a new challenge.
Generate() (Challenge, error)
// Verify reports whether answer is correct for the challenge identified
// by id. It consumes the challenge: a repeat call with the same id
// always returns false afterward, regardless of the answer given either
// time. An empty id or answer is always false and never touches the
// store.
Verify(id, answer string) bool
}
Generator issues challenges and checks answers against them.
Implementations must make Verify single-use: once an id has been checked — whether the answer was correct or not — a later call with the same id must return false. Implementations must also be safe for concurrent use, since a captcha is typically issued and verified from concurrent HTTP handlers.
type ImageGenerator ¶
type ImageGenerator struct {
// contains filtered or unexported fields
}
ImageGenerator is the default Generator: a self-hosted, drawn image captcha with no external calls. Zero external calls also means it works unchanged behind a network that cannot reach a third-party captcha provider.
func NewImageGenerator ¶
func NewImageGenerator(store Store, opts ...Option) *ImageGenerator
NewImageGenerator builds an ImageGenerator over store. A nil store is replaced with DefaultMemoryStore(), a TTL- and capacity-bounded in-process store; pass a different Store (e.g. a Redis-backed one) to share challenges across multiple instances of a caller's service.
func (*ImageGenerator) Generate ¶
func (g *ImageGenerator) Generate() (Challenge, error)
Generate implements Generator. Each call draws a fresh image and id; the underlying driver generates the id, so concurrent calls never collide on one.
func (*ImageGenerator) Verify ¶
func (g *ImageGenerator) Verify(id, answer string) bool
Verify implements Generator.
type MemoryStore ¶
type MemoryStore struct {
// contains filtered or unexported fields
}
MemoryStore is an in-process Store bounded on two axes so it cannot grow without limit: entries older than ttl are treated as gone, and the store never holds more than maxItems entries at once — once full, the oldest entry is evicted to make room for a new one, even if it has not expired yet. Both bounds are enforced without a background goroutine: expired and over-capacity entries are purged inline on Set, and a lookup that finds an expired entry deletes it too. There is nothing to shut down and nothing that leaks if the store is simply dropped.
MemoryStore is the default Store used when a caller does not supply one. It is safe for concurrent use.
func DefaultMemoryStore ¶
func DefaultMemoryStore() *MemoryStore
DefaultMemoryStore returns a MemoryStore using the package's default TTL and capacity.
func NewMemoryStore ¶
func NewMemoryStore(maxItems int, ttl time.Duration) *MemoryStore
NewMemoryStore returns a MemoryStore that keeps at most maxItems entries, each expiring ttl after it was set. maxItems <= 0 or ttl <= 0 are replaced with the package defaults rather than producing an unbounded store.
func (*MemoryStore) Get ¶
func (s *MemoryStore) Get(id string, clear bool) string
Get implements Store.
func (*MemoryStore) Len ¶
func (s *MemoryStore) Len() int
Len reports the number of entries currently held, including any that have expired but not yet been purged by a Set or a lookup. Exposed mainly so tests can observe the capacity cap taking effect.
type Option ¶
type Option func(*imageGeneratorConfig)
Option configures an ImageGenerator.
func WithDriver ¶
func WithDriver(driver base64Captcha.Driver) Option
WithDriver replaces the captcha driver entirely, e.g. to switch from digits to base64Captcha's arithmetic, Chinese-character or audio drivers. It takes a base64Captcha.Driver directly, so a caller reaching for this needs the base64Captcha import too; ImageGenerator's own exported API never requires it.
type Provider ¶
type Provider string
Provider names a third-party token captcha service. The zero value is not a valid provider on its own — pass WithEndpoint alongside it to verify against a custom or self-hosted siteverify-compatible endpoint.
type Result ¶
type Result struct {
// Success is the provider's own verdict on the token, already folded
// together with the hostname-pinning check below: it is true only when
// the provider accepted the token AND (hostname pinning is not
// configured, or the provider's reported hostname is on the allow
// list). Treat this as the one field to branch on for pass/fail.
Success bool
// Hostname is the hostname the provider reports the challenge was
// solved on. Providers omit this in some configurations (e.g. reCAPTCHA
// v2 with domain verification turned off), in which case it is "".
Hostname string
// ChallengeTS is the provider's own timestamp for when the challenge
// was solved, exactly as returned (ISO 8601, e.g.
// "2024-01-02T15:04:05Z"). Not parsed, since callers that want it
// parsed can do so themselves and this package should not fail Verify
// over a provider using a slightly different time layout.
ChallengeTS string
// ErrorCodes is the provider's own error-codes array, verbatim, present
// when Success (before hostname pinning) is false. Safe to log: it
// never contains the secret or the token, only provider-defined
// short codes like "invalid-input-secret" or "timeout-or-duplicate".
ErrorCodes []string
// HostnameMismatch is true when the provider accepted the token but its
// reported Hostname was not on the configured allow list — the specific
// case Success=false does not by itself distinguish from an ordinary
// bad/expired token. See TokenVerifier's WithAllowedHostnames doc for
// what "allow list" means here, including its empty-list behavior.
HostnameMismatch bool
}
Result is the outcome of one Verify call, carrying enough of the provider's reply for the caller to log or branch on without this package exposing the raw JSON.
type Store ¶
type Store interface {
// Set stores value under id, replacing any existing entry.
Set(id, value string) error
// Get returns the value stored under id, or "" if none exists or it has
// expired. When clear is true the entry is removed as part of the read,
// regardless of whether it was found.
Get(id string, clear bool) string
// Verify reports whether answer matches the value stored under id. When
// clear is true the entry is removed as part of the check, regardless of
// whether answer matched — a wrong guess burns the challenge exactly like a
// right one, so a store configured for single-use never allows brute-forcing
// the same id twice.
Verify(id, answer string, clear bool) bool
}
Store persists challenge answers between Generate and Verify. Its method set is intentionally identical to github.com/mojocn/base64Captcha's own Store interface, so any value satisfying Store also satisfies that package's Store without this file importing it: a caller can swap in a Redis-backed, etcd-backed or any other implementation, including a base64Captcha community store, with no adapter needed.
clear controls whether the entry is deleted as part of the read. Callers that want single-use challenges (the only safe default for a captcha) pass clear as true.
type TokenOption ¶
type TokenOption func(*tokenVerifierConfig)
TokenOption configures a TokenVerifier built by NewTokenVerifier.
func WithAllowedHostnames ¶
func WithAllowedHostnames(hosts ...string) TokenOption
WithAllowedHostnames turns on hostname pinning: after the provider accepts a token, its reported Hostname must case-insensitively match one of hosts, or Verify reports Success: false, HostnameMismatch: true. This is the defense against a token solved on a different site that happens to share this site key/secret being replayed against this caller.
Chosen default — an EMPTY or never-given host list DISABLES this check entirely, and Verify accepts whatever hostname (or lack of one) the provider reports. This mirrors both call sites this package's token verification was consolidated from, which made the same choice for the same reason: a hostname to pin against comes from the caller's own configured public URL, and a deployment that has not configured one (or configured it wrong) must not be locked out of login entirely by a captcha check silently rejecting every token. The tradeoff this makes is explicit: with no allow list configured, hostname pinning provides NO protection against cross-site token replay — a caller that has a known origin should always call WithAllowedHostnames rather than rely on this default.
Empty strings in hosts are ignored; passing only empty strings (or none at all) is equivalent to not calling this option.
func WithEndpoint ¶
func WithEndpoint(rawURL string) TokenOption
WithEndpoint overrides the siteverify URL NewTokenVerifier would otherwise pick from Provider. Two uses: pointing a verifier at a mock server in tests, and pointing it at a private or enterprise siteverify-compatible deployment (e.g. hCaptcha Enterprise's dedicated endpoint, or a self-hosted Turnstile-compatible service) in production. It is also the only way to build a working verifier for a Provider outside the three known constants — NewTokenVerifier returns an error for an unknown Provider unless this option is also given.
func WithHTTPClient ¶
func WithHTTPClient(c *http.Client) TokenOption
WithHTTPClient supplies the *http.Client Verify sends requests with, letting a test point it at an httptest.Server (via the client's Transport) or a caller share a connection-pooled client across verifiers. Unset, NewTokenVerifier builds one of its own with Timeout set from WithTimeout (or DefaultTokenTimeout).
Whichever client is in effect, Verify always additionally bounds the request with context.WithTimeout using the configured timeout before calling it — so even a client with no Timeout of its own (like http.DefaultClient) cannot hang a caller forever. Passing an http.DefaultClient works but is discouraged: bring your own client so its transport-level settings (proxies, connection limits) are under the caller's control too.
func WithTimeout ¶
func WithTimeout(d time.Duration) TokenOption
WithTimeout overrides DefaultTokenTimeout as the bound Verify places on the whole siteverify round trip, applied via context.WithTimeout regardless of which http.Client is in effect (see WithHTTPClient). A non-positive value is ignored and the default is kept, so a verifier can never end up with no timeout at all.
type TokenVerifier ¶
type TokenVerifier struct {
// contains filtered or unexported fields
}
TokenVerifier checks third-party captcha tokens against one provider's siteverify endpoint. Build one with NewTokenVerifier; the zero value is not usable (it has no endpoint and no secret).
func NewTokenVerifier ¶
func NewTokenVerifier(provider Provider, secret string, opts ...TokenOption) (*TokenVerifier, error)
NewTokenVerifier builds a TokenVerifier for provider, authenticating to its siteverify endpoint with secret. secret must be non-empty. provider must be one of the known constants (ProviderTurnstile, ProviderRecaptcha, ProviderHCaptcha) unless WithEndpoint is also given, in which case provider is only used as a label — the endpoint it names is never resolved.
Constructing one of these per request is fine, and is what a caller with live-reloadable configuration has to do, since the secret and the allowed hostnames are fixed here. The http.Client built when WithHTTPClient is omitted has a nil Transport, so it shares http.DefaultTransport's connection pool with every other client built the same way: 50 sequential verifications through 50 freshly built verifiers open one connection, not 50.
Supplying WithHTTPClient with a client that carries its own &http.Transport{}, and constructing per request, is the case that does leak a pool per request. Share that client, or leave the Transport nil.
func (*TokenVerifier) Verify ¶
Verify POSTs token (and remoteIP, if given) to the provider's siteverify endpoint and reports what came back.
Two different things can make this fail, and they are deliberately not confused with each other:
- A non-nil error means the CHECK ITSELF could not be completed: the request could not be built (ErrRequest), the network call failed or timed out (ErrNetwork), the response status was not 200 (ErrBadStatus), or the 200 response body was not valid siteverify JSON (ErrDecodeResponse). A caller should treat this as "unknown", not as "rejected" — fail closed (do not treat the captcha as solved), but do not report it to the end user the same way as a wrong answer, since a retry by the same user is unlikely to help while the provider is unreachable.
- A nil error with Result.Success == false means the check completed and the token was rejected — either by the provider itself (see Result.ErrorCodes) or by hostname pinning (see Result.HostnameMismatch). This is an ordinary "bad captcha", safe to surface to the end user as such.
An empty token is always (Result{}, nil) without making a network call — there is nothing for the provider to check.
secret is never included in the returned error, in Result, or anywhere else Verify writes to — a caller can log a Verify error directly.