import React, { useState, useEffect } from 'react'; import { Button } from '@/components/ui/button'; import { Fingerprint, Loader2, Shield, Lock } from 'lucide-react'; import { toast } from 'sonner'; interface BiometricAuthProps { onSuccess: (credentialId: string) => void; userId?: string; userName?: string; mode: 'register' | 'login'; expectedCredentialId?: string | null; } const BiometricAuth: React.FC = ({ onSuccess, userId = "user-id", userName = "User", mode, expectedCredentialId }) => { const [isAvailable, setIsAvailable] = useState(false); const [loading, setLoading] = useState(false); // وظائف تحويل البيانات لضمان التوافق مع WebAuthn const bufferToBase64 = (b: ArrayBuffer) => { return btoa(String.fromCharCode(...new Uint8Array(b))) .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=/g, ''); }; const base64ToBuffer = (s: string) => { const base64 = s.replace(/-/g, '+').replace(/_/g, '/'); const binString = atob(base64); return Uint8Array.from(binString, c => c.charCodeAt(0)); }; useEffect(() => { const checkAvailability = async () => { if (window.PublicKeyCredential) { try { const available = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable(); setIsAvailable(available); } catch (e) { console.error("Biometric availability check failed:", e); setIsAvailable(false); } } }; checkAvailability(); }, []); const handleBiometricAuth = async () => { setLoading(true); try { const challenge = window.crypto.getRandomValues(new Uint8Array(32)); if (mode === 'register') { const options: CredentialCreationOptions = { publicKey: { challenge, rp: { name: "Minecraft FX", id: window.location.hostname === 'localhost' ? 'localhost' : window.location.hostname }, user: { // نستخدم قيمة ثابتة للمعرف أثناء التسجيل لضمان استقرار التوقيع id: new TextEncoder().encode(userId), name: userId, displayName: userName }, pubKeyCredParams: [ { alg: -7, type: "public-key" }, // ES256 { alg: -257, type: "public-key" } // RS256 ], authenticatorSelection: { authenticatorAttachment: "platform", userVerification: "preferred", residentKey: "preferred" }, timeout: 60000 } }; const cred = await navigator.credentials.create(options) as PublicKeyCredential; if (cred) { const credentialId = bufferToBase64(cred.rawId); toast.success("تم إعداد البصمة بنجاح"); onSuccess(credentialId); } } else { // In login mode without a stored credential, just verify platform authenticator const options: CredentialRequestOptions = { publicKey: { challenge, rpId: window.location.hostname === 'localhost' ? 'localhost' : window.location.hostname, ...(expectedCredentialId ? { allowCredentials: [{ id: base64ToBuffer(expectedCredentialId), type: 'public-key' as const, }], } : {}), userVerification: "preferred", timeout: 60000 } }; const assertion = await navigator.credentials.get(options); if (assertion) { toast.success("تم التحقق من البصمة بنجاح"); onSuccess(expectedCredentialId); } } } catch (err: any) { console.error("Biometric Error:", err); if (err.name === 'NotAllowedError') { toast.error("تم إلغاء عملية التحقق"); } else if (err.name === 'InvalidStateError') { toast.error("هذه البصمة مسجلة بالفعل أو غير صالحة"); } else if (err.name === 'SecurityError') { toast.error("خطأ في الأمان: تأكد من استخدام HTTPS ونطاق صحيح"); } else { toast.error(`فشل التحقق: ${err.message || "خطأ غير معروف"}`); } } finally { setLoading(false); } }; if (!isAvailable) return (

جهازك لا يدعم البصمة، سيتم الاعتماد على كلمة المرور فقط.

); return (
التحقق البيومتري
); }; export default BiometricAuth;