captcha

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 47 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

laravel-go-captcha

CI Go reference docs Go 1.27

Go port of mews/captcha: a self-hosted image captcha for Laravel for Go, with profiles, session and keyed modes, one-time challenges and validation rules. It follows mews/captcha 3.5 and is tested against fixtures that the PHP package itself generates. The image is drawn and the answer checked on your own server; nothing is sent to a third party.

Status: alpha. v0.1.0 is the first release; the API may still change before 1.0.

Quick start

go get github.com/bowerbird-si/laravel-go-captcha

Register the package, show the image, and check the answer with the rule:

The package needs APP_KEY and a cache store shared by every process (Redis or the database cache; for a single process, CAPTCHA_SINGLE_PROCESS=true allows the default memory store).

// bootstrap/app.go
Packages: []laravel.Package{captcha.New()},

// The form: <img src="{{captchaSrc "default"}}"> and <input name="captcha">
func (f *ContactForm) Rules(r *web.Request) (validation.Rules, error) {
	return validation.For(f, rule.Field(&f.Captcha, rule.Required, captcha.Rule(r))), nil
}

The same code is in example_test.go; CI runs it. The guide covers keyed captchas for APIs, profiles and testing.

PHP parity

Follows mews/captcha 3.5.1 (commit 7154a930e88b).

Parity level Abilities Covered Diverged Planned PHP fixtures Last verified
core 87 52 35 0 44 2026-12-04

Every ability is listed in parity.toml, with the tests that cover it or the reason it differs.

The PHP fixtures are generated by laravel-rust-captcha, the Rust port, which runs the real mews/captcha in a pinned PHP project. Both ports test against the same files, copied unchanged into testdata/conformance, and share the answer verifier byte for byte.

Differences from PHP

The port keeps the routes, profiles and rules, and changes these on purpose. Each one is tested: testdata/conformance/differences.json lists the PHP result next to the ports' result.

  • The API key is an opaque challenge id. PHP's key was a bcrypt hash of the answer, so a client could check guesses offline.
  • A challenge answers only the profile it was issued for. A rule without a profile means default.
  • The rule fails a missing or blank answer even without required, and accepts the answer "0".
  • Surrounding spaces in an answer are ignored.
  • An unknown profile is a 404, and invalid settings stop the application at startup.
  • HEAD on an image route issues nothing. Images are sent with Cache-Control: no-store, and the JPEG quality setting is used.
  • Each profile starts from the class defaults; settings never carry over from one profile to the next.
  • captchaImg escapes attribute values and drops event-handler attributes.
  • Wrong answers are limited per client and profile, and issuing images per client.

Migrating from PHP has the full list and the Go equivalent of each call.

Installation and configuration

See the guide: getting started, configuration and testing.

Compatibility

Module Framework Go
github.com/bowerbird-si/laravel-go-captcha go.laravel.com v0.2.0 1.27

105 tests · 44 PHP fixtures · 4 fuzz targets (counted by kit readme)

Contributing

Issues and pull requests are welcome, of any size: bug reports, failing test cases, PHP behaviour the port gets wrong, docs fixes, new features. Contributions written with AI coding agents are welcome too; please say what you checked. Run scripts/kit ci before opening a pull request, and see CONTRIBUTING.md. If you aren't sure, open an issue first.

Credits

Based on mews/captcha by MeWebStudio (Muharrem ERİN), MIT. The bundled fonts keep their own licences. The notices are in NOTICE.

Status and licence

Maintenance status: active. MIT licensed, see LICENSE. Copyright (c) 2026 Bowerbird SI.

Community package, not affiliated with Laravel.

Documentation

Overview

Package captcha is a self-hosted image captcha for Laravel for Go, a port of the PHP package mews/captcha. Every image is a challenge with its own id; a successful check consumes it atomically, and a challenge only answers the profile it was issued for.

Index

Examples

Constants

