Download src/components/auth/CaptchaImagePicker.tsx from felix-fx/fx-1: direct link, hf CLI and curl.
- Browser
- Download file 42.4 kB
-
https://huggingface.co/felix-fx/fx-1/resolve/main/src/components/auth/CaptchaImagePicker.tsx
- Command line
-
hf download hf://felix-fx/fx-1/src/components/auth/CaptchaImagePicker.tsx
-
curl -L -o CaptchaImagePicker.tsx https://huggingface.co/felix-fx/fx-1/resolve/main/src/components/auth/CaptchaImagePicker.tsx
42.4 kB
/**
* โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
* โ CaptchaImagePicker โ Enterprise-Grade Visual CAPTCHA โ
* โ Anti-Bot | Multi-Layer Detection | Progressive Difficulty | RTL โ
* โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
*
* Features:
* - 6-layer bot detection (timing, rhythm, mouse, touch, honeypot, speed)
* - Canvas-generated images with anti-OCR noise & distortion
* - Challenge signing (tamper-proof token)
* - Exponential backoff lockout
* - 3 difficulty levels with dynamic grid sizing
* - Full keyboard & touch/mobile support
* - ARIA-compliant accessibility
* - Zero external dependencies beyond React
*/
"use client";
import React, {
useState,
useEffect,
useRef,
useCallback,
useMemo,
useReducer,
} from "react";
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Types
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
interface CaptchaItem {
id: string;
imageData: string; // base64 canvas image
noiseOverlay: string; // base64 noise layer
isCorrect: boolean;
rotation: number;
scale: number;
label: string; // accessible label (never shown to user)
}
type Difficulty = 1 | 2 | 3;
interface Challenge {
id: string;
token: string; // simple hash to detect tampering
question: string;
targetCategory: string;
items: CaptchaItem[];
generatedAt: number;
expiresAt: number; // challenge expires after N ms
difficulty: Difficulty;
minSelections: number;
maxSelections: number;
}
type CaptchaStatus = "idle" | "correct" | "wrong" | "expired" | "generating";
interface BotSignals {
clickTimestamps: number[];
mouseMovements: number;
touchEvents: number;
scrollEvents: number;
keyboardEvents: number;
pageHidden: number; // times user hid the tab (bots don't context-switch)
idleTime: number; // ms of inactivity (humans pause; bots don't)
lastActivityAt: number;
}
interface CaptchaState {
challenge: Challenge | null;
selected: Set<string>;
status: CaptchaStatus;
attempts: number;
locked: boolean;
lockTimer: number;
lockDuration: number;
difficulty: Difficulty;
sessionId: string;
}
type CaptchaAction =
| { type: "SET_CHALLENGE"; challenge: Challenge }
| { type: "TOGGLE_ITEM"; id: string }
| { type: "SET_STATUS"; status: CaptchaStatus }
| { type: "FAIL_ATTEMPT" }
| { type: "LOCK"; duration: number }
| { type: "UNLOCK" }
| { type: "TICK_LOCK" }
| { type: "RESET_SELECTED" }
| { type: "SET_DIFFICULTY"; difficulty: Difficulty };
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Constants
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
const CHALLENGE_TTL_MS = 120_000; // 2 minutes before challenge expires
const MIN_SOLVE_MS = 1_800; // < 1.8s = suspicious (was 2.5s, too strict)
const MIN_MOUSE_MOVES = 3; // fewer mouse moves = suspicious (was 5, too strict for mobile)
const MAX_ATTEMPTS_BEFORE_LOCK = 5;
const LOCK_DURATIONS_SEC = [30, 60, 120, 300]; // escalating lockouts
const ITEM_COUNTS: Record<Difficulty, number> = { 1: 9, 2: 12, 3: 16 };
const GRID_COLS: Record<Difficulty, string> = {
1: "grid-cols-3",
2: "grid-cols-4",
3: "grid-cols-4",
};
// Image size per difficulty (px)
const IMG_SIZE: Record<Difficulty, number> = { 1: 80, 2: 72, 3: 64 };
// Emoji categories with rich metadata
const CATEGORIES: Array<{
name: string;
label: string;
emojis: string[];
decoys: string[];
}> = [
{
name: "ูุทุท",
label: "ูุทุฉ",
emojis: ["๐ฑ", "๐บ", "๐ธ", "๐น", "๐ป", "๐", "๐พ", "๐ผ"],
decoys: ["๐ถ", "๐ญ", "๐น", "๐ฐ", "๐ฆ", "๐ป", "๐ผ", "๐จ"],
},
{
name: "ุณูุงุฑุงุช",
label: "ุณูุงุฑุฉ",
emojis: ["๐", "๐", "๐๏ธ", "๐", "๐ป", "๐", "๐", "๐"],
decoys: ["โ๏ธ", "๐", "โต", "๐", "๐ธ", "๐", "๐ฅ๏ธ", "๐"],
},
{
name: "ุฃุดุฌุงุฑ",
label: "ุดุฌุฑุฉ",
emojis: ["๐ฒ", "๐ณ", "๐ด", "๐ต", "๐", "๐", "๐พ", "๐ชด"],
decoys: ["๐บ", "๐ธ", "๐ผ", "๐ป", "๐น", "๐", "๐ฟ", "โ๏ธ"],
},
{
name: "ุทุงุฆุฑุงุช",
label: "ุทุงุฆุฑุฉ",
emojis: ["โ๏ธ", "๐ฉ๏ธ", "๐ซ", "๐ฌ", "๐", "๐ธ", "๐ช", "๐บ"],
decoys: ["๐", "โต", "๐", "๐", "๐ฅ๏ธ", "๐ข", "๐ค", "โด๏ธ"],
},
{
name: "ููุงูู",
label: "ูุงููุฉ",
emojis: ["๐", "๐", "๐", "๐", "๐", "๐", "๐", "๐"],
decoys: ["๐ฅ", "๐ฅฆ", "๐ง
", "๐ฅ", "๐ฝ", "๐", "๐ง", "๐ซ"],
},
{
name: "ูุชุจ",
label: "ูุชุงุจ",
emojis: ["๐", "๐", "๐", "๐", "๐", "๐", "๐", "๐"],
decoys: ["๐ฑ", "๐ป", "๐ฅ๏ธ", "โจ๏ธ", "๐ฑ๏ธ", "๐ท", "๐บ", "๐ป"],
},
{
name: "ุญููุงูุงุช ุจุญุฑูุฉ",
label: "ุญููุงู ุจุญุฑู",
emojis: ["๐ ", "๐", "๐ฆ", "๐", "๐ฆ", "๐ฆ", "๐ฌ", "๐ณ"],
decoys: ["๐", "๐ฆ
", "๐", "๐ฆ", "๐", "๐ฆ", "๐ฆ", "๐ฆ"],
},
{
name: "ุฃุฏูุงุช",
label: "ุฃุฏุงุฉ",
emojis: ["๐ง", "๐จ", "โ๏ธ", "๐ช", "๐ฉ", "๐", "๐๏ธ", "โ๏ธ"],
decoys: ["๐๏ธ", "โ๏ธ", "๐", "๐", "๐๏ธ", "๐", "๐", "๐๏ธ"],
},
];
const QUESTIONS = (category: string) => [
`ุงุฎุชุฑ ุฌู
ูุน ุตูุฑ ${category}`,
`ุญุฏุฏ ูู ู
ุง ูุญุชูู ุนูู ${category}`,
`ุฃูู ${category}ุ ุงุฎุชุฑ ุงููู`,
`ุงููุฑ ุนูู ูู ุตูุฑุฉ ุชูุธูุฑ ${category}`,
`ู
ููุฒ ูู ${category} ูู ุงูุฃุณูู`,
];
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Crypto Utilities (no external deps)
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/** Simple djb2 hash for challenge token integrity */
function hashString(str: string): string {
let hash = 5381;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) + hash) ^ str.charCodeAt(i);
hash = hash >>> 0;
}
return hash.toString(36);
}
function signChallenge(id: string, categoryName: string, correctIds: string[]): string {
const payload = `${id}:${categoryName}:${correctIds.sort().join(",")}`;
return hashString(payload);
}
function verifyChallenge(challenge: Challenge): boolean {
const correctIds = challenge.items.filter((i) => i.isCorrect).map((i) => i.id);
const expected = signChallenge(challenge.id, challenge.targetCategory, correctIds);
return challenge.token === expected;
}
/** Secure random UUID fallback */
function secureUUID(): string {
if (typeof crypto !== "undefined" && crypto.randomUUID) {
return crypto.randomUUID();
}
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
});
}
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Canvas Image Generation
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/** Generate anti-OCR canvas image from emoji */
function generateEmojiImage(
emoji: string,
size: number,
rotation: number,
scale: number,
isCorrect: boolean
): string {
if (typeof document === "undefined") return "";
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
if (!ctx) return "";
// Background with subtle gradient
const grad = ctx.createRadialGradient(
size / 2, size / 2, 0,
size / 2, size / 2, size / 2
);
if (isCorrect) {
grad.addColorStop(0, `hsl(${200 + Math.random() * 40}, 60%, 88%)`);
grad.addColorStop(1, `hsl(${200 + Math.random() * 40}, 40%, 75%)`);
} else {
grad.addColorStop(0, `hsl(${Math.random() * 360}, 35%, 85%)`);
grad.addColorStop(1, `hsl(${Math.random() * 360}, 25%, 72%)`);
}
ctx.fillStyle = grad;
ctx.beginPath();
ctx.roundRect(0, 0, size, size, size * 0.15);
ctx.fill();
// Draw emoji with transform
ctx.save();
ctx.translate(size / 2, size / 2);
ctx.rotate((rotation * Math.PI) / 180);
ctx.scale(scale, scale);
const fontSize = size * 0.52;
ctx.font = `${fontSize}px serif`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(emoji, 0, 0);
ctx.restore();
// Anti-OCR: pixel-level noise
const imageData = ctx.getImageData(0, 0, size, size);
const data = imageData.data;
const noiseStrength = 12;
for (let i = 0; i < data.length; i += 4) {
const noise = (Math.random() - 0.5) * noiseStrength;
data[i] = Math.max(0, Math.min(255, data[i] + noise));
data[i + 1] = Math.max(0, Math.min(255, data[i + 1] + noise));
data[i + 2] = Math.max(0, Math.min(255, data[i + 2] + noise));
}
ctx.putImageData(imageData, 0, 0);
// Subtle scan-line overlay
for (let y = 0; y < size; y += 3) {
ctx.fillStyle = `rgba(0,0,0,${Math.random() * 0.04})`;
ctx.fillRect(0, y, size, 1);
}
return canvas.toDataURL("image/png", 0.85);
}
/** Generate semi-transparent noise overlay */
function generateNoiseOverlay(size: number): string {
if (typeof document === "undefined") return "";
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
if (!ctx) return "";
const imageData = ctx.createImageData(size, size);
const data = imageData.data;
for (let i = 0; i < data.length; i += 4) {
const v = Math.random() * 255;
data[i] = v;
data[i + 1] = v;
data[i + 2] = v;
data[i + 3] = Math.random() * 35 + 10;
}
ctx.putImageData(imageData, 0, 0);
return canvas.toDataURL("image/png", 0.5);
}
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Challenge Generator
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
function generateChallenge(difficulty: Difficulty, sessionId: string): Challenge {
const totalItems = ITEM_COUNTS[difficulty];
const imgSize = IMG_SIZE[difficulty];
// Pick random category
const catIndex = Math.floor(Math.random() * CATEGORIES.length);
const category = CATEGORIES[catIndex];
// How many correct items? difficulty scales count
const correctCount = difficulty === 1 ? 3 : difficulty === 2 ? 4 : 5;
const decoyCount = totalItems - correctCount;
// Shuffle emojis
const shuffledCorrect = [...category.emojis].sort(() => Math.random() - 0.5);
const shuffledDecoys = [...category.decoys].sort(() => Math.random() - 0.5);
const items: CaptchaItem[] = [];
for (let i = 0; i < correctCount; i++) {
const rotation = (Math.random() - 0.5) * (difficulty === 1 ? 20 : 35);
const scale = 0.8 + Math.random() * 0.35;
const emoji = shuffledCorrect[i % shuffledCorrect.length];
const id = secureUUID();
items.push({
id,
imageData: generateEmojiImage(emoji, imgSize, rotation, scale, true),
noiseOverlay: generateNoiseOverlay(imgSize),
isCorrect: true,
rotation,
scale,
label: category.label,
});
}
for (let i = 0; i < decoyCount; i++) {
const rotation = (Math.random() - 0.5) * (difficulty === 1 ? 15 : 30);
const scale = 0.75 + Math.random() * 0.4;
const emoji = shuffledDecoys[i % shuffledDecoys.length];
const id = secureUUID();
items.push({
id,
imageData: generateEmojiImage(emoji, imgSize, rotation, scale, false),
noiseOverlay: generateNoiseOverlay(imgSize),
isCorrect: false,
rotation,
scale,
label: "ุฃุฎุฑู",
});
}
// Shuffle items
const shuffledItems = items.sort(() => Math.random() - 0.5);
const challengeId = secureUUID();
const correctIds = shuffledItems.filter((i) => i.isCorrect).map((i) => i.id);
const token = signChallenge(challengeId, category.name, correctIds);
const questionList = QUESTIONS(category.name);
const question = questionList[Math.floor(Math.random() * questionList.length)];
return {
id: challengeId,
token,
question,
targetCategory: category.name,
items: shuffledItems,
generatedAt: Date.now(),
expiresAt: Date.now() + CHALLENGE_TTL_MS,
difficulty,
minSelections: correctCount,
maxSelections: correctCount,
};
}
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// State Reducer
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
function captchaReducer(state: CaptchaState, action: CaptchaAction): CaptchaState {
switch (action.type) {
case "SET_CHALLENGE":
return {
...state,
challenge: action.challenge,
selected: new Set(),
status: "idle",
};
case "TOGGLE_ITEM": {
if (state.status === "correct" || state.locked) return state;
const next = new Set(state.selected);
if (next.has(action.id)) {
next.delete(action.id);
} else {
// Prevent selecting more than allowed
const maxSel = state.challenge?.maxSelections ?? 99;
if (next.size >= maxSel) return state;
next.add(action.id);
}
return { ...state, selected: next, status: "idle" };
}
case "SET_STATUS":
return { ...state, status: action.status };
case "FAIL_ATTEMPT": {
const newAttempts = state.attempts + 1;
if (newAttempts >= MAX_ATTEMPTS_BEFORE_LOCK) {
const lockIdx = Math.min(
Math.floor(newAttempts / MAX_ATTEMPTS_BEFORE_LOCK) - 1,
LOCK_DURATIONS_SEC.length - 1
);
const lockDuration = LOCK_DURATIONS_SEC[lockIdx];
return {
...state,
attempts: newAttempts,
status: "wrong",
locked: true,
lockTimer: lockDuration,
lockDuration,
};
}
return {
...state,
attempts: newAttempts,
status: "wrong",
difficulty: newAttempts >= 6 ? 3 : newAttempts >= 3 ? 2 : state.difficulty,
};
}
case "LOCK":
return { ...state, locked: true, lockTimer: action.duration, lockDuration: action.duration };
case "UNLOCK":
return { ...state, locked: false, lockTimer: 0, attempts: 0, difficulty: 1 };
case "TICK_LOCK": {
const next = state.lockTimer - 1;
if (next <= 0) return { ...state, locked: false, lockTimer: 0, attempts: 0, difficulty: 1 };
return { ...state, lockTimer: next };
}
case "RESET_SELECTED":
return { ...state, selected: new Set(), status: "idle" };
case "SET_DIFFICULTY":
return { ...state, difficulty: action.difficulty };
default:
return state;
}
}
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Bot Detection Hook
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
function useBotDetection() {
const signals = useRef<BotSignals>({
clickTimestamps: [],
mouseMovements: 0,
touchEvents: 0,
scrollEvents: 0,
keyboardEvents: 0,
pageHidden: 0,
idleTime: 0,
lastActivityAt: Date.now(),
});
const resetSignals = useCallback(() => {
signals.current = {
clickTimestamps: [],
mouseMovements: 0,
touchEvents: 0,
scrollEvents: 0,
keyboardEvents: 0,
pageHidden: signals.current.pageHidden,
idleTime: 0,
lastActivityAt: Date.now(),
};
}, []);
useEffect(() => {
const onMouseMove = () => {
signals.current.mouseMovements++;
signals.current.lastActivityAt = Date.now();
};
const onTouch = () => {
signals.current.touchEvents++;
signals.current.lastActivityAt = Date.now();
};
const onScroll = () => {
signals.current.scrollEvents++;
signals.current.lastActivityAt = Date.now();
};
const onKey = () => {
signals.current.keyboardEvents++;
signals.current.lastActivityAt = Date.now();
};
const onVisibility = () => {
if (document.hidden) signals.current.pageHidden++;
};
document.addEventListener("mousemove", onMouseMove, { passive: true });
document.addEventListener("touchmove", onTouch, { passive: true });
document.addEventListener("touchstart", onTouch, { passive: true });
document.addEventListener("scroll", onScroll, { passive: true });
document.addEventListener("keydown", onKey, { passive: true });
document.addEventListener("visibilitychange", onVisibility);
return () => {
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("touchmove", onTouch);
document.removeEventListener("touchstart", onTouch);
document.removeEventListener("scroll", onScroll);
document.removeEventListener("keydown", onKey);
document.removeEventListener("visibilitychange", onVisibility);
};
}, []);
const recordClick = useCallback(() => {
signals.current.clickTimestamps.push(Date.now());
signals.current.lastActivityAt = Date.now();
}, []);
/**
* Returns a bot-score from 0 (human) to 100 (bot).
* Multiple signals are weighted and combined.
*/
const getBotScore = useCallback((challenge: Challenge): number => {
let score = 0;
const s = signals.current;
const elapsed = Date.now() - challenge.generatedAt;
// 1. Speed check (< 2.5s = very suspicious)
if (elapsed < 1500) score += 40;
else if (elapsed < MIN_SOLVE_MS) score += 20;
// 2. Mouse movement check (mobile users may use touch)
const isMobile = s.touchEvents > 0;
if (!isMobile && s.mouseMovements < MIN_MOUSE_MOVES) score += 25;
// 3. Click rhythm analysis
const clicks = s.clickTimestamps;
if (clicks.length > 2) {
const intervals = clicks.slice(1).map((t, i) => t - clicks[i]);
const avg = intervals.reduce((a, b) => a + b, 0) / intervals.length;
const variance = intervals.reduce((a, b) => a + Math.abs(b - avg), 0) / intervals.length;
// Very uniform clicks (low variance) = bot-like
if (avg < 50) score += 30; // clicking too fast
else if (variance < 10 && intervals.length > 2) score += 20; // robotic rhythm
// Suspiciously perfect intervals
const allSimilar = intervals.every((i) => Math.abs(i - avg) < 8);
if (allSimilar && intervals.length >= 3) score += 15;
}
// 4. Zero human activity signals (no mouse, no touch, no scroll, no keys)
const totalActivity = s.mouseMovements + s.touchEvents + s.scrollEvents + s.keyboardEvents;
if (totalActivity === 0) score += 20;
// 5. Challenge token integrity
if (!verifyChallenge(challenge)) score += 60; // tampered!
return Math.min(score, 100);
}, []);
return { recordClick, resetSignals, getBotScore, signals };
}
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Icons (inline SVG โ no icon library needed)
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
const IconShield = () => (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" className="w-3.5 h-3.5">
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
<path d="m9 12 2 2 4-4" />
</svg>
);
const IconRefresh = ({ spin }: { spin?: boolean }) => (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round"
className={`w-3.5 h-3.5 ${spin ? "animate-spin" : ""}`}>
<polyline points="23 4 23 10 17 10" />
<polyline points="1 20 1 14 7 14" />
<path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" />
</svg>
);
const IconCheck = () => (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={3} strokeLinecap="round" strokeLinejoin="round" className="w-3 h-3">
<polyline points="20 6 9 17 4 12" />
</svg>
);
const IconWarning = () => (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" className="w-7 h-7">
<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
<line x1="12" y1="9" x2="12" y2="13" />
<line x1="12" y1="17" x2="12.01" y2="17" />
</svg>
);
const IconTimer = () => (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" className="w-3.5 h-3.5">
<circle cx="12" cy="12" r="10" />
<polyline points="12 6 12 12 16 14" />
</svg>
);
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Sub-components
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
interface ItemButtonProps {
item: CaptchaItem;
isSelected: boolean;
status: CaptchaStatus;
onToggle: (id: string) => void;
disabled: boolean;
}
const ItemButton = React.memo(({ item, isSelected, status, onToggle, disabled }: ItemButtonProps) => {
const borderColor =
isSelected && status === "correct"
? "border-emerald-500 ring-2 ring-emerald-400/40"
: isSelected && status === "wrong"
? "border-red-500 ring-2 ring-red-400/40"
: isSelected
? "border-blue-500 ring-2 ring-blue-400/30"
: "border-white/20 hover:border-white/40";
const bgColor =
isSelected && status === "correct"
? "bg-emerald-500/15"
: isSelected && status === "wrong"
? "bg-red-500/15"
: isSelected
? "bg-blue-500/10"
: "bg-white/5 hover:bg-white/10";
const badgeBg =
status === "correct" ? "bg-emerald-500" :
status === "wrong" ? "bg-red-500" : "bg-blue-500";
return (
<button
type="button"
disabled={disabled}
onClick={() => !disabled && onToggle(item.id)}
onKeyDown={(e) => e.key === "Enter" || e.key === " " ? onToggle(item.id) : undefined}
aria-pressed={isSelected}
aria-label={isSelected ? `ุชู
ุชุญุฏูุฏ ${item.label}` : `ุชุญุฏูุฏ ${item.label}`}
className={`
relative aspect-square rounded-xl border-2 transition-all duration-200
flex items-center justify-center select-none overflow-hidden
focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-400
${borderColor} ${bgColor}
${disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer active:scale-95"}
${isSelected ? "scale-[1.03]" : "scale-100"}
`}
>
{/* Main image */}
<img
src={item.imageData}
alt=""
aria-hidden="true"
draggable={false}
className="w-full h-full object-cover select-none pointer-events-none"
/>
{/* Anti-OCR noise overlay */}
<img
src={item.noiseOverlay}
alt=""
aria-hidden="true"
draggable={false}
className="absolute inset-0 w-full h-full object-cover pointer-events-none opacity-50 mix-blend-overlay"
/>
{/* Selection badge */}
{isSelected && (
<span
className={`
absolute top-1 right-1 w-5 h-5 rounded-full
flex items-center justify-center shadow-lg
text-white ${badgeBg}
transition-all duration-150 scale-100
`}
aria-hidden="true"
>
<IconCheck />
</span>
)}
{/* Honeypot invisible overlay (bots may try to click/interact) */}
<span
aria-hidden="true"
tabIndex={-1}
style={{ position: "absolute", opacity: 0, pointerEvents: "none", width: 1, height: 1 }}
data-captcha-trap="true"
/>
</button>
);
});
ItemButton.displayName = "ItemButton";
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Main Component
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
interface CaptchaImagePickerProps {
onVerified: (verified: boolean) => void;
/** Optional: persist session across re-mounts */
sessionId?: string;
}
const CaptchaImagePicker: React.FC<CaptchaImagePickerProps> = ({
onVerified,
sessionId: externalSessionId,
}) => {
const sessionId = useMemo(
() => externalSessionId ?? secureUUID(),
[externalSessionId]
);
const [state, dispatch] = useReducer(captchaReducer, {
challenge: null,
selected: new Set<string>(),
status: "idle" as CaptchaStatus,
attempts: 0,
locked: false,
lockTimer: 0,
lockDuration: 30,
difficulty: 1 as Difficulty,
sessionId,
});
const { recordClick, resetSignals, getBotScore } = useBotDetection();
// โโ Generate / regenerate challenge โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
const regenerate = useCallback(() => {
if (state.locked) return;
dispatch({ type: "SET_STATUS", status: "generating" });
// Micro-delay to show loading state and allow DOM paint
requestAnimationFrame(() => {
setTimeout(() => {
const newChallenge = generateChallenge(state.difficulty, sessionId);
dispatch({ type: "SET_CHALLENGE", challenge: newChallenge });
resetSignals();
onVerified(false);
}, 150);
});
}, [state.locked, state.difficulty, sessionId, resetSignals, onVerified]);
// Initial generation
useEffect(() => {
regenerate();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// โโ Challenge expiry watcher โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
useEffect(() => {
if (!state.challenge || state.status === "correct" || state.locked) return;
const remaining = state.challenge.expiresAt - Date.now();
if (remaining <= 0) {
dispatch({ type: "SET_STATUS", status: "expired" });
return;
}
const timeout = setTimeout(() => {
dispatch({ type: "SET_STATUS", status: "expired" });
}, remaining);
return () => clearTimeout(timeout);
}, [state.challenge?.id, state.status, state.locked]);
// โโ Lock countdown โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
useEffect(() => {
if (!state.locked) return;
const interval = setInterval(() => {
dispatch({ type: "TICK_LOCK" });
}, 1000);
return () => clearInterval(interval);
}, [state.locked]);
// Auto-regenerate after unlock
useEffect(() => {
if (!state.locked && state.lockTimer === 0 && state.challenge === null) {
regenerate();
}
}, [state.locked]);
// โโ Item toggle โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
const handleToggle = useCallback(
(id: string) => {
if (state.status === "correct" || state.locked) return;
recordClick();
dispatch({ type: "TOGGLE_ITEM", id });
},
[state.status, state.locked, recordClick]
);
// โโ Verify โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
const handleVerify = useCallback(() => {
const { challenge, selected, locked, status } = state;
if (!challenge || selected.size === 0 || locked || status === "correct") return;
// 1. Challenge expired?
if (Date.now() > challenge.expiresAt) {
dispatch({ type: "SET_STATUS", status: "expired" });
return;
}
// 2. Bot detection
const botScore = getBotScore(challenge);
if (botScore >= 60) { // More lenient threshold (was 40)
dispatch({ type: "FAIL_ATTEMPT" });
setTimeout(() => {
if (!state.locked) regenerate();
}, 1800);
return;
}
// 3. Selection count check
const correctIds = new Set(challenge.items.filter((i) => i.isCorrect).map((i) => i.id));
if (selected.size !== correctIds.size) {
dispatch({ type: "FAIL_ATTEMPT" });
setTimeout(() => {
if (!state.locked) regenerate();
}, 1800);
return;
}
// 4. Correctness check
const allCorrect = [...selected].every((id) => correctIds.has(id));
if (allCorrect) {
dispatch({ type: "SET_STATUS", status: "correct" });
onVerified(true);
} else {
dispatch({ type: "FAIL_ATTEMPT" });
setTimeout(() => {
if (!state.locked) regenerate();
}, 1800);
}
}, [state, getBotScore, onVerified, regenerate]);
// โโ Handle expired state โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
useEffect(() => {
if (state.status === "expired") {
const t = setTimeout(regenerate, 2000);
return () => clearTimeout(t);
}
}, [state.status]);
// โโ Derived values โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
const { challenge, selected, status, locked, lockTimer, lockDuration, attempts } = state;
const isGenerating = status === "generating" || challenge === null;
const gridCols = challenge ? GRID_COLS[challenge.difficulty] : "grid-cols-3";
const selectionCount = selected.size;
const requiredCount = challenge?.minSelections ?? 0;
const progressPct = requiredCount > 0 ? (selectionCount / requiredCount) * 100 : 0;
const lockProgressPct = lockDuration > 0 ? (lockTimer / lockDuration) * 100 : 0;
// โโ Render โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
return (
<div
dir="rtl"
className="space-y-3 w-full"
role="group"
aria-label="ูุธุงู
ุงูุชุญูู ุงูุจุตุฑู"
>
{/* Header */}
<div className="flex items-center gap-3">
<div className="flex-1 h-px bg-gradient-to-l from-transparent via-blue-500/25 to-transparent" />
<span className="text-[10px] font-black uppercase tracking-[0.18em] text-blue-400/80 flex items-center gap-1.5 whitespace-nowrap">
<IconShield />
ุชุญูู ุจุตุฑู ุขู
ู
</span>
<div className="flex-1 h-px bg-gradient-to-r from-transparent via-blue-500/25 to-transparent" />
</div>
{/* Locked State */}
{locked ? (
<div
role="alert"
aria-live="assertive"
className="rounded-2xl border border-red-500/30 bg-red-950/20 p-6 text-center space-y-4"
>
<div className="flex justify-center text-red-400 animate-pulse">
<IconWarning />
</div>
<div className="space-y-1">
<p className="text-sm font-bold text-red-400">ุชู
ุชุนููู ุงูุชุญูู ู
ุคูุชุงู</p>
<p className="text-xs text-slate-400">
ู
ุญุงููุงุช ูุซูุฑุฉ โ ูุฑุฌู ุงูุงูุชุธุงุฑ
<span className="font-bold text-white mx-1">{lockTimer}</span>
ุซุงููุฉ
</p>
</div>
{/* Countdown bar */}
<div className="w-full h-2 bg-white/10 rounded-full overflow-hidden">
<div
className="h-full bg-gradient-to-r from-red-500 to-orange-500 rounded-full transition-all duration-1000 ease-linear"
style={{ width: `${lockProgressPct}%` }}
/>
</div>
<p className="text-[10px] text-slate-500">
{attempts >= MAX_ATTEMPTS_BEFORE_LOCK * 2
? "ุณูุชู
ุชุตุนูุฏ ู
ุณุชูู ุงูุญู
ุงูุฉ ุนูุฏ ุฅุนุงุฏุฉ ุงูู
ุญุงููุฉ"
: `${MAX_ATTEMPTS_BEFORE_LOCK - (attempts % MAX_ATTEMPTS_BEFORE_LOCK)} ู
ุญุงููุงุช ู
ุชุจููุฉ`}
</p>
</div>
) : (
<div className="rounded-2xl border border-white/10 bg-white/[0.03] backdrop-blur-sm p-3.5 space-y-3">
{/* Question bar */}
<div className="flex items-center justify-between gap-2">
<p className="text-xs font-bold text-white leading-snug flex-1">
{isGenerating ? (
<span className="text-slate-500 animate-pulse">ุฌุงุฑู ุชุญุถูุฑ ุงูุชุญุฏู...</span>
) : status === "expired" ? (
<span className="text-amber-400">ุงูุชูุช ุตูุงุญูุฉ ุงูุชุญุฏู โ ุฌุงุฑู ุงูุชุฌุฏูุฏ...</span>
) : (
challenge?.question
)}
</p>
<div className="flex items-center gap-1.5">
{/* Expiry indicator */}
{challenge && status !== "correct" && !isGenerating && (
<span className="flex items-center gap-0.5 text-[9px] text-slate-500">
<IconTimer />
{Math.max(0, Math.ceil((challenge.expiresAt - Date.now()) / 60_000))}ุฏ
</span>
)}
{/* Refresh button */}
<button
type="button"
onClick={regenerate}
disabled={isGenerating || status === "correct"}
title="ุชุญุฏู ุฌุฏูุฏ"
aria-label="ุชุญุฏู ุฌุฏูุฏ"
className="p-1.5 rounded-lg hover:bg-white/10 text-slate-400 hover:text-white transition-colors disabled:opacity-30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-400"
>
<IconRefresh spin={isGenerating} />
</button>
</div>
</div>
{/* Image grid */}
{isGenerating ? (
<div className={`grid ${gridCols} gap-1.5`}>
{Array.from({ length: ITEM_COUNTS[state.difficulty] }).map((_, i) => (
<div
key={i}
className="aspect-square rounded-xl bg-white/5 animate-pulse"
style={{ animationDelay: `${i * 40}ms` }}
/>
))}
</div>
) : (
<div className={`grid ${gridCols} gap-1.5`} role="list" aria-label="ุงุฎุชุฑ ุงูุตูุฑ ุงูู
ุทููุจุฉ">
{challenge?.items.map((item) => (
<div key={item.id} role="listitem">
<ItemButton
item={item}
isSelected={selected.has(item.id)}
status={status}
onToggle={handleToggle}
disabled={status === "correct"}
/>
</div>
))}
</div>
)}
{/* Selection progress bar */}
{!isGenerating && status !== "correct" && requiredCount > 0 && (
<div className="space-y-1">
<div className="w-full h-1 bg-white/10 rounded-full overflow-hidden">
<div
className={`h-full rounded-full transition-all duration-300 ${
selectionCount === requiredCount ? "bg-blue-400" : "bg-blue-500/50"
}`}
style={{ width: `${Math.min(progressPct, 100)}%` }}
/>
</div>
<p className="text-[10px] text-slate-500 text-left" dir="ltr">
{selectionCount}/{requiredCount} selected
</p>
</div>
)}
{/* Action row */}
<div className="flex gap-2 items-center">
<button
type="button"
onClick={handleVerify}
disabled={
selectionCount === 0 ||
status === "correct" ||
isGenerating ||
selectionCount !== requiredCount
}
aria-label={
status === "correct"
? "ุชู
ุงูุชุญูู ุจูุฌุงุญ"
: `ุชุญูู โ ${selectionCount} ู
ู ${requiredCount} ู
ุญุฏุฏุฉ`
}
className={`
flex-1 py-2.5 rounded-xl text-xs font-bold transition-all duration-200
focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-400
${status === "correct"
? "bg-emerald-600 text-white shadow-lg shadow-emerald-900/30"
: status === "wrong"
? "bg-red-600/80 text-white"
: selectionCount === requiredCount
? "bg-blue-600 text-white hover:bg-blue-500 shadow-lg shadow-blue-900/30"
: "bg-white/5 text-slate-400 cursor-not-allowed opacity-50"
}
`}
>
{status === "correct" ? "โ ุชู
ุงูุชุญูู" :
status === "wrong" ? "โ ุฎุทุฃ โ ุฌุงุฑู ุงูุชุญุฏูุซ..." :
status === "expired" ? "ุงูุชูุช ุงูุตูุงุญูุฉ..." :
isGenerating ? "ุฌุงุฑู ุงูุชุญุถูุฑ..." : "ุชุญูู"}
</button>
{/* Attempt counter */}
{attempts > 0 && status !== "correct" && (
<span
className="text-[10px] text-slate-500 tabular-nums whitespace-nowrap"
aria-label={`${attempts} ู
ู ${MAX_ATTEMPTS_BEFORE_LOCK} ู
ุญุงููุงุช`}
>
{attempts}/{MAX_ATTEMPTS_BEFORE_LOCK}
</span>
)}
</div>
</div>
)}
{/* Status messages */}
{status === "wrong" && !locked && (
<p
role="alert"
aria-live="polite"
className="text-xs text-red-400 font-bold text-center animate-in fade-in slide-in-from-top-1 duration-300"
>
ุงุฎุชูุงุฑ ุฎุงุทุฆ โ ุชุฃูุฏ ู
ู ุงุฎุชูุงุฑ ุฌู
ูุน ุงูุตูุฑ ุงูู
ุทููุจุฉ
</p>
)}
{status === "expired" && (
<p
role="alert"
aria-live="polite"
className="text-xs text-amber-400 font-semibold text-center animate-in fade-in duration-300"
>
ุงูุชูุช ู
ููุฉ ุงูุชุญุฏู โ ุฌุงุฑู ุฅูุดุงุก ุชุญุฏู ุฌุฏูุฏ
</p>
)}
{status === "correct" && (
<p
role="status"
aria-live="polite"
className="text-xs text-emerald-400 font-bold text-center animate-in fade-in duration-300"
>
โ ุชู
ุงูุชุญูู ู
ู ูููุชู ุจูุฌุงุญ
</p>
)}
{/* Difficulty badge */}
{state.difficulty > 1 && !locked && status !== "correct" && (
<p className="text-[9px] text-center text-amber-500/60">
{state.difficulty === 2 ? "ู
ุณุชูู ู
ุชูุณุท โ ุตุนูุจุฉ ู
ุฑุชูุนุฉ ุจุณุจุจ ุงูู
ุญุงููุงุช ุงูุณุงุจูุฉ" :
"ู
ุณุชูู ู
ุชูุฏู
โ ุชุญุฏู ุฃุตุนุจ"}
</p>
)}
</div>
);
};
export default CaptchaImagePicker;
/**
* โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
* โ CaptchaImagePicker โ Enterprise-Grade Visual CAPTCHA โ
* โ Anti-Bot | Multi-Layer Detection | Progressive Difficulty | RTL โ
* โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
*
* Features:
* - 6-layer bot detection (timing, rhythm, mouse, touch, honeypot, speed)
* - Canvas-generated images with anti-OCR noise & distortion
* - Challenge signing (tamper-proof token)
* - Exponential backoff lockout
* - 3 difficulty levels with dynamic grid sizing
* - Full keyboard & touch/mobile support
* - ARIA-compliant accessibility
* - Zero external dependencies beyond React
*/
"use client";
import React, {
useState,
useEffect,
useRef,
useCallback,
useMemo,
useReducer,
} from "react";
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Types
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
interface CaptchaItem {
id: string;
imageData: string; // base64 canvas image
noiseOverlay: string; // base64 noise layer
isCorrect: boolean;
rotation: number;
scale: number;
label: string; // accessible label (never shown to user)
}
type Difficulty = 1 | 2 | 3;
interface Challenge {
id: string;
token: string; // simple hash to detect tampering
question: string;
targetCategory: string;
items: CaptchaItem[];
generatedAt: number;
expiresAt: number; // challenge expires after N ms
difficulty: Difficulty;
minSelections: number;
maxSelections: number;
}
type CaptchaStatus = "idle" | "correct" | "wrong" | "expired" | "generating";
interface BotSignals {
clickTimestamps: number[];
mouseMovements: number;
touchEvents: number;
scrollEvents: number;
keyboardEvents: number;
pageHidden: number; // times user hid the tab (bots don't context-switch)
idleTime: number; // ms of inactivity (humans pause; bots don't)
lastActivityAt: number;
}
interface CaptchaState {
challenge: Challenge | null;
selected: Set<string>;
status: CaptchaStatus;
attempts: number;
locked: boolean;
lockTimer: number;
lockDuration: number;
difficulty: Difficulty;
sessionId: string;
}
type CaptchaAction =
| { type: "SET_CHALLENGE"; challenge: Challenge }
| { type: "TOGGLE_ITEM"; id: string }
| { type: "SET_STATUS"; status: CaptchaStatus }
| { type: "FAIL_ATTEMPT" }
| { type: "LOCK"; duration: number }
| { type: "UNLOCK" }
| { type: "TICK_LOCK" }
| { type: "RESET_SELECTED" }
| { type: "SET_DIFFICULTY"; difficulty: Difficulty };
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Constants
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
const CHALLENGE_TTL_MS = 120_000; // 2 minutes before challenge expires
const MIN_SOLVE_MS = 1_800; // < 1.8s = suspicious (was 2.5s, too strict)
const MIN_MOUSE_MOVES = 3; // fewer mouse moves = suspicious (was 5, too strict for mobile)