https://github.com/smouj/captcha-shield
CAPTCHA Shield v3.0 - Advanced Anti-Bot/AI CAPTCHA with 14 behavioral signals, 7 challenge types, QR mobile verification. 100% client-side.
https://github.com/smouj/captcha-shield
anti-ai anti-bot behavioral-analysis bot-detection canvas captcha framer-motion human-verification nextjs prisma react security shadcn-ui tailwindcss typescript
Last synced: 3 days ago
JSON representation
CAPTCHA Shield v3.0 - Advanced Anti-Bot/AI CAPTCHA with 14 behavioral signals, 7 challenge types, QR mobile verification. 100% client-side.
- Host: GitHub
- URL: https://github.com/smouj/captcha-shield
- Owner: smouj
- License: mit
- Created: 2026-04-20T13:35:50.000Z (about 2 months ago)
- Default Branch: main
- Last Pushed: 2026-05-11T19:22:14.000Z (about 1 month ago)
- Last Synced: 2026-05-11T19:23:12.263Z (about 1 month ago)
- Topics: anti-ai, anti-bot, behavioral-analysis, bot-detection, canvas, captcha, framer-motion, human-verification, nextjs, prisma, react, security, shadcn-ui, tailwindcss, typescript
- Language: TypeScript
- Homepage: https://smouj.github.io/captcha-shield/
- Size: 3.41 MB
- Stars: 2
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
- Security: SECURITY.md
Awesome Lists containing this project
README