View Source
const DefaultMessage = "The :attribute is incorrect."

DefaultMessage is the rule's message. PHP's was the raw key "validation.captcha".

View Source
const NoDeadline time.Duration = 0

NoDeadline is the Expire of a profile whose challenges have no deadline of their own: they live for Config.NoDeadlineLifetime.

View Source
const Unlimited = challenge.Unlimited

Unlimited is the attempt limit of a profile whose challenges may be retried until they are answered correctly. The failure limit still applies.

Variables

View Source
var ErrContended = challenge.ErrContended

ErrContended means concurrent changes prevented a check from committing. PHP's check has no equivalent error.

View Source
var ErrRendererBusy = errors.New("captcha: image renderer is busy")

ErrRendererBusy means PHP's Captcha::create equivalent could not start an image within the render queue's short wait.

View Source
var ErrTooManyFailures = errors.New("captcha: too many wrong answers; try again in a minute")

ErrTooManyFailures is returned when a client gave too many wrong answers.

View Source
var ErrUnknownProfile = errors.New("captcha: unknown profile")

ErrUnknownProfile is returned for a profile that isn't configured.

Functions

func Check

func Check(r *web.Request, value string, opts ...CheckOption) (bool, error)

Check answers r's session challenge (PHP's captcha_check). Without WithProfile it requires the "default" profile.

Example

ExampleCheck shows PHP's captcha_check and captcha_api_check in Go handlers.

app := captchaExampleApp("", laravel.Routes{Web: func(route *routing.Router, _ *config.Config) {
	route.Post("/session", func(r *web.Request) *web.Response {
		ok, err := captcha.Check(r, r.FormValue("captcha"), captcha.WithProfile("contact"))
		if err != nil {
			return web.Fail(err)
		}
		return web.JSON(ok)
	})
	route.Post("/keyed", func(r *web.Request) *web.Response {
		ok, err := captcha.CheckKey(r, r.FormValue("captcha_key"), r.FormValue("captcha"), "math")
		if err != nil {
			return web.Fail(err)
		}
		return web.JSON(ok)
	})
}})
defer app.Close()

for _, path := range []string{"/session", "/keyed"} {
	response := captchaExampleRequest(app, "POST", path, "captcha=wrong")
	fmt.Println(strings.TrimSpace(response.Body.String()))
}
Output:
false
false

func CheckKey

func CheckKey(ctx context.Context, key, value, profile string) (bool, error)

