fx-1 / src /components /auth /CaptchaText.tsx
felix-fx's picture
Initial commit from GitHub fx-1
6711fd5 verified
Raw History Blame Contribute Delete
15 kB
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<CaptchaTextProps> = ({ onVerified }) => {
const canvasRef = useRef<HTMLCanvasElement>(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<number[]>([]);
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<HTMLInputElement>) => {
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 (
<div className="space-y-3">
<div className="flex items-center gap-3">
<div className="flex-1 h-px bg-gradient-to-r from-transparent via-primary/30 to-transparent" />
<span className="text-[10px] font-black uppercase tracking-[0.2em] text-muted-foreground flex items-center gap-1">
<ShieldCheck className="w-3 h-3" />
التحقق الآمن
</span>
<div className="flex-1 h-px bg-gradient-to-r from-transparent via-primary/30 to-transparent" />
</div>
<div className="relative rounded-xl overflow-hidden border border-border bg-card shadow-lg">
<canvas
ref={canvasRef}
width={360}
height={90}
className="w-full h-[90px] block select-none pointer-events-none"
style={{ imageRendering: 'auto' }}
onContextMenu={(e) => e.preventDefault()}
draggable={false}
/>
<button
type="button"
onClick={regenerate}
disabled={isLocked}
className="absolute top-2 left-2 p-1.5 rounded-lg bg-background/80 hover:bg-background text-muted-foreground hover:text-foreground transition-colors disabled:opacity-30"
title="رمز جديد"
>
<RefreshCw className="w-3.5 h-3.5" />
</button>
{attempts >= 3 && (
<div className="absolute top-2 right-2">
<ShieldAlert className="w-4 h-4 text-destructive animate-pulse" />
</div>
)}
{isLocked && (
<div className="absolute inset-0 bg-black/60 flex items-center justify-center backdrop-blur-sm">
<div className="text-center">
<Lock className="w-6 h-6 text-destructive mx-auto mb-1" />
<p className="text-xs text-white font-bold">مقفل لمدة {lockTimer} ثانية</p>
</div>
</div>
)}
</div>
{/* Honeypot */}
<div className="absolute -left-[9999px] opacity-0 h-0 overflow-hidden" aria-hidden="true">
<input
type="text"
tabIndex={-1}
autoComplete="off"
value={honeypot}
onChange={(e) => setHoneypot(e.target.value)}
name="website_url"
/>
</div>
<div className="flex gap-2">
<Input
value={input}
onChange={handleInputChange}
placeholder="أدخل الأحرف أعلاه"
disabled={status === 'correct' || isLocked}
className="bg-card border-border h-10 text-foreground font-mono tracking-widest text-center text-sm"
dir="ltr"
maxLength={5}
autoComplete="off"
spellCheck={false}
onKeyDown={(e) => e.key === 'Enter' && handleVerify()}
onPaste={(e) => e.preventDefault()}
onCopy={(e) => e.preventDefault()}
onCut={(e) => e.preventDefault()}
/>
<Button
type="button"
onClick={handleVerify}
disabled={!input || status === 'correct' || isLocked}
size="sm"
className={`h-10 px-4 font-bold transition-all ${
status === 'correct'
? 'bg-green-600 text-white'
: status === 'wrong'
? 'bg-destructive text-destructive-foreground animate-shake'
: 'bg-primary text-primary-foreground'
}`}
>
{status === 'correct' ? '✓' : status === 'wrong' ? '✗' : 'تحقق'}
</Button>
</div>
<p className="text-[9px] text-muted-foreground/60 text-center">
الأحرف حساسة لحالتها — أدخل ما تراه بالضبط
</p>
{status === 'wrong' && (
<p className="text-xs text-destructive font-bold animate-in fade-in text-center">
خطأ — جاري تحديث الرمز ({attempts} محاولة)
</p>
)}
{status === 'correct' && (
<p className="text-xs text-green-500 font-bold animate-in fade-in text-center">✓ تم التحقق بنجاح</p>
)}
</div>
);
};
export default CaptchaText;