# @wrnexus/captcha
A first-class CAPTCHA and anti-automation package for WRNexusJS. It supports self-hosted challenges, a managed WRNexus service, external providers, form submission guards, page gates, accessible audio, adaptive risk checks, and a Tailwind-only `.wrn` component.
## Included challenge modes
- Number, alphabet, and alphanumeric image challenges
- Addition, subtraction, multiplication, and exact-division calculations
- Generated shape-selection image challenges
- Audio alternatives for text, numbers, and calculations
- Honeypot and minimum-completion-time invisible checks
- Self-hosted “I’m not a robot” checkbox challenge with one-time server verification
- Always, once-per-session, and adaptive page gates
- Cloudflare Turnstile, Google reCAPTCHA, hCaptcha, managed, and custom providers
## Create the self-hosted engine
```ts
import {
createCaptchaEngine,
createCaptchaHttpHandlers,
RedisCaptchaStore,
} from "@wrnexus/captcha/server";
const engine = createCaptchaEngine({
secret: process.env.CAPTCHA_SECRET!,
store: new RedisCaptchaStore(redis),
basePath: "/api/captcha",
challengeTtlMs: 2 * 60_000,
responseTokenTtlMs: 5 * 60_000,
maxAttempts: 3,
minCompletionMs: 800,
});
export const handlers = createCaptchaHttpHandlers(engine);
```
Mount the handlers from an API catch-all route:
```ts
import type { Context } from "@wrnexus/core";
import { handlers } from "../../lib/captcha.ts";
export async function POST(ctx: Context) {
return (await handlers.handle(ctx.req, ctx)) ?? new Response("Not Found", { status: 404 });
}
export const GET = POST;
export const HEAD = POST;
```
## Use the component
```wrn
```
The component uses Tailwind utilities and `--wire-*` theme variables. It has no companion component CSS file.
### Main props
`provider`, `siteKey`, `type`, `action`, `presentation`, `difficulty`, `disturbance`, `imageStyle`, `allowedStyles`, `excludedStyles`, `randomizeStyle`, `locale`, `size`, `color`, `class`, `name`, `endpoint`, `verifyEndpoint`, `responseField`, labels/messages, `autoLoad`, `autoVerify`, `showVerify`, `showRefresh`, `showAudio`, `showListen`, `showStatus`, `disabled`, `required`, and the backward-compatible `compact` alias.
### Component sizes
Use one of the three supported display modes:
```wrn
```
`small`/`sm` are accepted as aliases for `compact`, while `large`/`lg` are accepted as aliases for `big`. The old `compact="true"` prop still forces compact mode.
### Listen button visibility
Audio remains available by default. Hide the Listen and Use audio controls with either of these props:
```wrn
```
`showListen` is the direct UI switch. `showAudio` remains the broader backward-compatible audio switch.
### I’m not a robot checkbox
```wrn
```
The checkbox is not a client-only boolean. Clicking it completes a self-hosted invisible challenge that is time-limited, attempt-limited, one-time-use, action-bound, optionally session/hostname/IP-bound, and verified on the server. It is a low-friction anti-automation layer; use adaptive escalation to a visual or external provider for high-risk traffic.
### Visual disturbance
Use `disturbance` for visual and image-selection challenges. It accepts an integer from `25` through `75`:
- `25`: light disturbance and easiest readability
- `50`: balanced default
- `75`: maximum supported dots, line crossings, glyph movement, and image-tile noise
The browser sends this value to the challenge API, and the server validates the range before generating the challenge. It is also returned in challenge metadata.
### Generated image renderer styles
Text, number, alphanumeric, and calculation CAPTCHA images support 18 concrete renderers plus a random mode:
`classic`, `collision`, `snow`, `corrosion`, `spiderweb`, `cross-shadow`, `split`, `split2`, `cut`, `darts`, `distortion`, `stitch`, `striped`, `wave`, `grid-noise`, `scribble`, `pixel`, and `broken-lines`.
Use a fixed style:
```wrn
```
Use a new random style whenever the challenge is refreshed:
```wrn
```
Control the random pool with comma-separated component props or arrays in the TypeScript API:
```wrn
```
```ts
const challenge = await engine.create({
action: "checkout",
type: "alphanumeric",
imageStyle: "random",
allowedStyles: ["classic", "snow", "distortion", "wave"],
excludedStyles: ["collision"],
});
```
Set `randomizeStyle: true` to force random selection even when `imageStyle` names a concrete renderer. The resolved style, requested style, and active pool are returned in challenge metadata. The answer is never embedded in metadata or browser JavaScript.
### Events
`@ready`, `@challenge`, `@input`, `@verify`, `@success`, `@failure`, `@expired`, `@refresh`, `@audioStart`, `@audioEnd`, and `@error`.
## Protect a validated form API
Validate a cloned request first, then consume the CAPTCHA response token. This prevents a valid token from being consumed when ordinary field validation fails.
```ts
import { captchaGuard } from "@wrnexus/captcha/server";
import { parseBody } from "@wrnexus/validation";
import contactSchema from "../schemas/contact.ts";
import { engine } from "../lib/captcha.ts";
const guard = captchaGuard({
action: "contact-submit",
engine,
bindHostname: true,
bindSession: true,
});
export async function POST(ctx) {
const validation = await parseBody(contactSchema, ctx.req.clone());
if (!validation.ok) return validation.response;
return guard(ctx, async () =>
Response.json({ ok: true, submission: validation.value }),
);
}
```
The CAPTCHA runtime binds its required-form check in the capture phase, so a `data-schema` validator cannot submit the form before CAPTCHA verification. After a successful form request, the component automatically creates a fresh challenge.
## Validate a schema and CAPTCHA together
```ts
const result = await parseWithCaptcha(signupSchema, body, ctx, {
action: "signup",
engine,
});
if (!result.ok) return Response.json({ ok: false, errors: result.errors }, { status: 400 });
```
## Page gate
```ts
export default captchaPageGate({
action: "reports-access",
engine,
challengePath: "/captcha",
policy: {
mode: "session",
verifiedForMs: 15 * 60_000,
routeGroups: ["/reports"],
},
});
```
Use `mode: "always"` for every visit, `mode: "session"` for a temporary grant, or `mode: "adaptive"` with `signals(ctx)`.
The challenge page should post the return path as a normal hidden field instead of constructing JavaScript inside the HTML `action` attribute:
```wrn
```
The `/api/page-grant` route reads `returnTo`, restricts it to the current origin, and redirects only after `captchaPageGate()` has verified and stored the temporary session grant.
## External providers
```ts
const turnstile = turnstileProvider({
secretKey: process.env.TURNSTILE_SECRET!,
siteKey: process.env.PUBLIC_TURNSTILE_SITE_KEY!,
expectedHostnames: ["example.com"],
expectedAction: "signup",
});
```
```wrn
```
Use the matching provider in `captchaGuard({ provider: turnstile })`. reCAPTCHA and hCaptcha adapters follow the same pattern.
## Managed provider
```ts
const managed = managedCaptchaProvider({
baseUrl: "https://captcha.example.com",
siteKey: process.env.PUBLIC_CAPTCHA_SITE_KEY!,
secretKey: process.env.CAPTCHA_SECRET_KEY!,
});
```
For direct browser challenge creation, configure the component’s `endpoint` as the managed `/v1/challenges` URL and its `verifyEndpoint` as `/v1/solve`. Keep the secret key only in the server provider.
## Stores
- `MemoryCaptchaStore`: development and one-process applications
- `SqliteCaptchaStore`: adapter for SQLite-like `prepare().run/get/all()` clients
- `RedisCaptchaStore`: shared TTL storage with Lua-backed atomic consumption when `eval` is available
- `CaptchaStore`: implement this interface for PostgreSQL, MySQL, MongoDB, or another backend
## Audio
`AssetAudioRenderer` concatenates bundled English PCM WAV clips without calling an external service. Supply a custom `CaptchaAudioRenderer` for recorded voices, Hindi or other languages, or managed text-to-speech.
## DevToolbar
Register `captchaPlugin()` in the WRNexusJS config. The audit panel checks for likely client-side secrets, missing action bindings, missing provider site keys, optional CAPTCHA fields, accessible alternatives, and server-verification reminders.
## Testing
Use deterministic custom generators in unit tests. Never require users or CI to solve random CAPTCHA images. The package includes engine, provider, policy, HTTP, storage, replay, expiry, binding, and audio authorization tests.
## Custom challenge generator
```ts
import { defineCaptchaGenerator, createCaptchaEngine } from "@wrnexus/captcha";
const wordChallenge = defineCaptchaGenerator({
type: "word" as const,
generate(context) {
const answer = "NEXUS";
return {
type: "word",
presentation: "visual",
prompt: "Enter the displayed word",
answer,
answerKind: "text",
image: renderYourImage(answer),
inputMode: "text",
};
},
});
const engine = createCaptchaEngine({ secret, generators: [wordChallenge] });
```
Applications may also implement `CaptchaStore`, `CaptchaAudioRenderer`, or use `defineCaptchaProvider()` for a completely custom service.