CheckKey answers a keyed challenge (PHP's captcha_api_check).

func Image

func Image(r *web.Request, profile string) *web.Response

Image is PHP's captcha() helper. It issues a session challenge and returns its JPEG response. Use it in a web handler with session middleware.

func Img

func Img(ctx context.Context, profile string, attrs ...Attr) template.HTML

Img is PHP's captcha_img. It renders a session image with escaped attributes in caller order. It accepts alt, class, id, title, width, height, loading, decoding, role and aria-* attributes. If the caller omits alt, it supplies alt="captcha".

func PHPCharacters

func PHPCharacters() []string

PHPCharacters is the alphabet mews/captcha ships.

func PHPProfiles

func PHPProfiles() map[string]Profile

PHPProfiles returns the five profiles that mews/captcha ships, as shipped. The "math" profile is a nine-character captcha: PHP never turns Math on for it.

func Src

func Src(ctx context.Context, profile string) string

Src is PHP's captcha_src. It returns an absolute URL for a session image with an eight-character cache buster. An empty or invalid profile name uses "/captcha/default".

Example

ExampleSrc shows PHP's captcha_src as an Inertia page prop.

app := captchaExampleApp("", laravel.Routes{Web: func(route *routing.Router, _ *config.Config) {
	route.Get("/contact", func(r *web.Request) *web.Response {
		return inertia.Render("Contact", inertia.Props{
			"captcha": map[string]string{"src": captcha.Src(r, "contact")},
		})
	}).Middleware(inertia.Middleware{})
}})
defer app.Close()

request := httptest.NewRequest("GET", "https://example.test/contact", nil)
request.Header.Set("X-Inertia", "true")
response := httptest.NewRecorder()
app.ServeHTTP(response, request)
fmt.Println(strings.Contains(response.Body.String(), "https://example.test/captcha/contact?"))
Output:
true

Types

type Attr

type Attr struct {
	Name, Value string
}

Attr is a name and value from PHP's captcha_img attributes array.

type Captcha

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

Captcha is the package and its service. Install it with laravel.Options.Packages, and reach it from a context with From.

func From

func From(ctx context.Context) *Captcha

From returns the Captcha that ctx's application installed.

func New

func New(configure ...func(cfg *Config)) *Captcha

New returns the package. Each configure function changes the settings after the package reads them from the environment.

func (*Captcha) CheckKeyed

func (c *Captcha) CheckKeyed(ctx context.Context, key, value, profile string) (Verdict, error)

CheckKeyed answers the keyed challenge key for profile ("" means "default") and returns the verdict. When disabled it returns Missing without looking up the key.

func (*Captcha) CheckSession

func (c *Captcha) CheckSession(r *web.Request, value string, opts ...CheckOption) (Verdict, error)

CheckSession answers r's session challenge and returns the verdict. When captcha is disabled it returns Missing without using the session.

func (*Captcha) Config

func (c *Captcha) Config() Config

Config returns a copy of the active settings, corresponding to PHP's config/captcha.php. The renderer and filesystem are shared dependencies.

func (*Captcha) Issue

func (c *Captcha) Issue(ctx context.Context, profile string) (Challenge, error)

Issue creates a keyed challenge for profile and draws it. It returns an error when captcha is disabled.

func (*Captcha) RecordAnswers

func (c *Captcha) RecordAnswers(record func(key, answer string))

RecordAnswers makes the package report every answer it issues, with the keyed challenge id or "session:<profile>" for a session challenge. It is for captchatest: production code never calls it, and nothing keeps answers otherwise.

func (*Captcha) Register

func (c *Captcha) Register(app *laravel.Registrar) error

Register installs the package in an application. It builds everything from scratch, because Laravel may call it more than once.

type Challenge

type Challenge struct {
	// Key is the opaque id the client sends back in the key field.
	Key string `json:"key"`
	// Profile is the profile it was issued for.
	Profile string `json:"-"`
	// Sensitive reports whether the answer keeps its case.
	Sensitive bool `json:"sensitive"`
	// Image is the JPEG.
	Image []byte `json:"-"`
}

Challenge is an issued keyed challenge: its id for the client, and its image.

func Issue

func Issue(ctx context.Context, profile string) (Challenge, error)

Issue creates a keyed challenge for profile and draws it. It never touches the session. The issuance limit applies.

Example

ExampleIssue shows PHP's Captcha::create in API mode with a server-rendered keyed form. To enable refresh, wrap captchaField and a button together in an element with data-captcha-field, add data-captcha-refresh to the type="button" button, and load {{vendorAsset "captcha" "refresh.js"}}.

const form = `<form method="post">
		{{csrfField}}
		{{captchaField .Captcha}}
		<label>Security code <input name="captcha" required></label>
		<button>Send</button>
	</form>`
app := captchaExampleApp(form, laravel.Routes{Web: func(route *routing.Router, _ *config.Config) {
	route.Get("/contact", func(r *web.Request) *web.Response {
		ch, err := captcha.Issue(r, "default")
		if err != nil {
			return web.Fail(err)
		}
		return ch.NoStore(web.View("form", struct{ Captcha captcha.Challenge }{ch}))
	})
	route.Post("/contact", func(r *web.Request) *web.Response {
		if _, err := r.Validate[exampleAPIForm](); err != nil {
			return web.Fail(err)
		}
		return web.Text("sent")
	})
}})
defer app.Close()

page := captchaExampleRequest(app, "GET", "/contact", "")
fmt.Println(page.Header().Get("Cache-Control"))
fmt.Println(strings.Contains(page.Body.String(), `name="captcha_key" value="`))
Output:
no-store
true

func (Challenge) DataURI

func (ch Challenge) DataURI() string

DataURI returns the image as a data: URI.

func (Challenge) NoStore

func (ch Challenge) NoStore(res *web.Response) *web.Response

NoStore marks a response that carries this challenge as not cacheable, so one challenge never reaches several visitors.

type CheckOption

type CheckOption func(*checkOptions)

CheckOption changes what a check requires.

func WithProfile

func WithProfile(name string) CheckOption

WithProfile makes a check require a challenge of the named profile.

type Config

type Config struct {
	// Disable turns the captcha off: no routes, and every rule passes.
	// Issue returns an error, Image returns HTTP 404, and the direct checks
	// return false. Src and Img still generate URLs and markup. CAPTCHA_DISABLE
	// sets it.
	Disable bool
	// Characters is the default alphabet. Each entry is one drawn character
	// (it may be several runes).
	Characters []string
	// Profiles are the named captcha styles; "default" must exist.
	Profiles map[string]Profile
	// Fonts and Backgrounds replace PHP's fontsDirectory and bgsDirectory.
	// Each path may name a file or directory. Nil selects bundled assets.
	Fonts, Backgrounds []string
	// AssetFS supplies PHP's asset paths from a filesystem such as embed.FS.
	// Nil reads local paths. "{assets}/" always refers to bundled assets.
	AssetFS fs.FS
	// RenderConcurrency caps simultaneous calls to PHP's Captcha::create
	// equivalent. Zero uses GOMAXPROCS.
	RenderConcurrency int
	// Renderer supplies a custom implementation of PHP's image renderer.
	// Nil selects the bundled drawing pipeline.
	Renderer Renderer
	// Store names the cache store for challenges and failure quotas, or ""
	// for the application's default. CAPTCHA_STORE sets it. It must be
	// shared between processes.
	Store string
	// SingleProcess allows a process-local store (memory), for an application
	// that runs exactly one process. CAPTCHA_SINGLE_PROCESS sets it.
	SingleProcess bool
	// TrustStore confirms the resolved cache store is shared between processes
	// and supports atomic compare-and-swap and counters. In production, a
	// database cache configured with SQLite also requires it to confirm the
	// resolved store uses a separate database file.
	TrustStore bool
	// Throttle is how many challenges a client may get per minute, on every
	// entry point; 0 turns it off. CAPTCHA_THROTTLE sets it.
	Throttle int
	// Failures caps wrong answers per client and profile in a fixed minute.
	// Checks reserve one unit in advance. Zero turns the limit off.
	// CAPTCHA_FAILURES sets it.
	Failures int
	// NoDeadlineLifetime is how long a challenge of a NoDeadline profile
	// lives.
	NoDeadlineLifetime time.Duration
	// Field and KeyField are the form fields of the answer and the keyed
	// challenge id. They are never flashed as old input.
	Field, KeyField string
}

Config is the package's settings. New's configure functions change it after the package reads the environment.

func ParsePHPConfig

func ParsePHPConfig(data []byte) (Config, error)

ParsePHPConfig imports json_encode(config('captcha')) from mews/captcha. It accepts disable, characters, fontsDirectory, bgsDirectory, and named profiles. Each profile starts from Defaults, and "default" is required. Profile settings include length, width, height, quality, math, sensitive, expire (positive seconds), characters, fonts, backgrounds, lines, lineWidth, lineColor, angle, contrast, sharpen, blur, invert, bgImage, bgColor, fontColors, textLeftPadding, and marginTop. Relative asset paths use the working directory.

The importer ignores the top-level driver, the profile encrypt setting, and other unknown profile settings. It rejects profile-level fontsDirectory and bgsDirectory, nonpositive or overflowing expiry values, and invalid profiles or values. To use a profile without a deadline, set its Expire to NoDeadline in Go.

type KeyedRule

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

KeyedRule checks a keyed challenge, PHP's `captcha_api` rule. It reads the challenge id from the key field (captcha_key unless Config.KeyField says otherwise), or from KeyedWith.

func Keyed

func Keyed() KeyedRule

Keyed returns the keyed rule. It requires the "default" profile unless Profile names another.

Example

ExampleKeyed shows PHP's captcha_api flow. JSON clients get an image and a key from /captcha/api/default, then submit captcha and captcha_key.

app := captchaExampleApp("", laravel.Routes{Bare: func(route *routing.Router, _ *config.Config) {
	route.Post("/submit", func(r *web.Request) *web.Response {
		if _, err := r.Validate[exampleAPIForm](); err != nil {
			return web.Fail(err)
		}
		return web.JSON(map[string]bool{"accepted": true})
	})
}})
defer app.Close()

response := captchaExampleRequest(app, "GET", "/captcha/api/default", "")
var challenge struct {
	Img string `json:"img"`
	Key string `json:"key"`
}
if err := json.Unmarshal(response.Body.Bytes(), &challenge); err != nil {
	panic(err)
}
fmt.Println(strings.HasPrefix(challenge.Img, "data:image/jpeg;base64,"))
rejected := captchaExampleRequest(app, "POST", "/submit",
	fmt.Sprintf(`{"captcha":"wrong","captcha_key":%q}`, challenge.Key))
fmt.Println(rejected.Code)
Output:
true
422

func KeyedWith

func KeyedWith(key string) KeyedRule

KeyedWith returns the keyed rule for an id the handler already has.

func (KeyedRule) Implicit

func (KeyedRule) Implicit() bool

Implicit makes the rule run for a missing or blank value, which fails.

func (KeyedRule) Profile

func (k KeyedRule) Profile(name string) KeyedRule

Profile requires a challenge of the named profile.

func (KeyedRule) Validate

func (k KeyedRule) Validate(ctx context.Context, field validation.Field) error

Validate checks the answer.

type Kind

type Kind challenge.Kind

Kind is the outcome of a check, extending PHP's boolean check result.

const (
	// Passed means the correct answer consumed the challenge.
	Passed Kind = Kind(challenge.Passed)
	// Wrong means an incorrect answer used an attempt.
	Wrong Kind = Kind(challenge.Wrong)
	// Exhausted means the challenge has no attempts left.
	Exhausted Kind = Kind(challenge.Exhausted)
	// Expired means the record was found after its deadline.
	Expired Kind = Kind(challenge.Expired)
	// Missing means no current challenge was found.
	Missing Kind = Kind(challenge.Missing)
	// ProfileMismatch means the keyed challenge belongs to another profile.
	ProfileMismatch Kind = Kind(challenge.ProfileMismatch)
)

func (Kind) String

func (k Kind) String() string

String returns the readable name of a check outcome.

type Profile

type Profile struct {
	// Length is the number of characters, from 1 to 32.
	Length int
	// Width and Height are the image size in pixels: width 1 to 1000,
	// height 16 to 400. Each drawn entry needs at least eight pixels of
	// horizontal space after subtracting TextLeftPadding.
	Width, Height int
	// Quality is the JPEG quality, from 1 to 100. PHP ignores it; we don't.
	Quality int
	// Math draws "x + y = " and expects the sum.
	Math bool
	// Expire is how long a challenge may be answered, or NoDeadline.
	Expire time.Duration
	// Attempts is how many answers a challenge accepts, or Unlimited.
	Attempts int
	// Sensitive keeps the case of answers.
	Sensitive bool
	// Characters, when set, replaces Config.Characters for this profile.
	Characters []string
	// Lines is the number of extra noise lines: PHP draws Lines + 1.
	Lines int
	// LineWidth and LineColor style the noise lines.
	LineWidth int
	LineColor string
	// Angle is the largest rotation of a character, in degrees.
	Angle int
	// Contrast, Sharpen, Blur and Invert are filters, as in PHP.
	Contrast int
	Sharpen  int
	Blur     int
	Invert   bool
	// BgImage draws on a random background; otherwise on BgColor.
	BgImage bool
	BgColor string
	// FontColors, when set, is the palette for characters; otherwise each
	// character gets a random colour.
	FontColors []string
	// Fonts and Backgrounds replace PHP's enumerated asset lists per profile.
	// Nil inherits the corresponding Config list.
	Fonts, Backgrounds []string
	// TextLeftPadding and MarginTop place the characters; MarginTop 0 means
	// Height / Length.
	TextLeftPadding int
	MarginTop       int
}

Profile is one captcha style, like PHP's named arrays in config/captcha.php. Start every profile from Defaults, so a Go zero value never means "unset".

func Defaults

func Defaults() Profile

Defaults returns the PHP class defaults that every profile starts from. Like PHP, a named profile does not inherit from the "default" profile.

type Renderer

type Renderer interface {
	Render(ctx context.Context, profile string, p Profile, text []string) ([]byte, error)
}

Renderer draws a challenge's characters and returns a JPEG, as PHP's ImageManager does. Render is called concurrently within the configured render slots. The context carries the request's deadline.

type SessionRule

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

SessionRule checks the session challenge, PHP's `captcha` rule. Build it in the form's Rules(r *web.Request) method, because a rule's context can't reach the session.

func Rule

func Rule(r *web.Request) SessionRule

Rule returns the session rule for r. It requires the "default" profile unless Profile names another.

Example

ExampleRule shows a session form using PHP's captcha_src and captcha rule.

const form = `<form method="post">
		{{csrfField}}
		<img src="{{captchaSrc "contact"}}" alt="Security code">
		<label>Security code <input name="captcha" required></label>
		<button>Send</button>
	</form>`
app := captchaExampleApp(form, laravel.Routes{Web: func(route *routing.Router, _ *config.Config) {
	route.Get("/contact", func(*web.Request) *web.Response { return web.View("form", nil) })
	route.Post("/contact", func(r *web.Request) *web.Response {
		if _, err := r.Validate[exampleSessionForm](); err != nil {
			return web.Fail(err)
		}
		return web.Text("sent")
	})
}})
defer app.Close()

page := captchaExampleRequest(app, "GET", "/contact", "")
fmt.Println(strings.Contains(page.Body.String(), "/captcha/contact?"))
Output:
true

func (SessionRule) Implicit

func (SessionRule) Implicit() bool

Implicit makes the rule run for a missing or blank value, which fails. PHP's rule passed a missing captcha when `required` was left out.

func (SessionRule) Profile

func (s SessionRule) Profile(name string) SessionRule

Profile requires a challenge of the named profile.

func (SessionRule) Validate

func (s SessionRule) Validate(ctx context.Context, field validation.Field) error

Validate checks the answer.

type Verdict

type Verdict struct {
	Kind Kind
	// Remaining is the attempts left after Wrong, or -1 when unlimited.
	Remaining int
}

Verdict is the committed outcome of a check, extending PHP's boolean result.

Directories

Path Synopsis
Package assets contains the fonts and backgrounds shipped by mews/captcha.
Package assets contains the fonts and backgrounds shipped by mews/captcha.
Package captchatest helps tests answer captchas without reading images.
Package captchatest helps tests answer captchas without reading images.
Package draw implements the mews/captcha image pipeline without Laravel.
Package draw implements the mews/captcha image pipeline without Laravel.
internal
challenge
Package challenge holds captcha challenge records and the rules for checking them.
Package challenge holds captcha challenge records and the rules for checking them.

Jump to

Keyboard shortcuts

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