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 ¶
- Constants
- Variables
- func Check(r *web.Request, value string, opts ...CheckOption) (bool, error)
- func CheckKey(ctx context.Context, key, value, profile string) (bool, error)
- func Image(r *web.Request, profile string) *web.Response
- func Img(ctx context.Context, profile string, attrs ...Attr) template.HTML
- func PHPCharacters() []string
- func PHPProfiles() map[string]Profile
- func Src(ctx context.Context, profile string) string
- type Attr
- type Captcha
- func (c *Captcha) CheckKeyed(ctx context.Context, key, value, profile string) (Verdict, error)
- func (c *Captcha) CheckSession(r *web.Request, value string, opts ...CheckOption) (Verdict, error)
- func (c *Captcha) Config() Config
- func (c *Captcha) Issue(ctx context.Context, profile string) (Challenge, error)
- func (c *Captcha) RecordAnswers(record func(key, answer string))
- func (c *Captcha) Register(app *laravel.Registrar) error
- type Challenge
- type CheckOption
- type Config
- type KeyedRule
- type Kind
- type Profile
- type Renderer
- type SessionRule
- type Verdict
Examples ¶
Constants ¶
const DefaultMessage = "The :attribute is incorrect."
DefaultMessage is the rule's message. PHP's was the raw key "validation.captcha".
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.
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 ¶
var ErrContended = challenge.ErrContended
ErrContended means concurrent changes prevented a check from committing. PHP's check has no equivalent error.
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.
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.
var ErrUnknownProfile = errors.New("captcha: unknown profile")
ErrUnknownProfile is returned for a profile that isn't configured.
Functions ¶
func Check ¶
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 Image ¶
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 ¶
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 ¶
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 ¶
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 New ¶
New returns the package. Each configure function changes the settings after the package reads them from the environment.
func (*Captcha) CheckKeyed ¶
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 ¶
CheckSession answers r's session challenge and returns the verdict. When captcha is disabled it returns Missing without using the session.
func (*Captcha) 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 ¶
Issue creates a keyed challenge for profile and draws it. It returns an error when captcha is disabled.
func (*Captcha) RecordAnswers ¶
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.
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 ¶
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
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 ¶
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
type 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) )
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".
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.
Source Files
¶
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. |