fx-1 / src /components /auth /CaptchaImagePicker.tsx
felix-fx's picture
Initial commit from GitHub fx-1
6711fd5 verified
Raw History Blame Contribute Delete
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)