feat(security): replace Firebase with Cloudflare Turnstile bot verification

This commit is contained in:
2026-11-13 17:48:49 +05:30
parent 5907031e1c
commit 1ed1d25bda
19 changed files with 422 additions and 1518 deletions
-379
View File
@@ -1,379 +0,0 @@
'use client';
import React, { useState, useEffect } from 'react';
import {
X,
Mail,
Lock,
User as UserIcon,
Eye,
EyeOff,
AlertCircle,
CheckCircle2,
Sparkles,
ArrowRight,
Loader2,
} from 'lucide-react';
import { useAuth } from '@/lib/firebase/AuthContext';
function GoogleIcon({ className = 'w-4 h-4' }: { className?: string }) {
return (
<svg viewBox="0 0 24 24" className={className} aria-hidden="true">
<path
d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
fill="#4285F4"
/>
<path
d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
fill="#34A853"
/>
<path
d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.06H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.94l2.85-2.22.81-.63z"
fill="#FBBC05"
/>
<path
d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84c.87-2.6 3.3-4.52 6.16-4.52z"
fill="#EA4335"
/>
</svg>
);
}
function parseAuthError(error: any): string {
const code = error?.code || '';
switch (code) {
case 'auth/user-not-found':
case 'auth/wrong-password':
case 'auth/invalid-credential':
return 'Invalid email address or password.';
case 'auth/email-already-in-use':
return 'An account already exists with this email address.';
case 'auth/invalid-email':
return 'Please enter a valid email address.';
case 'auth/weak-password':
return 'Password should be at least 6 characters.';
case 'auth/popup-closed-by-user':
return 'Sign in cancelled before completion.';
case 'auth/too-many-requests':
return 'Too many attempts. Please wait a few moments and try again.';
case 'auth/network-request-failed':
return 'Network error. Please check your internet connection.';
default:
return error?.message || 'Authentication failed. Please try again.';
}
}
export function AuthModal() {
const {
authModalOpen,
authModalMode,
closeAuthModal,
openAuthModal,
signInWithGoogle,
signInWithEmail,
signUpWithEmail,
sendPasswordReset,
isConfigured,
} = useAuth();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [name, setName] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
// Reset form when modal opens or mode changes
useEffect(() => {
setError(null);
setSuccess(null);
setEmail('');
setPassword('');
setName('');
}, [authModalOpen, authModalMode]);
// Handle ESC key to close modal
useEffect(() => {
if (!authModalOpen) return;
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') closeAuthModal();
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [authModalOpen, closeAuthModal]);
if (!authModalOpen) return null;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setSuccess(null);
setLoading(true);
try {
if (authModalMode === 'signin') {
if (!email.trim() || !password) {
setError('Please provide both email and password.');
setLoading(false);
return;
}
await signInWithEmail(email, password);
} else if (authModalMode === 'signup') {
if (!email.trim() || !password) {
setError('Please provide email and password.');
setLoading(false);
return;
}
if (password.length < 6) {
setError('Password must be at least 6 characters.');
setLoading(false);
return;
}
await signUpWithEmail(email, password, name);
} else if (authModalMode === 'reset') {
if (!email.trim()) {
setError('Please enter your account email.');
setLoading(false);
return;
}
await sendPasswordReset(email);
setSuccess('Password reset link sent! Check your inbox.');
}
} catch (err: any) {
setError(parseAuthError(err));
} finally {
setLoading(false);
}
};
const handleGoogleSignIn = async () => {
setError(null);
setSuccess(null);
setLoading(true);
try {
await signInWithGoogle();
} catch (err: any) {
setError(parseAuthError(err));
} finally {
setLoading(false);
}
};
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6 bg-slate-950/60 backdrop-blur-sm animate-in fade-in duration-200"
onClick={(e) => {
if (e.target === e.currentTarget) closeAuthModal();
}}
role="dialog"
aria-modal="true"
aria-labelledby="auth-modal-title"
>
<div className="relative w-full max-w-md bg-paper-hi border border-rule rounded-2xl p-6 sm:p-8 shadow-2xl overflow-hidden motion-safe:transition-all">
{/* Top Close Button */}
<button
onClick={closeAuthModal}
className="absolute right-4 top-4 p-1.5 rounded-full text-slate-400 hover:text-slate-900 hover:bg-slate-100 transition-colors cursor-pointer"
aria-label="Close dialog"
>
<X className="w-4 h-4" />
</button>
{/* Unconfigured Configuration Warning Banner */}
{!isConfigured && (
<div className="mb-5 p-3 rounded-xl bg-amber-500/10 border border-amber-500/20 text-amber-800 text-xs flex items-start gap-2.5">
<AlertCircle className="w-4 h-4 text-amber-600 shrink-0 mt-0.5" />
<div>
<span className="font-semibold block text-amber-900">Firebase Setup Ready</span>
Add your credentials to <code className="font-mono text-[11px] bg-amber-200/50 px-1 py-0.5 rounded">.env.local</code> to activate live authentication.
</div>
</div>
)}
{/* Header */}
<div className="text-center mb-6">
<div className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-accent/10 border border-accent/20 text-accent text-xs font-semibold mb-3">
<Sparkles className="w-3.5 h-3.5" />
<span>CRE Innovations Studio</span>
</div>
<h2 id="auth-modal-title" className="text-2xl font-display font-bold text-ink tracking-tight">
{authModalMode === 'signin' && 'Welcome back'}
{authModalMode === 'signup' && 'Create your account'}
{authModalMode === 'reset' && 'Reset your password'}
</h2>
<p className="mt-1 text-xs sm:text-sm text-slate-500 font-sans">
{authModalMode === 'signin' && 'Sign in to access your cloud studio workspace'}
{authModalMode === 'signup' && 'Start editing with lossless 4K neural vision tools'}
{authModalMode === 'reset' && "Enter your email and we'll send you a password recovery link"}
</p>
</div>
{/* Error & Success Messages */}
{error && (
<div className="mb-4 p-3 rounded-xl bg-rose-500/10 border border-rose-500/20 text-rose-700 text-xs flex items-start gap-2">
<AlertCircle className="w-4 h-4 shrink-0 mt-0.5" />
<span>{error}</span>
</div>
)}
{success && (
<div className="mb-4 p-3 rounded-xl bg-emerald-500/10 border border-emerald-500/20 text-emerald-700 text-xs flex items-start gap-2">
<CheckCircle2 className="w-4 h-4 shrink-0 mt-0.5" />
<span>{success}</span>
</div>
)}
{/* OAuth: Google One-Click Sign In (for signin & signup) */}
{authModalMode !== 'reset' && (
<div className="space-y-4 mb-5">
<button
type="button"
onClick={handleGoogleSignIn}
disabled={loading}
className="w-full h-11 inline-flex items-center justify-center gap-2.5 px-4 rounded-xl bg-white border border-slate-200 hover:border-slate-300 hover:bg-slate-50/80 text-slate-700 font-sans font-semibold text-xs sm:text-sm shadow-xs transition-all active:scale-[0.99] cursor-pointer disabled:opacity-60"
>
<GoogleIcon className="w-4 h-4" />
<span>Continue with Google</span>
</button>
<div className="relative flex items-center justify-center">
<div className="border-t border-slate-200 w-full" />
<span className="bg-paper-hi px-3 text-[11px] font-mono text-slate-400 uppercase tracking-wider">
or with email
</span>
</div>
</div>
)}
{/* Email & Password Form */}
<form onSubmit={handleSubmit} className="space-y-3.5">
{authModalMode === 'signup' && (
<div>
<label className="block text-xs font-semibold text-slate-700 mb-1">Full name</label>
<div className="relative">
<UserIcon className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
<input
type="text"
placeholder="Jane Doe"
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full pl-9 pr-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-xs sm:text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/20"
/>
</div>
</div>
)}
<div>
<label className="block text-xs font-semibold text-slate-700 mb-1">Email address</label>
<div className="relative">
<Mail className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
<input
type="email"
placeholder="[email protected]"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full pl-9 pr-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-xs sm:text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/20"
/>
</div>
</div>
{authModalMode !== 'reset' && (
<div>
<div className="flex items-center justify-between mb-1">
<label className="text-xs font-semibold text-slate-700">Password</label>
{authModalMode === 'signin' && (
<button
type="button"
onClick={() => openAuthModal('reset')}
className="text-[11px] text-accent hover:underline cursor-pointer"
>
Forgot password?
</button>
)}
</div>
<div className="relative">
<Lock className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
<input
type={showPassword ? 'text' : 'password'}
placeholder="••••••••"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="w-full pl-9 pr-10 py-2.5 rounded-xl border border-slate-200 bg-white text-xs sm:text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/20"
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-1"
aria-label={showPassword ? 'Hide password' : 'Show password'}
>
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
</div>
)}
<button
type="submit"
disabled={loading}
className="w-full h-11 inline-flex items-center justify-center gap-2 rounded-xl bg-slate-900 hover:bg-accent text-white font-sans font-semibold text-xs sm:text-sm transition-all shadow-xs hover:shadow-md cursor-pointer active:scale-[0.99] disabled:opacity-50 mt-1"
>
{loading ? (
<Loader2 className="w-4 h-4 animate-spin text-white" />
) : (
<>
<span>
{authModalMode === 'signin' && 'Sign In'}
{authModalMode === 'signup' && 'Create Account'}
{authModalMode === 'reset' && 'Send Reset Link'}
</span>
<ArrowRight className="w-4 h-4" />
</>
)}
</button>
</form>
{/* Footer Mode Switcher */}
<div className="mt-6 text-center text-xs text-slate-500 font-sans">
{authModalMode === 'signin' && (
<p>
Don&apos;t have an account?{' '}
<button
type="button"
onClick={() => openAuthModal('signup')}
className="font-semibold text-accent hover:underline cursor-pointer"
>
Sign up
</button>
</p>
)}
{authModalMode === 'signup' && (
<p>
Already have an account?{' '}
<button
type="button"
onClick={() => openAuthModal('signin')}
className="font-semibold text-accent hover:underline cursor-pointer"
>
Sign in
</button>
</p>
)}
{authModalMode === 'reset' && (
<p>
Remember your password?{' '}
<button
type="button"
onClick={() => openAuthModal('signin')}
className="font-semibold text-accent hover:underline cursor-pointer"
>
Back to Sign in
</button>
</p>
)}
</div>
</div>
</div>
);
}
-159
View File
@@ -1,159 +0,0 @@
'use client';
import React, { useState, useRef, useEffect } from 'react';
import Link from 'next/link';
import {
User as UserIcon,
LogOut,
Sparkles,
ChevronDown,
CheckCircle2,
AlertCircle,
ExternalLink,
} from 'lucide-react';
import { useAuth } from '@/lib/firebase/AuthContext';
export function UserMenu() {
const { user, loading, openAuthModal, logout } = useAuth();
const [dropdownOpen, setDropdownOpen] = useState(false);
const dropdownRef = useRef<HTMLDivElement>(null);
// Close dropdown on click outside
useEffect(() => {
if (!dropdownOpen) return;
const handleClickOutside = (e: MouseEvent) => {
if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
setDropdownOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, [dropdownOpen]);
// Close on Escape key
useEffect(() => {
if (!dropdownOpen) return;
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') setDropdownOpen(false);
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [dropdownOpen]);
if (loading) {
return (
<div className="w-8 h-8 rounded-full bg-slate-200/80 animate-pulse shrink-0" />
);
}
if (!user) {
return (
<button
type="button"
onClick={() => openAuthModal('signin')}
className="inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-full text-xs sm:text-sm font-sans font-semibold text-slate-700 hover:text-slate-950 bg-paper-2/90 hover:bg-paper-hi border border-rule transition-colors cursor-pointer active:scale-[0.98]"
aria-label="Sign in to your account"
>
<UserIcon className="w-3.5 h-3.5 text-accent" />
<span>Sign In</span>
</button>
);
}
const initial = (user.displayName || user.email || 'U').charAt(0).toUpperCase();
return (
<div className="relative shrink-0" ref={dropdownRef}>
<button
type="button"
onClick={() => setDropdownOpen(!dropdownOpen)}
className="inline-flex items-center gap-2 p-1 pr-2 rounded-full border border-rule bg-paper-hi hover:bg-slate-50 transition-colors shadow-2xs cursor-pointer focus:outline-none focus:ring-2 focus:ring-accent/20"
aria-expanded={dropdownOpen}
aria-haspopup="true"
aria-label="User account menu"
>
{user.photoURL ? (
<img
src={user.photoURL}
alt={user.displayName || 'User profile'}
className="w-7 h-7 rounded-full object-cover border border-slate-200"
/>
) : (
<div className="w-7 h-7 rounded-full bg-accent/15 text-accent font-sans font-bold text-xs flex items-center justify-center border border-accent/20">
{initial}
</div>
)}
<span className="hidden sm:inline text-xs font-sans font-medium text-slate-800 max-w-[100px] truncate">
{user.displayName || user.email?.split('@')[0]}
</span>
<ChevronDown className={`w-3.5 h-3.5 text-slate-400 transition-transform ${dropdownOpen ? 'rotate-180' : ''}`} />
</button>
{dropdownOpen && (
<div
className="absolute right-0 mt-2 w-64 rounded-2xl bg-paper-hi border border-rule shadow-2xl p-2 z-50 animate-in fade-in-0 zoom-in-95 duration-150"
role="menu"
>
{/* User Profile Summary */}
<div className="p-3 border-b border-rule">
<div className="font-semibold text-xs text-slate-900 truncate">
{user.displayName || 'Studio Member'}
</div>
<div className="text-[11px] font-mono text-slate-500 truncate mt-0.5">
{user.email}
</div>
{user.emailVerified ? (
<span className="inline-flex items-center gap-1 text-[10px] text-emerald-600 mt-1.5 font-medium">
<CheckCircle2 className="w-3 h-3" />
<span>Verified Account</span>
</span>
) : (
<span className="inline-flex items-center gap-1 text-[10px] text-amber-600 mt-1.5 font-medium">
<AlertCircle className="w-3 h-3" />
<span>Unverified Email</span>
</span>
)}
</div>
{/* Quick Links */}
<div className="py-1">
<Link
href="/tools"
onClick={() => setDropdownOpen(false)}
className="flex items-center gap-2.5 px-3 py-2 rounded-xl text-xs font-sans text-slate-700 hover:bg-slate-100 hover:text-slate-950 transition-colors"
role="menuitem"
>
<Sparkles className="w-3.5 h-3.5 text-accent" />
<span>Studio Workspaces</span>
</Link>
<Link
href="/apps"
onClick={() => setDropdownOpen(false)}
className="flex items-center gap-2.5 px-3 py-2 rounded-xl text-xs font-sans text-slate-700 hover:bg-slate-100 hover:text-slate-950 transition-colors"
role="menuitem"
>
<ExternalLink className="w-3.5 h-3.5 text-slate-400" />
<span>Mobile App Suite</span>
</Link>
</div>
{/* Sign Out */}
<div className="pt-1 border-t border-rule">
<button
type="button"
onClick={async () => {
setDropdownOpen(false);
await logout();
}}
className="w-full flex items-center gap-2.5 px-3 py-2 rounded-xl text-xs font-sans text-rose-600 hover:bg-rose-50 transition-colors cursor-pointer font-medium"
role="menuitem"
>
<LogOut className="w-3.5 h-3.5" />
<span>Sign Out</span>
</button>
</div>
</div>
)}
</div>
);
}
+15
View File
@@ -13,6 +13,7 @@ import {
} from 'lucide-react';
import { ToolItem, AppItem, VariantSpec, resolveLocalised } from '@/types';
import { CardBeforeAfterSlider } from '../ui/CardBeforeAfterSlider';
import { TurnstileWidget } from '@/components/turnstile/TurnstileWidget';
interface TryItWidgetProps {
tool: ToolItem;
@@ -43,6 +44,7 @@ export function TryItWidget({
const [status, setStatus] = useState<'idle' | 'selected' | 'processing' | 'success' | 'limit' | 'error' | 'unavailable'>('idle');
const [errorMessage, setErrorMessage] = useState<string>('');
const [remainingTries, setRemainingTries] = useState<number>(tool.tryIt?.limits?.perDay || 5);
const [turnstileToken, setTurnstileToken] = useState<string>('');
const [isDragOver, setIsDragOver] = useState<boolean>(false);
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -125,6 +127,10 @@ export function TryItWidget({
formData.append('variant', activeVariant);
}
if (turnstileToken) {
formData.append('cf-turnstile-response', turnstileToken);
}
const response = await fetch(`/api/try/${tool.id}`, {
method: 'POST',
body: formData,
@@ -316,6 +322,15 @@ export function TryItWidget({
</div>
)}
<div className="py-2 flex justify-center">
<TurnstileWidget
onVerify={(tok) => setTurnstileToken(tok)}
onExpire={() => setTurnstileToken('')}
theme="auto"
size="flexible"
/>
</div>
<button
type="button"
onClick={runTryIt}
+18 -1
View File
@@ -36,6 +36,7 @@ import { ImageCropper } from './ImageCropper';
import { PostResultAppHandoff } from './PostResultAppHandoff';
import { AnimatedShinyText } from '@/components/magicui/animated-shiny-text';
import { BorderBeam } from '@/components/magicui/border-beam';
import { TurnstileWidget, TurnstileWidgetRef } from '@/components/turnstile/TurnstileWidget';
interface DynamicToolWorkspaceProps {
tool: ToolItem;
@@ -110,6 +111,8 @@ export function DynamicToolWorkspace({
const [errorMessage, setErrorMessage] = useState<string>('');
const [remainingTries, setRemainingTries] = useState<number>(tool.tryIt?.limits?.perDay || 5);
const [hasDownloadedResult, setHasDownloadedResult] = useState<boolean>(false);
const [turnstileToken, setTurnstileToken] = useState<string>('');
const turnstileRef = useRef<TurnstileWidgetRef>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const secondaryFileInputRef = useRef<HTMLInputElement>(null);
@@ -326,6 +329,11 @@ export function DynamicToolWorkspace({
}
}
// Attach Cloudflare Turnstile token for human verification
if (turnstileToken) {
formData.append('cf-turnstile-response', turnstileToken);
}
const res = await fetch(`/api/try/${tool.id}`, {
method: 'POST',
body: formData,
@@ -793,7 +801,16 @@ export function DynamicToolWorkspace({
</div>
{/* Right: Massive High-Visibility Main Process Button with Dynamic Server-backed Quota Icon */}
<div className="w-full sm:w-auto order-1 sm:order-2">
<div className="w-full sm:w-auto order-1 sm:order-2 flex flex-col items-center sm:items-end gap-3">
{/* Cloudflare Turnstile Human Verification Widget */}
<TurnstileWidget
ref={turnstileRef}
onVerify={(tok) => setTurnstileToken(tok)}
onExpire={() => setTurnstileToken('')}
theme="auto"
size="flexible"
/>
<button
type="button"
onClick={handleExecute}
@@ -0,0 +1,177 @@
'use client';
import React, { useEffect, useRef, useState, useImperativeHandle, forwardRef } from 'react';
import { ShieldCheck, Loader2 } from 'lucide-react';
declare global {
interface Window {
turnstile?: {
render: (
container: string | HTMLElement,
params: {
sitekey: string;
callback?: (token: string) => void;
'error-callback'?: (error: any) => void;
'expired-callback'?: () => void;
theme?: 'light' | 'dark' | 'auto';
size?: 'normal' | 'compact' | 'flexible';
action?: string;
appearance?: 'always' | 'execute' | 'interaction-only';
}
) => string;
reset: (widgetId?: string) => void;
remove: (widgetId?: string) => void;
};
onTurnstileLoaded?: () => void;
}
}
// Official Cloudflare test site key that always passes (for dev / testing)
export const CLOUDFLARE_TEST_SITE_KEY_ALWAYS_PASS = '1x00000000000000000000AA';
export interface TurnstileWidgetRef {
reset: () => void;
}
export interface TurnstileWidgetProps {
onVerify: (token: string) => void;
onExpire?: () => void;
onError?: (err: any) => void;
theme?: 'light' | 'dark' | 'auto';
size?: 'normal' | 'compact' | 'flexible';
action?: string;
className?: string;
}
export const TurnstileWidget = forwardRef<TurnstileWidgetRef, TurnstileWidgetProps>(
function TurnstileWidget(
{
onVerify,
onExpire,
onError,
theme = 'auto',
size = 'normal',
action = 'ai-tool-execution',
className = '',
},
ref
) {
const containerRef = useRef<HTMLDivElement>(null);
const widgetIdRef = useRef<string | null>(null);
const [isScriptLoaded, setIsScriptLoaded] = useState(false);
const [isVerified, setIsVerified] = useState(false);
const siteKey =
process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY || CLOUDFLARE_TEST_SITE_KEY_ALWAYS_PASS;
useImperativeHandle(ref, () => ({
reset: () => {
setIsVerified(false);
if (widgetIdRef.current && window.turnstile) {
window.turnstile.reset(widgetIdRef.current);
}
},
}));
// Dynamically inject Cloudflare Turnstile script once
useEffect(() => {
if (typeof window === 'undefined') return;
if (window.turnstile) {
setIsScriptLoaded(true);
return;
}
const scriptId = 'cloudflare-turnstile-script';
let script = document.getElementById(scriptId) as HTMLScriptElement | null;
if (!script) {
script = document.createElement('script');
script.id = scriptId;
script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
script.async = true;
script.defer = true;
script.onload = () => {
setIsScriptLoaded(true);
};
document.head.appendChild(script);
} else {
const interval = setInterval(() => {
if (window.turnstile) {
setIsScriptLoaded(true);
clearInterval(interval);
}
}, 100);
return () => clearInterval(interval);
}
}, []);
// Render Turnstile widget once container and script are ready
useEffect(() => {
if (!isScriptLoaded || !containerRef.current || !window.turnstile) return;
// Clean up any previous widget in this container
if (widgetIdRef.current) {
try {
window.turnstile.remove(widgetIdRef.current);
} catch {
// ignore
}
widgetIdRef.current = null;
}
try {
const id = window.turnstile.render(containerRef.current, {
sitekey: siteKey,
theme,
size,
action,
callback: (token: string) => {
setIsVerified(true);
onVerify(token);
},
'expired-callback': () => {
setIsVerified(false);
if (onExpire) onExpire();
},
'error-callback': (err: any) => {
setIsVerified(false);
if (onError) onError(err);
},
});
widgetIdRef.current = id;
} catch (err) {
console.error('[Turnstile] Failed to render widget:', err);
}
return () => {
if (widgetIdRef.current && window.turnstile) {
try {
window.turnstile.remove(widgetIdRef.current);
} catch {
// ignore
}
widgetIdRef.current = null;
}
};
}, [isScriptLoaded, siteKey, theme, size, action, onVerify, onExpire, onError]);
return (
<div className={`turnstile-wrapper flex flex-col items-center gap-1.5 ${className}`}>
<div ref={containerRef} className="min-h-[65px] flex items-center justify-center" />
{/* Verification Status Micro-badge */}
<div className="flex items-center gap-1 text-[11px] text-ink-2 font-sans select-none">
<ShieldCheck className={`w-3.5 h-3.5 ${isVerified ? 'text-emerald-500' : 'text-blue-500'}`} />
<span>
{isVerified ? (
<span className="text-emerald-600 font-medium">Human verification confirmed</span>
) : (
<span>Protected by Cloudflare Turnstile</span>
)}
</span>
</div>
</div>
);
}
);
+1 -7
View File
@@ -20,7 +20,6 @@ import {
import { SiteConfig, CategoryItem, resolveLocalised } from '@/types';
import { BrandLogo } from './BrandLogo';
import { RainbowButton } from '@/components/magicui/rainbow-button';
import { UserMenu } from '@/components/auth/UserMenu';
interface NavbarProps {
config: SiteConfig;
@@ -148,9 +147,8 @@ export function Navbar({ config, currentLocale, categories = [], totalToolsCount
})}
</nav>
{/* Right CTA Actions from JSON + User Authentication */}
{/* Right CTA Actions from JSON */}
<div className="hidden md:flex items-center gap-3 relative z-20 flex-shrink-0">
<UserMenu />
<RainbowButton href={ctaHref}>
<span>{ctaLabel}</span>
<ArrowRight className="w-3.5 h-3.5 ml-1 inline" aria-hidden="true" />
@@ -210,10 +208,6 @@ export function Navbar({ config, currentLocale, categories = [], totalToolsCount
</nav>
<div className="pt-6 border-t border-rule space-y-3">
<div className="flex items-center justify-between pb-3 border-b border-rule/70">
<span className="text-xs font-semibold text-slate-700">Studio Account</span>
<UserMenu />
</div>
<RainbowButton
href={ctaHref}
onClick={() => setMobileMenuOpen(false)}