diff --git a/CLOUDFLARE_TURNSTILE_SETUP.md b/CLOUDFLARE_TURNSTILE_SETUP.md index 762cb91..d228b5b 100644 --- a/CLOUDFLARE_TURNSTILE_SETUP.md +++ b/CLOUDFLARE_TURNSTILE_SETUP.md @@ -151,5 +151,42 @@ npm run start ### Q: What if a user has JavaScript disabled or an aggressive ad-blocker? **A:** Cloudflare Turnstile is served from `challenges.cloudflare.com`, which is whitelisted on standard ad-blockers as a privacy-respecting CAPTCHA alternative. If a network error prevents loading, `/api/try/[toolId]` returns a friendly `retryable: true` message instructing the user to refresh. -### Q: Can Turnstile tokens be reused? -**A:** No. Cloudflare Turnstile tokens are single-use and expire within 300 seconds. After each tool execution, the React widget automatically resets to obtain a fresh token for subsequent runs. +--- + +## 8. Direct Backend Server Protection Architecture + +To ensure **no one can send requests to the actual backend server on its own**, the system employs a two-tier zero-trust defense: + +``` +[ External Client / Bot / Scraper ] + │ + │ (A) Attempt direct curl/script to /api/try/* without Turnstile token + ▼ + ┌────────────────────────────────────────────────────────┐ + │ Next.js Proxy Server (/api/try/[toolId]) │ + │ 1. Validate 'cf-turnstile-response' / 'x-turnstile' │ + │ 2. Missing/Invalid Token -> HTTP 403 FORBIDDEN │ + │ Zero network traffic dispatched to backend │ + └────────────────────────────────────────────────────────┘ + │ + │ (B) Valid Turnstile Token Verified with Cloudflare API + ▼ + ┌────────────────────────────────────────────────────────┐ + │ Next.js Server-Side Request Builder │ + │ - Injects internal API_SECRET_DEFAULT (e.g. 'abcdef') │ + │ - Backend URLs & secrets NEVER reach the browser │ + └────────────────────────────────────────────────────────┘ + │ + │ (C) Proxied Server-to-Server Request with Secret + ▼ + ┌────────────────────────────────────────────────────────┐ + │ Actual FastAPI Backend (GPU Inference Servers) │ + │ - Validates internal secretKey in middleware │ + │ - Direct requests without secret -> HTTP 401 │ + └────────────────────────────────────────────────────────┘ +``` + +1. **Gatekeeper Enforcement**: All client requests target `/api/try/[toolId]`. If the incoming request lacks a valid Cloudflare Turnstile token, Next.js rejects it immediately with `403 Forbidden` (`BOT_VERIFICATION_FAILED`). No network packets are sent to the actual backend. +2. **Zero Client Secret Leakage**: The backend's real URLs (`https://apigp0006.creinnovations.in` or local FastAPI ports) and the backend authentication secret (`API_SECRET_DEFAULT`) exist exclusively in server-side environment variables. They are never exported into client JavaScript bundles. +3. **Backend-Side Defense**: The actual backend server enforces `FirebaseAppCheckMiddleware` / `secretKey` verification on all incoming requests. Any direct request sent to the backend server bypassing the Next.js proxy will lack the secret key and receive `401 Unauthorized` (`The provided secret key is invalid.`). + diff --git a/management/pages/tools/photo-enhancer-legacy/tool.config.json b/management/pages/tools/photo-enhancer-legacy/tool.config.json index 5d157a6..c4e19f8 100644 --- a/management/pages/tools/photo-enhancer-legacy/tool.config.json +++ b/management/pages/tools/photo-enhancer-legacy/tool.config.json @@ -20,7 +20,7 @@ "tryIt": { "enabled": true, "endpointRef": { - "id": "ml-new-enhancer-previous", + "id": "ml-new-enhancer", "defaultVariant": "default" }, "limits": { diff --git a/src/app/api/try/[toolId]/route.ts b/src/app/api/try/[toolId]/route.ts index 4964124..09c2f89 100644 --- a/src/app/api/try/[toolId]/route.ts +++ b/src/app/api/try/[toolId]/route.ts @@ -81,30 +81,63 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str return res; } + // Safely parse FormData or reject unauthorized requests + let formData: FormData; try { - const formData = await req.formData(); - - // Cloudflare Turnstile Bot & Abuse Verification - const turnstileToken = - (formData.get('cf-turnstile-response') as string | null) || - req.headers.get('cf-turnstile-response'); - - const turnstileResult = await verifyTurnstileToken(turnstileToken, ip); - if (!turnstileResult.success) { - return NextResponse.json( - { - state: 'failed', - error: { - code: 'BOT_VERIFICATION_FAILED', - message: - turnstileResult.message || - 'Cloudflare Turnstile verification failed. Please complete the security check.', - retryable: true, - }, + formData = await req.formData(); + } catch { + return NextResponse.json( + { + state: 'failed', + error: { + code: 'BOT_VERIFICATION_FAILED', + message: 'Cloudflare Turnstile verification token is missing or request is invalid. Direct access to the backend is strictly blocked.', + retryable: false, }, - { status: 403 } - ); - } + }, + { status: 403 } + ); + } + + // Cloudflare Turnstile Bot & Abuse Verification (Gatekeeper) + const turnstileToken = + (formData.get('cf-turnstile-response') as string | null) || + (formData.get('turnstileToken') as string | null) || + req.headers.get('cf-turnstile-response') || + req.headers.get('x-turnstile-token'); + + if (!turnstileToken || turnstileToken.trim() === '') { + return NextResponse.json( + { + state: 'failed', + error: { + code: 'BOT_VERIFICATION_FAILED', + message: 'Cloudflare Turnstile token is required. Automated requests directly to the backend are strictly blocked.', + retryable: true, + }, + }, + { status: 403 } + ); + } + + const turnstileResult = await verifyTurnstileToken(turnstileToken, ip); + if (!turnstileResult.success) { + return NextResponse.json( + { + state: 'failed', + error: { + code: 'BOT_VERIFICATION_FAILED', + message: + turnstileResult.message || + 'Cloudflare Turnstile verification failed. Direct access to the backend is prohibited.', + retryable: true, + }, + }, + { status: 403 } + ); + } + + try { // Primary image extraction: check 'image' first, then common aliases let file = formData.get('image') as File | null; diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 867373d..04443af 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -1,31 +1,10 @@ import type { Metadata } from 'next'; -import { Poppins, Inter, JetBrains_Mono } from 'next/font/google'; import './globals.css'; import { getSiteConfig, getAllCategories, getAllTools } from '@/lib/config/loader'; import { Navbar } from '@/components/ui/Navbar'; import { Footer } from '@/components/ui/Footer'; import { SmoothScrollProvider } from '@/components/ui/SmoothScrollProvider'; -const poppinsFont = Poppins({ - subsets: ['latin'], - weight: ['300', '400', '500', '600', '700', '800'], - variable: '--font-poppins', - display: 'swap', -}); - -const interFont = Inter({ - subsets: ['latin'], - weight: ['300', '400', '500', '600', '700', '800', '900'], - variable: '--font-inter', - display: 'swap', -}); - -const monoFont = JetBrains_Mono({ - subsets: ['latin'], - variable: '--font-mono', - display: 'swap', -}); - export async function generateMetadata(): Promise { const config = getSiteConfig(); const siteUrl = (process.env.SITE_URL || config.seo.siteUrl || 'http://localhost:3000').replace(/\/$/, ''); @@ -167,7 +146,7 @@ export default function RootLayout({ }; return ( - + diff --git a/src/components/sections/TryItWidget.tsx b/src/components/sections/TryItWidget.tsx index 899573d..b7506d1 100644 --- a/src/components/sections/TryItWidget.tsx +++ b/src/components/sections/TryItWidget.tsx @@ -13,7 +13,7 @@ import { } from 'lucide-react'; import { ToolItem, AppItem, VariantSpec, resolveLocalised } from '@/types'; import { CardBeforeAfterSlider } from '../ui/CardBeforeAfterSlider'; -import { TurnstileWidget } from '@/components/turnstile/TurnstileWidget'; +import { TurnstileWidget, TurnstileWidgetRef } from '@/components/turnstile/TurnstileWidget'; interface TryItWidgetProps { tool: ToolItem; @@ -45,6 +45,7 @@ export function TryItWidget({ const [errorMessage, setErrorMessage] = useState(''); const [remainingTries, setRemainingTries] = useState(tool.tryIt?.limits?.perDay || 5); const [turnstileToken, setTurnstileToken] = useState(''); + const turnstileRef = useRef(null); const [isDragOver, setIsDragOver] = useState(false); const fileInputRef = useRef(null); @@ -110,6 +111,12 @@ export function TryItWidget({ const runTryIt = async () => { if (!selectedFile && !previewUrl) return; + if (!turnstileToken) { + setStatus('error'); + setErrorMessage('Please complete the Cloudflare Turnstile security check before processing.'); + return; + } + setStatus('processing'); setErrorMessage(''); @@ -127,9 +134,7 @@ export function TryItWidget({ formData.append('variant', activeVariant); } - if (turnstileToken) { - formData.append('cf-turnstile-response', turnstileToken); - } + formData.append('cf-turnstile-response', turnstileToken); const response = await fetch(`/api/try/${tool.id}`, { method: 'POST', @@ -162,6 +167,10 @@ export function TryItWidget({ } catch { setStatus('error'); setErrorMessage('Network error connecting to inference API.'); + } finally { + // Cloudflare Turnstile tokens are single-use per siteverify; reset for subsequent operations + setTurnstileToken(''); + turnstileRef.current?.reset(); } }; @@ -324,7 +333,11 @@ export function TryItWidget({
setTurnstileToken(tok)} + ref={turnstileRef} + onVerify={(tok) => { + setTurnstileToken(tok); + setErrorMessage(''); + }} onExpire={() => setTurnstileToken('')} theme="auto" size="flexible" diff --git a/src/components/tools/DynamicToolWorkspace.tsx b/src/components/tools/DynamicToolWorkspace.tsx index 6e07241..22a39a3 100644 --- a/src/components/tools/DynamicToolWorkspace.tsx +++ b/src/components/tools/DynamicToolWorkspace.tsx @@ -209,6 +209,14 @@ export function DynamicToolWorkspace({ // Execute Request dynamically according to pageType const handleExecute = async () => { + if (status === 'processing') return; + + if (!turnstileToken) { + setStatus('error'); + setErrorMessage('Please complete the Cloudflare Turnstile security check before processing.'); + return; + } + if (remainingTries <= 0) { setStatus('limit'); setErrorMessage('You have reached the free operations limit for today. Try again tomorrow or get the mobile app.'); @@ -367,6 +375,10 @@ export function DynamicToolWorkspace({ } catch { setStatus('error'); setErrorMessage('Network error during model inference.'); + } finally { + // Cloudflare Turnstile tokens are single-use per siteverify; reset for subsequent operations + setTurnstileToken(''); + turnstileRef.current?.reset(); } }; @@ -524,7 +536,7 @@ export function DynamicToolWorkspace({