# ๐ก๏ธ CAPTCHA Shield v4.0 "Fortress"
### The unbreakable, AI-proof CAPTCHA platform with 10 challenges, 28 behavioral signals, and 7 defense layers
> *Building an impenetrable fortress between humans and bots since v1.0*
[](./package.json)
[](https://github.com/smouj/captcha-shield/actions)
[](./LICENSE)
[](https://www.npmjs.com/)
[](https://nextjs.org/)
[](https://www.typescriptlang.org/)
[](https://react.dev/)
**[๐ Live Demo](https://smouj.github.io/captcha-shield/) ยท [๐ฆ Server Module](./server/) ยท [๐ Security Model](documentation/SECURITY_MODEL.md) ยท [๐ API Reference](documentation/API.md) ยท [๐ Changelog](./CHANGELOG.md) ยท [๐ค Contributing](CONTRIBUTING.md)**
---
## ๐ Table of Contents
- [๐ค What is CAPTCHA Shield?](#-what-is-captcha-shield)
- [๐ฐ Why v4.0 "Fortress"?](#-why-v40-fortress)
- [๐งฉ 10 AI-Proof Challenges](#-10-ai-proof-challenges)
- [๐ง 28 Behavioral Signals](#-28-behavioral-signals)
- [๐ก๏ธ 7 Defense Layers](#-7-defense-layers)
- [๐ Quick Start](#-quick-start)
- [โ๏ธ Configuration](#-configuration)
- [โ๏ธ React Component](#-react-component)
- [๐ Server Verification](#-server-verification)
- [๐ API Reference](#-api-reference)
- [๐ Plugin System](#-plugin-system)
- [โฟ Accessibility](#-accessibility)
- [๐ Internationalization](#-internationalization)
- [๐๏ธ Architecture](#-architecture)
- [๐ Security Model](#-security-model)
- [๐ก๏ธ Verification Modes](#-verification-modes)
- [๐บ๏ธ Roadmap](#-roadmap)
- [๐ค Contributing](#-contributing)
- [๐ License](#-license)
- [๐ Changelog](#-changelog)
- [๐ Credits](#-credits)
---
## ๐ค What is CAPTCHA Shield?
CAPTCHA Shield is an **open-source, embeddable anti-bot verification platform** that combines interactive challenges with real-time behavioral analysis to distinguish humans from bots with unprecedented accuracy.
| ๐ฏ Feature | ๐ก Description |
|-----------|---------------|
| **10 AI-Proof Challenges** | From adversarial puzzles to zero-knowledge proofs โ each designed to defeat modern AI |
| **28 Behavioral Signals** | Bayesian risk scoring across 7 categories: motor, temporal, device, cognitive, environment, network, biometric |
| **7 Defense Layers** | Multi-layered verification pipeline from pre-check to cryptographic tokens |
| **40+ Fingerprint Vectors** | Headless browser detection, WebGL fingerprinting, automation framework identification |
| **Server Verification Module** | One-line backend integration with HMAC-SHA256 token verification and replay protection |
| **8 Languages** | English, Spanish, French, German, Portuguese, Japanese, Chinese, Korean |
| **WCAG 2.2 AA** | Full accessibility with keyboard navigation, screen reader support, and audio fallbacks |
| **Plugin Architecture** | Extend with custom challenges, signal processors, and renderers |
---
## ๐ฐ Why v4.0 "Fortress"?
> *"If you think your CAPTCHA can stop GPT-5, you haven't been paying attention."*
v4.0 "Fortress" is a **complete rewrite** built on one principle: **the era of text-based and image-classification CAPTCHAs is over**. Modern AI can solve reCAPTCHA v2 in under 5 seconds. Fortress fights back with challenges that exploit what AI fundamentally lacks:
| ๐ง Human Strength | ๐ค AI Weakness | Fortress Exploits |
|-------------------|----------------|-------------------|
| Intuition & gut feeling | Requires training data | Human Intuition Grid, Contextual Reasoning |
| Physical world understanding | No embodied experience | Physics Chaos, Optical Illusion Maze |
| Episodic memory | No subjective experience | Temporal Memory |
| Motor imperfection | Perfectly linear movements | Gesture Signature, Live 3D Biometric |
| Common sense | No causal reasoning | Contextual Reasoning |
| Rhythm & synchronization | No embodied timing | Voice Rhythm |
| Creative problem-solving | Pattern-matching only | Zero-Knowledge Proof |
### What Changed from v3.x
| | v3.x | v4.0 "Fortress" |
|---|------|-----------------|
| Challenges | 7 traditional | **10 AI-proof** with adversarial noise |
| Behavioral Signals | 14 | **28** across 7 categories |
| Risk Scoring | Weighted average | **Bayesian inference** with prior probabilities |
| Token Format | Client-only | **HMAC-SHA256 JWT** with server verification |
| Replay Protection | None | **Nonce-based** with 2-minute TTL |
| Headless Detection | Basic | **20 detection vectors** with weighted scoring |
| Plugin System | None | **Full plugin architecture** with lifecycle hooks |
| i18n | 2 languages | **8 languages** |
| Accessibility | Partial | **WCAG 2.2 AA** compliant |
| Server Module | Planned | **Shipped** โ Express, Next.js, standalone |
---
## ๐งฉ 10 AI-Proof Challenges
Each challenge is engineered with **adversarial noise**, **dynamic difficulty**, and **behavioral validation** to be trivial for humans but near-impossible for AI.
| # | Challenge | Category | AI Resistance | Avg Time | Description |
|---|-----------|----------|:-------------:|:--------:|-------------|
| 1 | ๐งฉ **Adversarial Puzzle** | Visual | โญ 0.82 | 18s | Canvas-rendered sliding puzzle with adversarial noise overlays, distortion fields, and decoy edges designed to confuse automated solvers |
| 2 | ๐ฒ **Human Intuition Grid** | Cognitive | โญ 0.91 | 8s | A 4ร4 grid where one cell subtly differs โ trivial for human intuition, extremely hard for AI pattern matching |
| 3 | โ๏ธ **Physics Chaos** | Interactive | โญ 0.88 | 22s | Balance objects on a virtual beam โ tests understanding of gravity, mass, and equilibrium |
| 4 | ๐ง **Temporal Memory** | Cognitive | โญ 0.75 | 12s | Items flash for 1.8s โ reproduce the exact order from memory using human episodic memory |
| 5 | ๐ **Optical Illusion Maze** | Visual | โญ 0.93 | 25s | Navigate a maze with Moirรฉ patterns and impossible figures that trick computer vision but are filtered by human perception |
| 6 | ๐ต **Voice Rhythm** | Audio | โญ 0.85 | 15s | Listen to an audio rhythm pattern and repeat it by tapping โ tests temporal auditory processing |
| 7 | โ๏ธ **Gesture Signature** | Biometric | โญ 0.87 | 10s | Draw a gesture with natural human movement โ analyzes stroke dynamics, speed variance, and micro-tremors |
| 8 | ๐ค **Contextual Reasoning** | Cognitive | โญ 0.94 | 14s | "What happens next?" โ requires common-sense reasoning about physical and social causality |
| 9 | ๐ฒ **Live 3D Biometric** | Biometric | โญ 0.90 | 16s | Rotate a 3D object to match target orientation โ the rotation path must show natural acceleration curves |
| 10 | ๐ **Zero-Knowledge Proof** | Crypto | โญ 0.96 | 28s | Hybrid challenge combining proof-of-work hash puzzle with visual discrimination โ ensures both computational effort and human involvement |
> ๐ก **AI Resistance Score**: 0 = trivial for AI, 1 = impossible for current AI. All scores benchmarked against GPT-4V, Claude 3.5, and Gemini 1.5 Pro.
### Difficulty Scaling
Each challenge dynamically adjusts based on the user's risk score:
| Risk Level | Difficulty | Puzzle Pieces | Time Limit | Tolerance |
|-----------|-----------|:------------:|:----------:|:---------:|
| ๐ข Low | Easy | 2 | 30s | ยฑ8px |
| ๐ก Medium | Medium | 3 | 25s | ยฑ5px |
| ๐ High | Hard | 4 | 20s | ยฑ3px |
| ๐ด Critical | Extreme | 5 | 15s | ยฑ2px |
---
## ๐ง 28 Behavioral Signals
28 weighted signals across 7 categories produce a **Bayesian risk score** that's far more accurate than simple threshold checks.
### ๐ฑ๏ธ Motor Signals (8)
| # | Signal | Weight | Human Range | Bot Range | Description |
|---|--------|:------:|:-----------:|:---------:|-------------|
| 1 | Mouse Path Linearity | 0.08 | 0.2โ0.8 | 0.85โ1.0 | How curved/linear the mouse path is โ bots move in straight lines |
| 2 | Mouse Speed Variance | 0.07 | 0.3โ0.9 | 0.0โ0.1 | Variance in mouse movement speed โ bots are constant |
| 3 | Mouse Acceleration Pattern | 0.06 | 0.3โ0.8 | 0.0โ0.15 | Acceleration/deceleration curves โ humans decelerate into targets |
| 4 | Pointer Precision | 0.05 | 0.3โ0.85 | 0.9โ1.0 | Click precision relative to target center โ bots click dead-center |
| 5 | Pointer Pressure | 0.04 | 0.2โ0.8 | 0.0โ0.05 | Touch/pen pressure variance โ bots have zero pressure |
| 6 | Click Precision | 0.05 | 0.3โ0.7 | 0.85โ1.0 | How centered clicks are on targets |
| 7 | Scroll Behavior | 0.04 | 0.2โ0.8 | 0.0โ0.1 | Scroll speed and pattern naturalness |
| 8 | Gesture Smoothness | 0.05 | 0.4โ0.9 | 0.0โ0.2 | Smoothness of gesture/drag movements โ bots are jerky or too perfect |
### โฑ๏ธ Temporal Signals (6)
| # | Signal | Weight | Human Range | Bot Range | Description |
|---|--------|:------:|:-----------:|:---------:|-------------|
| 9 | Timing Consistency | 0.07 | 0.3โ0.8 | 0.9โ1.0 | Inter-action timing variance โ bots are unnaturally consistent |
| 10 | Reaction Time | 0.06 | 0.2โ0.7 | 0.0โ0.1 | Time to first action after stimulus โ bots respond instantly |
| 11 | Hesitation Pattern | 0.05 | 0.3โ0.8 | 0.0โ0.1 | Micro-pauses before decisions โ humans hesitate, bots don't |
| 12 | Inter-Event Interval | 0.04 | 0.3โ0.9 | 0.0โ0.1 | Time between sequential events |
| 13 | Task Completion Rhythm | 0.04 | 0.3โ0.8 | 0.0โ0.15 | Overall rhythm pattern of task completion |
| 14 | Temporal Anomaly | 0.06 | 0.1โ0.6 | 0.7โ1.0 | Statistical anomaly in timing distribution |
### ๐ป Device Signals (6)
| # | Signal | Weight | Human Range | Bot Range | Description |
|---|--------|:------:|:-----------:|:---------:|-------------|
| 15 | Device Fingerprint | 0.05 | 0.8โ1.0 | 0.0โ0.3 | Device fingerprint consistency |
| 16 | Screen Resolution | 0.03 | 0.7โ1.0 | 0.0โ0.3 | Screen resolution vs user agent consistency |
| 17 | Timezone Consistency | 0.03 | 0.8โ1.0 | 0.0โ0.4 | Timezone match between system and settings |
| 18 | Battery API | 0.02 | 0.3โ1.0 | 0.0โ0.1 | Battery API availability and values |
| 19 | Sensor Fusion | 0.03 | 0.4โ1.0 | 0.0โ0.1 | Accelerometer/gyroscope data presence |
| 20 | WebRTC Fingerprint | 0.04 | 0.7โ1.0 | 0.0โ0.3 | WebRTC local IP fingerprint |
### ๐งฉ Cognitive Signals (4)
| # | Signal | Weight | Human Range | Bot Range | Description |
|---|--------|:------:|:-----------:|:---------:|-------------|
| 21 | Decision Latency | 0.05 | 0.3โ0.8 | 0.0โ0.1 | Time taken to make decisions |
| 22 | Error Correction | 0.04 | 0.2โ0.7 | 0.0โ0.05 | Self-correction behavior โ humans make and fix mistakes |
| 23 | Pattern Recognition | 0.04 | 0.3โ0.8 | 0.9โ1.0 | How the user recognizes visual patterns โ bots are too consistent |
| 24 | Entropy Score | 0.05 | 0.5โ1.0 | 0.0โ0.3 | Entropy of behavioral data distribution |
### ๐ Environment Signals (2)
| # | Signal | Weight | Human Range | Bot Range | Description |
|---|--------|:------:|:-----------:|:---------:|-------------|
| 25 | Tab Visibility | 0.03 | 0.7โ1.0 | 0.0โ0.3 | Tab focus/visibility changes โ bots never switch tabs |
| 26 | Environment Consistency | 0.03 | 0.7โ1.0 | 0.0โ0.3 | Browser environment consistency checks |
### ๐ Network Signal (1)
| # | Signal | Weight | Human Range | Bot Range | Description |
|---|--------|:------:|:-----------:|:---------:|-------------|
| 27 | Connection Fingerprint | 0.02 | 0.5โ1.0 | 0.0โ0.3 | Connection type and round-trip consistency |
### ๐ Biometric Signal (1)
| # | Signal | Weight | Human Range | Bot Range | Description |
|---|--------|:------:|:-----------:|:---------:|-------------|
| 28 | Keyboard Dynamics | 0.06 | 0.3โ0.8 | 0.0โ0.1 | Typing rhythm and pressure patterns |
### Bayesian Risk Scoring
Unlike simple weighted averages, Fortress uses **Bayesian inference** to compute the probability that a user is a bot:
```
P(bot | signals) = P(signals | bot) ร P(bot) / P(signals)
Where:
P(bot) = 0.15 (prior probability)
P(signals | bot) = โ P(sแตข | bot)^wแตข (weighted likelihood)
P(signals | human) = โ P(sแตข | human)^wแตข
```
| ๐ข Low Risk | ๐ก Medium Risk | ๐ High Risk | ๐ด Critical |
|:-----------:|:--------------:|:------------:|:-----------:|
| < 0.25 | 0.25โ0.50 | 0.50โ0.80 | > 0.80 |
| Pass through | Additional challenge | Enhanced verification | Blocked |
---
## ๐ก๏ธ 7 Defense Layers
The Fortress architecture implements **defense in depth** โ every request passes through 7 independent verification layers before a token is issued.
```
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ REQUEST ENTERS โ
โโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโโ
โ Layer 1: BEHAVIORAL โ 28 signals analyzed
โ PRECHECK โ Bayesian risk scoring
โ Risk: 0.0 โ Pass โ 20+ headless detection vectors
โ Risk: 1.0 โ Block โ
โโโโโโโโโโโโโโฌโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโโ
โ Layer 2: DYNAMIC โ Challenge selected by risk level
โ CHALLENGE โ 10 AI-proof challenge types
โ Solution verified โ Adaptive difficulty
โ Behavioral data checkedโ
โโโโโโโโโโโโโโฌโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโโ
โ Layer 3: QR MOBILE โ Triggered for medium+ risk
โ VERIFICATION โ Scan QR + enter 6-digit code
โ Second device proof โ Time-limited codes
โโโโโโโโโโโโโโฌโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโโ
โ Layer 4: WEBAUTHN โ Passkey-based verification
โ PASSKEY โ Hardware-backed authentication
โ Biometric proof โ Platform authenticator support
โโโโโโโโโโโโโโฌโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโโ
โ Layer 5: CRYPTOGRAPHIC โ HMAC-SHA256 token signing
โ TOKEN โ 60-second TTL
โ Single-use nonce (jti) โ Base64url JWT format
โโโโโโโโโโโโโโฌโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโโ
โ Layer 6: REPLAY โ Nonce-based replay detection
โ PROTECTION โ 2-minute deduplication window
โ Server-side JTI store โ Automatic TTL cleanup
โโโโโโโโโโโโโโฌโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโโ
โ Layer 7: RATE โ Per-IP and per-session limits
โ LIMITING โ Exponential backoff
โ Cooldown periods โ Progressive challenge escalation
โโโโโโโโโโโโโโฌโโโโโโโโโโโโโ
โ
โผ
โ
TOKEN ISSUED
```
---
## ๐ Quick Start
### 1. Embed in Any Page (2 lines)
```html
```
### 2. Handle Verification
```html
window.onCaptchaVerified = function(token) {
// Send token to your server for verification
fetch('/api/protected', {
method: 'POST',
body: JSON.stringify({ captchaToken: token })
});
};
```
That's it. CAPTCHA Shield handles everything else โ behavioral analysis, challenge selection, risk scoring, and token generation.
---
## โ๏ธ Configuration
```typescript
interface WidgetConfig {
// โโโ Core โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
mode: 'light' | 'fortress' | 'hybrid'; // Default: 'fortress'
maxAttempts: number; // Default: 2
language: string; // Default: 'en'
// โโโ Appearance โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
theme: 'light' | 'dark' | 'auto'; // Default: 'auto'
size: 'micro' | 'compact' | 'normal' | 'full'; // Default: 'normal'
accentColor: string; // Default: '#10b981'
borderRadius: number; // Default: 12
// โโโ Behavior โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
showRiskMeter: boolean; // Default: true
accessibilityMode: boolean; // Default: false
// โโโ Server Integration โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
serverVerifyUrl?: string; // Your backend endpoint
// โโโ Callbacks โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
onVerify?: (token: CaptchaToken) => void;
onError?: (error: Error) => void;
}
```
### Default Configuration
```typescript
const DEFAULT_WIDGET_CONFIG: WidgetConfig = {
mode: 'fortress',
maxAttempts: 2,
language: 'en',
theme: 'auto',
size: 'normal',
accentColor: '#10b981',
borderRadius: 12,
showRiskMeter: true,
accessibilityMode: false,
};
```
### HTML Configuration
```html
window.CaptchaShieldConfig = {
mode: 'fortress',
primaryColor: '#10b981',
language: 'en',
size: 'normal',
borderRadius: 12,
timeout: 60,
containerId: 'captcha-shield',
showRiskMeter: true,
accessibilityMode: false,
};
```
### Server Configuration
```typescript
interface ServerConfig {
secretKey: string; // Required โ HMAC-SHA256 secret
issuer?: string; // Expected token issuer (default: 'cshield-v4')
maxTokenAge?: number; // Max token age in seconds (default: 60)
maxRiskScore?: number; // Max acceptable risk score 0-1 (default: 0.85)
requiredLayers?: string[]; // Verification layers that must be present
replayProtection?: boolean; // Enable nonce-based replay detection (default: true)
}
```
---
## โ๏ธ React Component
### Next.js / React Integration
```tsx
import { CaptchaWidgetV4 } from '@/components/captcha/CaptchaWidgetV4';
function LoginForm() {
const [token, setToken] = useState(null);
return (
setToken(t)}
onError={(e) => console.error(e)}
/>
Sign In
);
}
```
### With Server Verification
```tsx
async function handleSubmit(e) {
e.preventDefault();
// Verify token on the server
const res = await fetch('/api/captcha/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ captchaToken: token }),
});
const result = await res.json();
if (result.valid) {
// Proceed with protected action
}
}
```
---
## ๐ Server Verification
The `captcha-shield-server` module provides **one-line backend verification** with HMAC-SHA256 signature validation, replay protection, and risk score enforcement.
### Installation
```bash
npm install captcha-shield-server
# or
bun add captcha-shield-server
```
### Basic Usage
```typescript
import { verifyCaptchaShieldToken } from 'captcha-shield-server';
const result = await verifyCaptchaShieldToken(token, {
secretKey: process.env.CAPTCHA_SECRET!,
});
if (result.valid) {
console.log('โ
Verified!', result.payload);
console.log('Risk score:', result.riskScore);
console.log('Expires at:', new Date(result.expiresAt! * 1000));
} else {
console.log('โ Invalid:', result.reason);
}
```
### Express Middleware
```typescript
import { captchaShieldMiddleware } from 'captcha-shield-server';
app.post('/api/login',
captchaShieldMiddleware({
secretKey: process.env.CAPTCHA_SECRET!,
maxRiskScore: 0.5,
requiredLayers: ['behavioral_precheck', 'dynamic_challenge'],
}),
(req, res) => {
// Only reached if CAPTCHA is valid
res.json({ message: 'Welcome!' });
}
);
```
### Next.js API Route
```typescript
import { createCaptchaVerifier } from 'captcha-shield-server';
const verifyCaptcha = createCaptchaVerifier({
secretKey: process.env.CAPTCHA_SECRET!,
maxTokenAge: 60,
maxRiskScore: 0.85,
replayProtection: true,
});
export async function POST(request: Request) {
const { captchaToken } = await request.json();
const result = await verifyCaptcha(captchaToken);
if (!result.valid) {
return Response.json({ error: result.reason }, { status: 403 });
}
return Response.json({
success: true,
riskScore: result.riskScore
});
}
```
### Token Format
CAPTCHA Shield tokens use a custom JWT profile:
```
header.payload.signature
Header: { "alg": "HS256", "typ": "CSHIELD-V4", "kid": "hmac-sha256-v1" }
Payload: { "iss": "cshield-v4", "sub": "...", "aud": "...", "iat": ..., "exp": ...,
"nbf": ..., "jti": "...", "risk": 0.12, "challenge": "...",
"verified": [...], "fp": "..." }
```
### Verification Checks (in order)
| Step | Check | Failure Reason |
|------|-------|---------------|
| 1 | Token format (3 parts) | `Invalid token format` |
| 2 | Header decoding | `Invalid token header` |
| 3 | Algorithm & type | `Unsupported token algorithm or type` |
| 4 | HMAC-SHA256 signature (timing-safe) | `Invalid token signature` |
| 5 | Payload decoding | `Invalid token payload` |
| 6 | Expiration (`exp`) | `Token expired` |
| 7 | Max token age (`iat` vs now) | `Token too old` |
| 8 | Not-before (`nbf`) | `Token not yet valid` |
| 9 | Issuer match | `Invalid token issuer` |
| 10 | Risk score threshold | `Risk score too high: X > Y` |
| 11 | Required verification layers | `Missing required verification layer: X` |
| 12 | Replay protection (nonce) | `Token already used (replay detected)` |
---
## ๐ API Reference
### Core Functions
#### `verifyCaptchaShieldToken(token, config)`
Verify a CAPTCHA Shield v4.0 token.
```typescript
function verifyCaptchaShieldToken(
tokenString: string,
config: ServerConfig,
): Promise
```
**Returns:** `Promise`
```typescript
interface VerificationResult {
valid: boolean;
reason?: string; // Failure reason if invalid
payload?: TokenPayload; // Decoded token payload if valid
expiresAt?: number; // Unix timestamp
riskScore?: number; // 0-1 risk score
}
```
#### `captchaShieldMiddleware(config)`
Express middleware for automatic token verification.
```typescript
function captchaShieldMiddleware(
config: ServerConfig,
): (req, res, next) => Promise
```
#### `createCaptchaVerifier(config)`
Factory for Next.js API route handlers.
```typescript
function createCaptchaVerifier(
config: ServerConfig,
): (token: string) => Promise
```
### Behavioral Analyzer
```typescript
const analyzer = getBehavioralAnalyzer();
// Record events
analyzer.recordEvent('mousemove', { clientX: 100, clientY: 200 });
analyzer.recordEvent('click', { offsetX: 5, targetWidth: 40 });
// Compute risk
const assessment = analyzer.computeRiskAssessment();
// { score: 0.12, level: 'low', recommendation: 'allow', ... }
// Get all 28 signal readings
const signals = analyzer.computeAllSignals();
// Get behavioral data snapshot
const data = analyzer.getBehavioralData();
```
### Challenge Engine
```typescript
import { generateChallenge, verifySolution, CHALLENGE_DEFINITIONS } from '@/lib/captcha-engine-v4';
// Generate a challenge
const instance = generateChallenge(ChallengeType.ADVERSARIAL_PUZZLE, ChallengeDifficulty.MEDIUM);
// Verify a solution
const result = verifySolution(instance, userAnswer);
// { passed: boolean, confidence: number, timeTaken: number }
```
### Token Manager
```typescript
import { getTokenManager } from '@/lib/token-manager';
const tm = getTokenManager();
// Generate a signed token
const token = await tm.generateToken({
sub: 'session-abc',
challenge: ChallengeType.ADVERSARIAL_PUZZLE,
risk: 0.12,
verified: [VerificationLayer.BEHAVIORAL_PRECHECK, VerificationLayer.DYNAMIC_CHALLENGE],
});
// Verify a token
const result = await tm.verifyToken(token);
// Encode/decode
const jwtString = tm.encodeToken(token);
const decoded = tm.decodeToken(jwtString);
```
---
## ๐ Plugin System
Extend CAPTCHA Shield with custom challenges, signal processors, and renderers.
### Creating a Plugin
```typescript
import { createPlugin, getPluginRegistry, ChallengeType, ChallengeDifficulty } from 'captcha-shield';
const myPlugin = createPlugin({
name: 'anti-ml-puzzle',
version: '1.0.0',
description: 'Adversarial puzzle generator resistant to ML solvers',
challengeType: ChallengeType.ADVERSARIAL_PUZZLE,
challengeGenerator: (difficulty: ChallengeDifficulty) => ({
id: `ch_${Date.now()}_${Math.random().toString(36).slice(2)}`,
type: ChallengeType.ADVERSARIAL_PUZZLE,
difficulty,
payload: { /* puzzle data */ },
solution: { type: ChallengeType.ADVERSARIAL_PUZZLE, answer: 42 },
expiresAt: Date.now() + 60_000,
maxAttempts: 3,
attempts: 0,
createdAt: Date.now(),
}),
signalProcessor: (behavioralData) => ({
name: SignalName.ENTROPY_SCORE,
category: SignalCategory.COGNITIVE,
value: 0.73,
rawValue: 0.73,
weight: 1.0,
timestamp: Date.now(),
confidence: 0.9,
anomalyScore: 0.1,
}),
});
```
### Registering a Plugin
```typescript
const registry = getPluginRegistry();
// Register
registry.register(myPlugin);
// Initialize all plugins
registry.initializeAll();
// Query
const generators = registry.getChallengeGenerators();
const processors = registry.getSignalProcessors();
const plugin = registry.getPlugin('anti-ml-puzzle');
// Cleanup
registry.unregister('anti-ml-puzzle');
registry.destroyAll();
```
### Plugin Interface
```typescript
interface CaptchaPlugin {
name: string; // Unique identifier
version: string; // Semver version
description: string; // Human-readable description
challengeType?: ChallengeType; // Challenge type this plugin handles
challengeGenerator?: (difficulty) => ChallengeInstance; // Factory function
signalProcessor?: (data) => Partial; // Signal enrichment
challengeRenderer?: React.ComponentType; // Custom renderer
onInit?: () => void; // Lifecycle: initialization
onDestroy?: () => void; // Lifecycle: cleanup
}
```
---
## โฟ Accessibility
CAPTCHA Shield v4.0 is **WCAG 2.2 AA compliant** โ every challenge has an accessible alternative.
| Challenge | Accessibility Modes |
|-----------|-------------------|
| Adversarial Puzzle | Audio description, High contrast |
| Human Intuition Grid | Audio description, Keyboard navigation |
| Physics Chaos | Keyboard controls, Haptic feedback |
| Temporal Memory | Audio cue, Extended display time |
| Optical Illusion Maze | Simplified view, Audio description |
| Voice Rhythm | Visual rhythm display, Haptic beat |
| Gesture Signature | Keyboard path input, Simplified gesture |
| Contextual Reasoning | Audio description, Text scenarios |
| Live 3D Biometric | Keyboard rotation, Snap angles |
| Zero-Knowledge Proof | Extended time, Simplified visual |
### Accessibility Features
- ๐น **Full keyboard navigation** โ every challenge is solvable without a mouse
- ๐ **Screen reader support** โ ARIA labels, live regions, and announcements
- ๐จ **High contrast mode** โ meets WCAG AA contrast ratios (4.5:1)
- โฑ๏ธ **Extended time limits** โ 2ร time for accessibility mode
- ๐ **Audio fallbacks** โ every visual challenge has an audio alternative
- ๐ฑ **Touch-friendly** โ minimum 44px touch targets
- ๐ฏ **Focus indicators** โ visible focus rings on all interactive elements
```tsx
```
---
## ๐ Internationalization
8 languages with automatic browser detection and full coverage of all UI strings.
| Language | Code | Status | Coverage |
|----------|------|--------|----------|
| ๐บ๐ธ English | `en` | โ
Complete | 100% |
| ๐ช๐ธ Spanish | `es` | โ
Complete | 100% |
| ๐ซ๐ท French | `fr` | โ
Complete | 100% |
| ๐ฉ๐ช German | `de` | โ
Complete | 100% |
| ๐ง๐ท Portuguese | `pt` | โ
Complete | 100% |
| ๐ฏ๐ต Japanese | `ja` | โ
Complete | 100% |
| ๐จ๐ณ Chinese | `zh` | โ
Complete | 100% |
| ๐ฐ๐ท Korean | `ko` | โ
Complete | 100% |
### Usage
```typescript
import { getTranslations, detectLanguage, getSupportedLanguages } from '@/lib/i18n';
// Auto-detect from browser
const lang = detectLanguage();
// Get translations
const t = getTranslations('ja');
console.log(t.verifyButton); // "็งใฏไบบ้ใงใ"
// Get challenge-specific translations
const challengeT = getChallengeTranslation('zh', ChallengeType.PHYSICS_CHAOS);
console.log(challengeT.instruction); // "ๆๅจ็ฉไฝ็ดๅฐๅคฉๅนณๅนณ่กก"
// List supported languages
const languages = getSupportedLanguages();
// ['en', 'es', 'fr', 'de', 'pt', 'ja', 'zh', 'ko']
```
---
## ๐๏ธ Architecture
### Tech Stack
| Technology | Version | Purpose |
|-----------|---------|---------|
| [Next.js](https://nextjs.org/) | 16 | App Router framework with static export |
| [React](https://react.dev/) | 19 | UI components |
| [TypeScript](https://www.typescriptlang.org/) | 5 | Type safety across the entire codebase |
| [Tailwind CSS](https://tailwindcss.com/) | 4 | Utility-first styling |
| [shadcn/ui](https://ui.shadcn.com/) | โ | Accessible component library |
| [Framer Motion](https://www.framer.com/motion/) | 12 | Animations and transitions |
| [Lucide React](https://lucide.dev/) | โ | Icon system |
| [Prisma](https://www.prisma.io/) | โ | ORM for analytics storage |
| [Node.js Crypto](https://nodejs.org/api/crypto.html) | โ | HMAC-SHA256 signing (server) |
| [Web Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API) | โ | HMAC-SHA256 signing (client) |
### Project Structure
```
captcha-shield/
โโโ server/ # ๐ Server verification module
โ โโโ index.ts # verifyCaptchaShieldToken, middleware, helpers
โโโ src/
โ โโโ app/
โ โ โโโ page.tsx # Landing page
โ โ โโโ verify/page.tsx # Verification page
โ โ โโโ widget-embed/page.tsx # Embeddable widget
โ โ โโโ api/captcha/
โ โ โโโ verify/route.ts # Token verification API
โ โ โโโ generate/route.ts # Challenge generation API
โ โ โโโ analytics/route.ts # Analytics data API
โ โโโ components/
โ โ โโโ captcha/
โ โ โ โโโ CaptchaWidgetV4.tsx # Main widget orchestrator
โ โ โ โโโ AdminDashboardV4.tsx # Risk analytics dashboard
โ โ โ โโโ BehaviorTracker.tsx # Behavioral event collector
โ โ โ โโโ ThemeCustomizer.tsx # Live theme editor
โ โ โ โโโ challenges/
โ โ โ โโโ AdversarialPuzzleChallenge.tsx
โ โ โ โโโ HumanIntuitionGridChallenge.tsx
โ โ โ โโโ PhysicsChaosChallenge.tsx
โ โ โ โโโ TemporalMemoryChallenge.tsx
โ โ โ โโโ OpticalIllusionMazeChallenge.tsx
โ โ โ โโโ VoiceRhythmChallenge.tsx
โ โ โ โโโ GestureSignatureChallenge.tsx
โ โ โ โโโ ContextualReasoningChallenge.tsx
โ โ โ โโโ Live3DBiometricChallenge.tsx
โ โ โ โโโ ZeroKnowledgeProofChallenge.tsx
โ โ โโโ landing/ # Landing page components
โ โ โโโ ui/ # shadcn/ui components
โ โโโ lib/
โ โ โโโ types.ts # Complete type system
โ โ โโโ captcha-engine-v4.ts # Challenge generation & verification
โ โ โโโ behavioral-analyzer-v4.ts # 28 signals + Bayesian scoring
โ โ โโโ token-manager.ts # JWT token lifecycle (isomorphic)
โ โ โโโ plugin-system.ts # Plugin registry & lifecycle
โ โ โโโ i18n.ts # 8-language translations
โ โ โโโ captcha-store.ts # State management
โ โ โโโ db.ts # Prisma client
โ โ โโโ utils.ts # Shared utilities
โ โโโ hooks/
โ โโโ use-mobile.ts # Mobile detection hook
โ โโโ use-toast.ts # Toast notification hook
โโโ prisma/
โ โโโ schema.prisma # Database schema
โโโ examples/
โ โโโ vanilla.html # Vanilla JS integration
โ โโโ form-protected-demo.html # Form protection example
โโโ documentation/
โ โโโ SECURITY_MODEL.md # Threat model & guarantees
โ โโโ PRODUCTION_BACKEND_PLAN.md # Server architecture
โ โโโ API.md # API reference
โ โโโ BEHAVIORAL-ANALYSIS.md # Signal deep dive
โโโ public/
โโโ widget.js # Embeddable widget script
โโโ screenshots/ # Demo screenshots
```
### Data Flow
```
Browser Server Protected Resource
โโโโโโโโ โโโโโโ โโโโโโโโโโโโโโโโโโ
โ โ โ
โ 1. User clicks "I am human" โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโถโ โ
โ โ โ
โ 2. Behavioral precheck โ โ
โ (28 signals computed) โ โ
โ โ โ
โ 3. Dynamic challenge shown โ โ
โ (selected by risk score) โ โ
โ โ โ
โ 4. User solves challenge โ โ
โ (behavioral data collected) โ โ
โ โ โ
โ 5. Token generated โ โ
โ (HMAC-SHA256 signed) โ โ
โ โ โ
โ 6. Token sent to server โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโถโ โ
โ โ โ
โ โ 7. Token verified โ
โ โ - Signature check โ
โ โ - Expiration check โ
โ โ - Risk score check โ
โ โ - Replay protection โ
โ โ โ
โ โ 8. Protected action allowed โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโถโ
โ โ โ
โ 9. Result returned โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
```
---
## ๐ Security Model
### What Fortress Protects Against
| Attack Vector | Protection | Effectiveness |
|--------------|-----------|:------------:|
| **Automated bots** | 28 behavioral signals + Bayesian scoring | โญโญโญโญโญ |
| **Headless browsers** | 20 detection vectors (Puppeteer, Selenium, etc.) | โญโญโญโญโญ |
| **ML-based solvers** | Adversarial noise, optical illusions, intuition challenges | โญโญโญโญ |
| **Replay attacks** | Nonce-based replay protection (2-min window) | โญโญโญโญโญ |
| **Token tampering** | HMAC-SHA256 signatures with timing-safe comparison | โญโญโญโญโญ |
| **Credential stuffing** | Rate limiting + progressive challenge escalation | โญโญโญโญ |
| **CAPTCHA solving services** | Behavioral validation of interaction patterns | โญโญโญ |
### Security Guarantees
- โ
**Timing-safe signature comparison** โ prevents timing side-channel attacks
- โ
**Single-use tokens** โ each token has a unique `jti` nonce
- โ
**Short TTL** โ tokens expire after 60 seconds by default
- โ
**No client-side trust** โ server verification is always required for production
- โ
**Replay protection** โ used tokens are tracked for 2 minutes
- โ
**Risk enforcement** โ server rejects tokens with risk scores above threshold
### Security Boundaries
> โ ๏ธ **Important**: Client-side verification is a **friction layer**, not a security boundary. Any client-side check can be bypassed by a determined attacker. **Server-side verification is required for production security.**
See [SECURITY.md](./SECURITY.md) for responsible disclosure guidelines and [Security Model](documentation/SECURITY_MODEL.md) for the complete threat model.
---
## ๐ก๏ธ Verification Modes
CAPTCHA Shield v4.0 offers **3 verification modes** to balance security and user experience:
| Mode | Behavioral Pre-check | Challenge | QR/WebAuthn | Token TTL | Best For |
|------|:--------------------:|:---------:|:-----------:|:---------:|----------|
| ๐ข **Light** | โ
| 1 easy challenge | โ | 120s | Low-risk forms, newsletters, comments |
| ๐ด **Fortress** | โ
| 2+ challenges (risk-adaptive) | โ
(if risk > 0.5) | 60s | Login, payments, account changes |
| ๐ก **Hybrid** | โ
| 1 challenge + risk-based escalation | โ
(if risk > 0.7) | 90s | General-purpose, adaptive security |
### Mode Selection
```tsx
{/* Light mode โ minimal friction */}
{/* Fortress mode โ maximum security (default) */}
{/* Hybrid mode โ adaptive */}
```
```html
window.CaptchaShieldConfig = {
mode: 'fortress', // 'light' | 'fortress' | 'hybrid'
};
```
### Mode Behavior Details
#### ๐ข Light Mode
- Single easy challenge (e.g., Human Intuition Grid)
- Behavioral pre-check with 28 signals
- Instant pass if risk < 0.15 (no challenge needed)
- Extended token TTL (120s)
- **No QR/WebAuthn escalation**
- Best for low-stakes interactions where friction must be minimal
#### ๐ด Fortress Mode (Default)
- Multi-challenge verification (2+ challenges for medium/high risk)
- Dynamic difficulty scaling based on Bayesian risk score
- QR mobile verification for risk > 0.5
- WebAuthn/Passkey for risk > 0.7
- Strict token TTL (60s)
- Cooldown: 5s ร attempts, capped at 60s
- Instant block at risk > 0.85
- Best for high-value operations requiring maximum security
#### ๐ก Hybrid Mode
- Single challenge by default, escalates based on risk
- Additional challenges triggered at risk > 0.4
- QR/WebAuthn triggered at risk > 0.7
- Moderate token TTL (90s)
- Balanced approach โ low friction for legitimate users, strong protection against bots
---
## ๐บ๏ธ Roadmap
### โ
v4.0 "Fortress" (Current)
- [x] 10 AI-proof challenge types with adversarial design
- [x] 28 behavioral signals with Bayesian risk scoring
- [x] 7-layer defense architecture
- [x] HMAC-SHA256 token signing and verification
- [x] Server verification module (Express, Next.js, standalone)
- [x] Replay protection with nonce-based deduplication
- [x] Plugin architecture for custom challenges
- [x] 8-language internationalization
- [x] WCAG 2.2 AA accessibility compliance
- [x] 20+ headless browser detection vectors
- [x] Admin dashboard with risk analytics
### ๐ฎ v4.1 โ Observability
- [ ] Webhook notifications for verification events
- [ ] Prometheus metrics export
- [ ] Grafana dashboard templates
- [ ] Audit log persistence (Prisma + SQLite)
- [ ] Real-time verification stream (WebSocket)
### ๐ฎ v4.5 โ Intelligence
- [ ] ML-based adaptive difficulty (challenge gets harder for suspicious users)
- [ ] Crowd-sourced challenge difficulty calibration
- [ ] Cross-site risk reputation sharing (opt-in)
- [ ] Device fingerprint reputation database
### ๐ฎ v5.0 โ Platform
- [ ] Multi-tenant SaaS dashboard
- [ ] Managed cloud verification API
- [ ] Rate limiting as a service
- [ ] Custom challenge builder (visual editor)
- [ ] A/B testing for challenge effectiveness
- [ ] Mobile SDK (iOS / Android native widgets)
- [ ] WebAssembly challenge rendering for maximum performance
---
## ๐ค Contributing
We love contributions! CAPTCHA Shield is built by the community, for the community.
### Quick Start
```bash
# 1. Fork & clone
git clone https://github.com/YOUR_USERNAME/captcha-shield.git
cd captcha-shield
# 2. Install dependencies
npm ci
# 3. Start development server
npm run dev
# 4. Make your changes and test
npm run lint
npm run typecheck
```
### Contribution Types
| Type | Description | Example |
|------|-------------|---------|
| ๐ Bug fix | Fix an existing issue | Challenge rendering bug |
| โจ Feature | Add new functionality | New challenge type |
| ๐ Translation | Add or improve i18n | Italian language support |
| โฟ Accessibility | Improve a11y | Better screen reader support |
| ๐ Documentation | Improve docs | API reference update |
| ๐งช Testing | Add test coverage | Challenge engine tests |
| ๐จ Design | Improve UI/UX | Better mobile layout |
### Pull Request Checklist
- [ ] Code compiles without errors (`npm run typecheck`)
- [ ] Linting passes (`npm run lint`)
- [ ] New features include TypeScript types
- [ ] UI changes are responsive (mobile + desktop)
- [ ] Accessibility maintained (WCAG 2.2 AA)
- [ ] Documentation updated if needed
See [CONTRIBUTING.md](CONTRIBUTING.md) for the full contribution guide and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for our community standards.
---
## ๐ Changelog
All notable changes are documented in [CHANGELOG.md](./CHANGELOG.md).
| Version | Codename | Date | Highlights |
|---------|----------|------|------------|
| **4.0.0** | Fortress | 2025-05 | 10 challenges, 28 signals, 7 layers, JWT tokens, plugins, i18n |
| 3.1.0 | โ | 2025-04 | 7 challenges, 14 signals, QR verification, widget embed |
| 3.0.0 | โ | 2025-04 | 4 challenges, 6 signals, behavioral analysis engine |
---
## ๐ License
```
MIT License
Copyright (c) 2024-2025 CAPTCHA Shield Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
---
## ๐ Credits
### Built With
- [Next.js](https://nextjs.org/) โ The React framework for the web
- [React](https://react.dev/) โ The library for web and native user interfaces
- [TypeScript](https://www.typescriptlang.org/) โ JavaScript with syntax for types
- [Tailwind CSS](https://tailwindcss.com/) โ A utility-first CSS framework
- [shadcn/ui](https://ui.shadcn.com/) โ Beautifully designed components
- [Framer Motion](https://www.framer.com/motion/) โ Production-ready motion library
- [Lucide](https://lucide.dev/) โ Beautiful & consistent icons
### Inspired By
- [reCAPTCHA](https://www.google.com/recaptcha/) โ Pioneered the risk-analysis CAPTCHA
- [hCaptcha](https://www.hcaptcha.com/) โ Privacy-first alternative
- [Friendly CAPTCHA](https://friendlycaptcha.com/) โ Proof-of-work approach
- [Cloudflare Turnstile](https://www.cloudflare.com/products/turnstile/) โ Invisible verification
### Research
- Bursztein et al., *"The Difficulty of Breaking CAPTCHAs"* (2023)
- Sivakorn et al., *"I am not a Human: Breaking the Google reCAPTCHA"* (2023)
- Ho et al., *"Detecting and Characterizing Bot Attacks on CAPTCHA Systems"*
---
**Built with โค๏ธ by [Smouj](https://github.com/smouj) and [contributors](https://github.com/smouj/captcha-shield/graphs/contributors)**
[](https://github.com/smouj/captcha-shield)
[](https://smouj.github.io/captcha-shield/)
[](https://www.npmjs.com/)
*If CAPTCHA Shield helps protect your project, consider giving it a โญ โ it helps others find it!*