/captcha-rs:captcha-rsfrom captcha-rs
Integrates self-hosted CAPTCHA protection in Rust projects using the captcha-rs crate. Supports visual text/math puzzles, invisible KDF Proof-of-Work v2 (PBKDF2, SHA, Argon2id, Scrypt), accessible SVG/WAV audio, and interactive Slider/Rotate puzzles. Includes Axum/Actix-web endpoint setup, stateless HMAC/JWT verification, and Redis replay stores.
Ships in captcha-rs. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
captcha-rs Integration GuideUse this skill whenever adding, configuring, or debugging CAPTCHA protection in a Rust codebase with captcha-rs.
Default features (default = ["text", "jpeg", "svg", "token"]) are 100% pure Rust, #![forbid(unsafe_code)], zero C/ring, and WASM-ready.
| Goal | cargo add Command |
|---|---|
| Visual Text / Math + SVG / JPEG + HMAC tokens | cargo add captcha-rs |
| Accessible Visual + 16 kHz PCM WAV Audio | cargo add captcha-rs --features audio |
| Lossless PNG or WebP output | cargo add captcha-rs --features png (or webp) |
| Invisible KDF PoW v2 only (zero graphics crates) | cargo add captcha-rs --no-default-features --features pow |
Memory-hard KDF PoW v2 (Argon2id or Scrypt) | cargo add captcha-rs --no-default-features --features pow-argon2 (or pow-scrypt) |
| Interactive Slider & Rotate puzzles | cargo add captcha-rs --no-default-features --features "puzzle,png" |
| Progressive escalation (PoW v2 + SVG/Audio fallback) | cargo add captcha-rs --features "pow,audio" |
RFC 7519 HS256 JWT tokens (native only; pulls ring) | cargo add captcha-rs --features jwt |
| Everything enabled | cargo add captcha-rs --features full |
Always import the prelude in user code:
use captcha_rs::prelude::*;
All 9 macros (captcha_service!, text_engine!, captcha!, pow_engine!, slider_engine!, rotate_engine!, palette!, filters!, font_pool!) are zero-proc-macro macro_rules! re-exported in captcha_rs::prelude::*.
use captcha_rs::prelude::*;
// Construct ONCE at startup and clone cheaply across Axum State / Actix Data (Arc-backed)
let service = captcha_service! {
engine: text_engine!(Medium, dark_mode: true), // or mode: Math, theme: Dark
secret: std::env::var("CAPTCHA_SECRET").expect("CAPTCHA_SECRET"),
ttl_secs: 300,
replay_capacity: 100_000,
};
// Issue (lazy: < 1 us, zero pixel rasterization until JPEG/PNG/WebP is requested)
let issued = service.issue()?;
let svg_uri = issued.challenge.to_svg_data_uri(); // zero rasterization (~90 us total)
let jpeg_uri = issued.challenge.to_jpeg_data_uri(80)?; // lazily rasterized & cached
// let audio_uri = issued.challenge.to_audio_data_uri(); // feature: audio (same token!)
let token = issued.token();
// Verify once (subsequent uses return Err(VerifyError::Replayed))
service.verify(token, &user_input)?;
feature = "pow")KdfPowEngine defaults to Deterministic PBKDF2/SHA-256 (1 KDF at issue + keySignature HMAC = 0-KDF constant-time verification on the server).
CaptchaService<KdfPowEngine> (DOMAIN = "pow-v2")let pow_svc = captcha_service! {
engine: pow_engine!(Pbkdf2Sha256, cost: 5_000, max_counter: 500),
// Alternatives:
// pow_engine!(Probabilistic, prefix: "00", cost: 5_000) // 0-KDF issue, 1-KDF verify
// pow_engine!(Argon2id, cost: 2, memory_kib: 16_384, max_counter: 30) // feature: pow-argon2
// pow_engine!(Scrypt, cost: 16_384, memory_cost: 8, max_counter: 30) // feature: pow-scrypt
secret: secret,
ttl_secs: 120,
replay_capacity: 100_000,
};
let issued = pow_svc.issue()?;
// Send `{ challenge: issued.challenge, token: issued.token }` to browser.
// On POST, deserialize `solution: KdfSolution` and call:
pow_svc.verify(&token, &solution)?;
use std::time::Duration;
let engine = pow_engine!(Pbkdf2Sha256, cost: 5_000, max_counter: 500);
// GET /pow -> return JSON of `KdfChallenge`
let challenge = engine.issue_signed(&secret, Duration::from_secs(120))?;
// POST /submit -> verify Base64 JSON `{ challenge, solution }` (0 KDFs in deterministic mode)
KdfPowEngine::verify_base64(&secret, &submitted_b64, Duration::ZERO, Some(&replay_store))?;
// Async distributed store:
// KdfPowEngine::verify_base64_async(&secret, &submitted_b64, Duration::ZERO, &redis_store).await?;
feature = "puzzle", plus png or webp)Always set consume_on_attempt: true on low-entropy puzzles so bots cannot probe multiple coordinates/angles against one token, and encode transparent puzzle pieces as ImageFormat::Png or ImageFormat::Webp (never JPEG).
let slider_svc = captcha_service! {
engine: slider_engine!(size: (300, 150), tolerance: 6, decoys: 1, dark_mode: true),
secret: secret.clone(),
consume_on_attempt: true,
replay_capacity: 50_000,
};
let s = slider_svc.issue()?;
let bg = s.challenge.background_data_uri(ImageFormat::Png)?;
let piece = s.challenge.piece_data_uri(ImageFormat::Png)?;
let y = s.challenge.y();
// NEVER send `s.challenge.expected_x()` to the client!
slider_svc.verify(s.token(), submitted_x_i32)?;
let rotate_svc = captcha_service! {
engine: rotate_engine!(size: 180, tolerance_deg: 12, dark_mode: true),
secret: secret,
consume_on_attempt: true,
replay_capacity: 50_000,
};
let r = rotate_svc.issue()?;
let disc = r.challenge.to_data_uri(ImageFormat::Png)?;
// NEVER send `r.challenge.expected_angle_deg()` to the client!
rotate_svc.verify(r.token(), submitted_angle_deg_i32)?;
const BRAND: Palette = palette! {
bg: "#0f172a",
gradient: "#1e293b",
fg: ["#38bdf8", "#a78bfa", "#34d399"],
shadow: "#020617",
};
let engine = text_engine! {
preset: Hard,
size: (220, 75),
palette: BRAND,
mode: Math,
filters: [GhostGrid::new(14), Elastic::default(), Dots::new(25)],
};
VerifyErrorVerifyError | HTTP Status | Action |
|---|---|---|
WrongSolution | 400 Bad Request | Prompt user to retry or refresh |
Expired | 410 Gone / 400 | Issue a fresh challenge |
Replayed | 409 Conflict / 400 | Token already used; issue a fresh challenge |
ReplayStoreError(_) | 503 Service Unavailable | Fail closed (capacity full or Redis/SQL outage) |
InvalidToken, InvalidSignature, DomainMismatch, MalformedPayload | 400 / 401 | Reject tampered or mismatched token |
AsyncReplayStoreImplement AsyncReplayStore::try_consume_async with atomic SET key 1 NX EX <ttl> (returning Ok(true) if inserted, Ok(false) if already present, Err(msg) on Redis failure so outages map to VerifyError::ReplayStoreError instead of Replayed), then verify via:
service.verify_async(&token, &answer, &redis_store).await?;
KdfPowEngine::issue_signed)const hexToBytes = (h) => Uint8Array.from(h.match(/.{2}/g), (b) => parseInt(b, 16));
const bytesToHex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
async function deriveKey({ algorithm, salt, nonce, cost, keyLength }, counter) {
const saltBytes = hexToBytes(salt);
const nonceBytes = hexToBytes(nonce);
const pwd = new Uint8Array(nonceBytes.length + 4);
pwd.set(nonceBytes, 0);
new DataView(pwd.buffer).setUint32(nonceBytes.length, counter, false); // CounterMode::Uint32
if (algorithm.startsWith('PBKDF2/')) {
const hash = algorithm.slice(7);
const key = await crypto.subtle.importKey('raw', pwd, 'PBKDF2', false, ['deriveBits']);
const bits = await crypto.subtle.deriveBits({ name: 'PBKDF2', salt: saltBytes, iterations: cost, hash }, key, keyLength * 8);
return new Uint8Array(bits);
}
const first = new Uint8Array(saltBytes.length + pwd.length);
first.set(saltBytes, 0);
first.set(pwd, saltBytes.length);
let digest = new Uint8Array(await crypto.subtle.digest(algorithm, first));
for (let i = 1; i < cost; i++) digest = new Uint8Array(await crypto.subtle.digest(algorithm, digest));
return digest.slice(0, keyLength);
}
export async function solveKdfChallenge(challenge, maxCounter = 1_000_000) {
const prefix = challenge.parameters.keyPrefix.toLowerCase();
const t0 = performance.now();
for (let counter = 0; counter <= maxCounter; counter++) {
const dkHex = bytesToHex(await deriveKey(challenge.parameters, counter));
if (dkHex.startsWith(prefix)) {
return btoa(JSON.stringify({
challenge,
solution: { counter, derivedKey: dkHex, time: Math.round((performance.now() - t0) * 10) / 10 },
}));
}
}
throw new Error('Solution not found within counter limit');
}
TextChallenge::answer(), SliderChallenge::expected_x(), or RotateChallenge::expected_angle_deg() into API responses.TextEngine, KdfPowEngine, SliderEngine, RotateEngine, and CaptchaService once at startup and .clone() them into request state.replay_capacity / InMemoryReplayStore on single-node servers or pass a distributed AsyncReplayStore (Redis/SQL) to verify_async.consume_on_attempt: true for low-entropy engines: Always enable it for SliderEngine, RotateEngine, and ChallengeMode::Math.fallback_secret or fallback_secrets: [...] (up to 8 keys) when rotating CAPTCHA_SECRET.wasm32-unknown-unknown):
jwt feature (it depends on jsonwebtoken/ring). Use default HmacTokenCodec.issue_at, verify_at, verify_at_async, issue_signed_at, verify_base64_at, verify_base64_at_async) instead of calling SystemTime::now().Hard/Extreme JPEG/PNG rasterization or memory-hard Argon2id/Scrypt derivation in tokio::task::spawn_blocking.CaptchaBuilder, Captcha, as_token, as_tuple, and captcha_rs::verify do not exist in v1+. Always use TextEngine / CaptchaService and the declarative macros.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
captcha, bot-protection, rust-crate, proof-of-work, form-verification
npx claudepluginhub samirdjelal/captcha-rs --plugin captcha-rsOther plugins' skills for the same job