import React, { useState, useEffect, useRef, useCallback } from 'react'; import { RefreshCw, ShieldCheck, ShieldAlert, Lock } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; interface CaptchaTextProps { onVerified: (verified: boolean) => void; } // Characters that are visually distinct to avoid confusion (removed O/0, I/l/1, etc.) const CHARS = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz2345679'; /** Simple hash for internal token signing */ function hashToken(str: string): string { let h = 5381; for (let i = 0; i < str.length; i++) { h = ((h << 5) + h) ^ str.charCodeAt(i); h = h >>> 0; } return h.toString(36); } /** XOR-based obfuscation so the answer isn't stored in plaintext */ function obfuscate(text: string, key: string): string { return text .split('') .map((c, i) => String.fromCharCode(c.charCodeAt(0) ^ key.charCodeAt(i % key.length))) .map(c => c.charCodeAt(0).toString(16).padStart(4, '0')) .join(''); } function deobfuscate(hex: string, key: string): string { const chars: string[] = []; for (let i = 0; i < hex.length; i += 4) { chars.push(String.fromCharCode(parseInt(hex.substring(i, i + 4), 16))); } return chars .map((c, i) => String.fromCharCode(c.charCodeAt(0) ^ key.charCodeAt(i % key.length))) .join(''); } function generateCode(length = 5): string { let code = ''; const arr = new Uint32Array(length); crypto.getRandomValues(arr); for (let i = 0; i < length; i++) { code += CHARS[arr[i] % CHARS.length]; } return code; } /** Draw the actual code with heavy distortion on canvas */ function drawCaptcha(canvas: HTMLCanvasElement, code: string) { const ctx = canvas.getContext('2d'); if (!ctx) return; const w = canvas.width; const h = canvas.height; // Dark textured background const bgGrad = ctx.createLinearGradient(0, 0, w, h); bgGrad.addColorStop(0, '#1a1a2e'); bgGrad.addColorStop(0.5, '#16213e'); bgGrad.addColorStop(1, '#0f3460'); ctx.fillStyle = bgGrad; ctx.fillRect(0, 0, w, h); // Heavy noise dots for (let i = 0; i < 200; i++) { ctx.fillStyle = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, ${0.03 + Math.random() * 0.08})`; ctx.beginPath(); ctx.arc(Math.random() * w, Math.random() * h, Math.random() * 2.5, 0, Math.PI * 2); ctx.fill(); } // Wavy confusing lines for (let i = 0; i < 6; i++) { ctx.strokeStyle = `rgba(${100 + Math.random() * 155}, ${100 + Math.random() * 155}, ${100 + Math.random() * 155}, ${0.15 + Math.random() * 0.2})`; ctx.lineWidth = 0.8 + Math.random() * 1.5; ctx.beginPath(); const startY = Math.random() * h; ctx.moveTo(0, startY); for (let x = 0; x < w; x += 3) { const amplitude = 4 + Math.random() * 8; const freq = 0.03 + Math.random() * 0.06; ctx.lineTo(x, startY + Math.sin(x * freq + i * 2) * amplitude + (Math.random() - 0.5) * 3); } ctx.stroke(); } // Bezier curves crossing text area for (let i = 0; i < 3; i++) { ctx.strokeStyle = `rgba(${150 + Math.random() * 100}, ${150 + Math.random() * 100}, ${200 + Math.random() * 55}, ${0.2 + Math.random() * 0.15})`; ctx.lineWidth = 1 + Math.random() * 2; ctx.beginPath(); ctx.moveTo(Math.random() * w, Math.random() * h); ctx.bezierCurveTo( Math.random() * w, Math.random() * h, Math.random() * w, Math.random() * h, Math.random() * w, Math.random() * h ); ctx.stroke(); } // Draw each character with individual distortion const charSpacing = w / (code.length + 1.5); const colors = [ '#e94560', '#0f3460', '#533483', '#e94560', '#00b4d8', '#48cae4', '#f72585', '#7209b7', '#3a0ca3', '#4361ee', ]; const fonts = [ "'Arial Black', 'Arial', sans-serif", "'Courier New', monospace", "'Georgia', serif", "'Verdana', sans-serif", "'Impact', sans-serif", "'Trebuchet MS', sans-serif", ]; code.split('').forEach((char, i) => { ctx.save(); const x = charSpacing * (i + 1) + (Math.random() - 0.5) * 8; const y = h / 2 + (Math.random() - 0.5) * 14; // Aggressive transforms const angle = (Math.random() - 0.5) * 0.6; const scaleX = 0.7 + Math.random() * 0.5; const scaleY = 0.7 + Math.random() * 0.5; const skewX = (Math.random() - 0.5) * 0.25; const skewY = (Math.random() - 0.5) * 0.1; ctx.translate(x, y); ctx.rotate(angle); ctx.transform(scaleX, skewY, skewX, scaleY, 0, 0); const fontSize = 28 + Math.floor(Math.random() * 12); const bold = Math.random() > 0.3 ? 'bold' : '900'; ctx.font = `${bold} ${fontSize}px ${fonts[i % fonts.length]}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; // Multi-layer text rendering for depth // Shadow layer ctx.shadowColor = 'rgba(0,0,0,0.5)'; ctx.shadowBlur = 3 + Math.random() * 4; ctx.shadowOffsetX = (Math.random() - 0.5) * 3; ctx.shadowOffsetY = (Math.random() - 0.5) * 3; // Main fill const color = colors[i % colors.length]; ctx.fillStyle = color; ctx.fillText(char, 0, 0); // Outline with slight offset for 3D effect ctx.shadowBlur = 0; ctx.shadowOffsetX = 0; ctx.shadowOffsetY = 0; ctx.strokeStyle = `rgba(255, 255, 255, ${0.15 + Math.random() * 0.2})`; ctx.lineWidth = 0.5 + Math.random() * 0.8; ctx.strokeText(char, (Math.random() - 0.5) * 1.5, (Math.random() - 0.5) * 1.5); // Ghost duplicate for confusion if (Math.random() > 0.5) { ctx.fillStyle = `rgba(${Math.random() * 200}, ${Math.random() * 200}, ${Math.random() * 200}, 0.08)`; ctx.fillText(char, (Math.random() - 0.5) * 6, (Math.random() - 0.5) * 6); } ctx.restore(); }); // Post-processing: pixel noise const imageData = ctx.getImageData(0, 0, w, h); const pixels = imageData.data; for (let i = 0; i < pixels.length; i += 4) { const noise = (Math.random() - 0.5) * 18; pixels[i] = Math.max(0, Math.min(255, pixels[i] + noise)); pixels[i + 1] = Math.max(0, Math.min(255, pixels[i + 1] + noise)); pixels[i + 2] = Math.max(0, Math.min(255, pixels[i + 2] + noise)); } ctx.putImageData(imageData, 0, 0); // Scanlines for (let y = 0; y < h; y += 2) { ctx.fillStyle = `rgba(0, 0, 0, ${0.02 + Math.random() * 0.06})`; ctx.fillRect(0, y, w, 1); } // Vignette const vig = ctx.createRadialGradient(w / 2, h / 2, w * 0.2, w / 2, h / 2, w * 0.7); vig.addColorStop(0, 'rgba(0,0,0,0)'); vig.addColorStop(1, 'rgba(0,0,0,0.3)'); ctx.fillStyle = vig; ctx.fillRect(0, 0, w, h); // Quality reduction: slight blur simulation ctx.globalAlpha = 0.15; ctx.drawImage(canvas, 1, 1, w - 2, h - 2, 0, 0, w, h); ctx.globalAlpha = 1; } const CaptchaText: React.FC = ({ onVerified }) => { const canvasRef = useRef(null); const [encryptedAnswer, setEncryptedAnswer] = useState(''); const [sessionKey] = useState(() => crypto.randomUUID()); const [input, setInput] = useState(''); const [status, setStatus] = useState<'idle' | 'correct' | 'wrong' | 'locked'>('idle'); const [attempts, setAttempts] = useState(0); const [generatedAt, setGeneratedAt] = useState(0); const [honeypot, setHoneypot] = useState(''); const [lockTimer, setLockTimer] = useState(0); const [interactionTimestamps, setInteractionTimestamps] = useState([]); const [mouseMovements, setMouseMovements] = useState(0); const regenerate = useCallback(() => { const code = generateCode(5); const encrypted = obfuscate(code, sessionKey); setEncryptedAnswer(encrypted); setInput(''); setStatus('idle'); setGeneratedAt(Date.now()); setInteractionTimestamps([]); setMouseMovements(0); onVerified(false); // Draw on next frame to ensure canvas is ready requestAnimationFrame(() => { if (canvasRef.current) { drawCaptcha(canvasRef.current, code); } }); }, [sessionKey, onVerified]); useEffect(() => { regenerate(); }, [regenerate]); // Lock timer countdown useEffect(() => { if (lockTimer <= 0) return; const interval = setInterval(() => { setLockTimer(prev => { if (prev <= 1) { setStatus('idle'); setAttempts(0); regenerate(); return 0; } return prev - 1; }); }, 1000); return () => clearInterval(interval); }, [lockTimer, regenerate]); // Track mouse movement for bot detection useEffect(() => { const handler = () => setMouseMovements(prev => prev + 1); window.addEventListener('mousemove', handler, { passive: true }); return () => window.removeEventListener('mousemove', handler); }, []); const handleInputChange = (e: React.ChangeEvent) => { if (status === 'correct' || status === 'locked') return; setInput(e.target.value); setInteractionTimestamps(prev => [...prev, Date.now()]); if (status === 'wrong') setStatus('idle'); }; const handleVerify = () => { if (status === 'correct' || status === 'locked' || !input.trim()) return; // 1. Honeypot check if (honeypot) { failAttempt(); return; } // 2. Timing check — solved too fast = bot const elapsed = Date.now() - generatedAt; if (elapsed < 1500) { failAttempt(); return; } // 3. Mouse movement check — no mouse = likely bot if (mouseMovements < 3 && elapsed > 5000) { // Only suspicious if enough time passed but no mouse movement // Could be mobile, so we don't hard-fail — just note it } // 4. Typing pattern analysis if (interactionTimestamps.length > 2) { const intervals = interactionTimestamps.slice(1).map((t, i) => t - interactionTimestamps[i]); const avgInterval = intervals.reduce((a, b) => a + b, 0) / intervals.length; // Perfectly uniform typing = bot if (intervals.length >= 4 && intervals.every(iv => Math.abs(iv - avgInterval) < 15)) { failAttempt(); return; } // Superhuman speed if (avgInterval < 30) { failAttempt(); return; } } // 5. Decrypt and compare const answer = deobfuscate(encryptedAnswer, sessionKey); if (input === answer) { setStatus('correct'); onVerified(true); } else { failAttempt(); } }; const failAttempt = () => { const newAttempts = attempts + 1; setAttempts(newAttempts); onVerified(false); if (newAttempts >= 8) { setStatus('locked'); setLockTimer(120); // 2 minutes } else if (newAttempts >= 5) { setStatus('locked'); setLockTimer(30); // 30 seconds } else { setStatus('wrong'); setTimeout(regenerate, 1200); } }; const isLocked = status === 'locked' && lockTimer > 0; return (
التحقق الآمن
e.preventDefault()} draggable={false} /> {attempts >= 3 && (
)} {isLocked && (

مقفل لمدة {lockTimer} ثانية

)}
{/* Honeypot */}
e.key === 'Enter' && handleVerify()} onPaste={(e) => e.preventDefault()} onCopy={(e) => e.preventDefault()} onCut={(e) => e.preventDefault()} />

الأحرف حساسة لحالتها — أدخل ما تراه بالضبط

{status === 'wrong' && (

خطأ — جاري تحديث الرمز ({attempts} محاولة)

)} {status === 'correct' && (

✓ تم التحقق بنجاح

)}
); }; export default CaptchaText;