diff --git a/FIREBASE_SECURITY_SETUP.md b/FIREBASE_SECURITY_SETUP.md new file mode 100644 index 0000000..9800beb --- /dev/null +++ b/FIREBASE_SECURITY_SETUP.md @@ -0,0 +1,367 @@ +# Firebase Security & Request Authenticity Guide + +This guide details how to secure the **Next.js Frontend**, **API Gateway Routes** (`/api/try/[toolId]`), and downstream **GPU Model Endpoints** against bots, unauthorized scrapers, curl/Postman scripts, and quota abuse using **Firebase App Check** and **Firebase Authentication**. + +--- + +## 1. Security Architecture Overview + +``` +┌────────────────────────────────────────────────────────┐ +│ Client Browser │ +│ 1. Firebase App Check (Attestation: Is it our app?) │ +│ 2. Firebase Auth (Identity: Who is the user?) │ +└───────────────────────┬────────────────────────────────┘ + │ + │ 1. Header: X-Firebase-AppCheck: + │ 2. Header: Authorization: Bearer + ▼ +┌────────────────────────────────────────────────────────┐ +│ Next.js API Gateway (/api/try/[toolId]) │ +│ ✓ adminAppCheck.verifyToken() → Blocks curl/bots │ +│ ✓ adminAuth.verifyIdToken() → Verifies user identity│ +│ ✓ Rate-Limiter (User UID & IP Quota Enforcer) │ +└───────────────────────┬────────────────────────────────┘ + │ + │ Internal Secret Key (never sent to browser) + ▼ +┌────────────────────────────────────────────────────────┐ +│ Remote GPU Model Server (creinnovations.in) │ +└────────────────────────────────────────────────────────┘ +``` + +### Why Dual Defense? +1. **Firebase App Check (Device & App Attestation)**: + - Proves the incoming HTTP request actually originated from **your legitimate web app running in a genuine browser**, not a headless bot, Postman, or `curl`. + - Uses **Google reCAPTCHA Enterprise** (invisible, frictionless risk analysis). +2. **Firebase Authentication (User Identity & Quota Control)**: + - Issues a cryptographically signed JWT (`idToken`). + - Supports **Anonymous Authentication** (1-click trial without requiring email/password signup) or OAuth (Google, GitHub, Email). + - Allows strictly tracking per-user daily limits (e.g., 5 free tries/day) tied to a cryptographically validated `uid`. + +--- + +## 2. Firebase Console Configuration + +### Step A: Create Firebase Project +1. Open the [Firebase Console](https://console.firebase.google.com/). +2. Click **Add project** (or select your existing project, e.g. `cre-photo-ai`). +3. Under **Project Overview**, click the **Web icon ()** to register a Web App. +4. Name your web app (e.g. `Photo Tools Web`) and copy the `firebaseConfig` object. + +### Step B: Enable Firebase App Check with reCAPTCHA Enterprise +1. In Firebase Console, navigate to **Build → App Check** in the left sidebar. +2. Under the **Apps** tab, find your registered Web App and click **Register**. +3. Select **reCAPTCHA Enterprise** (recommended) or **reCAPTCHA v3**. +4. In the Google Cloud / reCAPTCHA configuration: + - Add your authorized domains: `localhost`, `127.0.0.1`, and your production domain (e.g., `creinnovations.in`). + - Copy the public **Site Key**. +5. Save the configuration in Firebase App Check. + +### Step C: Enable Firebase Authentication +1. In Firebase Console, navigate to **Build → Authentication**. +2. Click **Get Started**, then go to the **Sign-in method** tab. +3. Enable **Anonymous**: + - Turn on the toggle and click **Save**. + *(This allows instant trial generation for first-time visitors without friction, while still giving each visitor a unique cryptographic `uid`)*. +4. (Optional) Enable **Google** or **Email/Password** for logged-in accounts. + +### Step D: Generate Backend Service Account Key +1. Go to **Project Settings** (gear icon) → **Service accounts** tab. +2. Verify **Node.js** is selected. +3. Click **Generate new private key**, then confirm **Generate key**. +4. A JSON file will be downloaded containing: + - `project_id` + - `client_email` + - `private_key` + +--- + +## 3. Environment Variables Setup + +Add the following values into your `.env.local` file: + +```env +# ============================================================================== +# Client-Side Firebase Keys (Public - safe in browser) +# ============================================================================== +NEXT_PUBLIC_FIREBASE_API_KEY="AIzaSy..." +NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN="cre-photo-ai.firebaseapp.com" +NEXT_PUBLIC_FIREBASE_PROJECT_ID="cre-photo-ai" +NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET="cre-photo-ai.appspot.com" +NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID="123456789012" +NEXT_PUBLIC_FIREBASE_APP_ID="1:123456789012:web:abcdef123456" +NEXT_PUBLIC_RECAPTCHA_SITE_KEY="6L..." + +# ============================================================================== +# Server-Side Firebase Admin Keys (Private - NEVER expose to browser) +# ============================================================================== +FIREBASE_PROJECT_ID="cre-photo-ai" +FIREBASE_CLIENT_EMAIL="firebase-adminsdk-xxxxx@cre-photo-ai.iam.gserviceaccount.com" +FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC...\n-----END PRIVATE KEY-----\n" + +# Secret Key for Remote Model Cluster (Injected only on server) +API_SECRET_DEFAULT="abcdef" +``` + +--- + +## 4. Frontend Client Implementation + +### 1. Install Firebase Client SDK +```bash +npm install firebase +``` + +### 2. Client Initialization (`src/lib/firebase/client.ts`) +```typescript +import { initializeApp, getApps, getApp } from 'firebase/app'; +import { getAuth, signInAnonymously } from 'firebase/auth'; +import { initializeAppCheck, ReCaptchaEnterpriseProvider, getToken } from 'firebase/app-check'; + +const firebaseConfig = { + apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY, + authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN, + projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID, + storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET, + messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID, + appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID, +}; + +// Initialize App (Singleton) +export const app = !getApps().length ? initializeApp(firebaseConfig) : getApp(); +export const auth = getAuth(app); + +let appCheckInstance: any = null; + +export function initAppCheck() { + if (typeof window === 'undefined' || appCheckInstance) return; + + // In development, enable debug token printing in browser console + if (process.env.NODE_ENV === 'development') { + // @ts-ignore + self.FIREBASE_APPCHECK_DEBUG_TOKEN = true; + } + + const siteKey = process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY; + if (!siteKey) return; + + try { + appCheckInstance = initializeAppCheck(app, { + provider: new ReCaptchaEnterpriseProvider(siteKey), + isTokenAutoRefreshEnabled: true, + }); + } catch (err) { + console.warn('[Firebase AppCheck] Init warning:', err); + } +} + +/** + * Returns security headers for genuine request verification: + * - Authorization: Bearer + * - X-Firebase-AppCheck: + */ +export async function getSecurityHeaders(): Promise> { + const headers: Record = {}; + + // 1. Firebase Auth: Ensure user session (anonymous or logged-in) + try { + let user = auth.currentUser; + if (!user) { + const cred = await signInAnonymously(auth); + user = cred.user; + } + const idToken = await user.getIdToken(); + headers['Authorization'] = `Bearer ${idToken}`; + } catch (err) { + console.error('[Firebase Auth] Failed to obtain ID token:', err); + } + + // 2. Firebase App Check: Obtain attestation token + if (appCheckInstance) { + try { + const appCheckResult = await getToken(appCheckInstance, /* forceRefresh */ false); + headers['X-Firebase-AppCheck'] = appCheckResult.token; + } catch (err) { + console.warn('[Firebase AppCheck] Failed to get attestation token:', err); + } + } + + return headers; +} +``` + +### 3. Send Security Headers in API Calls +In [`src/components/tools/DynamicToolWorkspace.tsx`](file:///home/creserver/Desktop/WEBB/src/components/tools/DynamicToolWorkspace.tsx): + +```typescript +import { getSecurityHeaders } from '@/lib/firebase/client'; + +async function handleRunInference() { + const securityHeaders = await getSecurityHeaders(); + + const response = await fetch(`/api/try/${tool.slug}`, { + method: 'POST', + headers: { + ...securityHeaders, + }, + body: formData, + }); + + if (!response.ok) { + const errorJson = await response.json(); + throw new Error(errorJson.error?.message || 'Processing failed'); + } + + const resultBlob = await response.blob(); + // Render result... +} +``` + +--- + +## 5. Backend Server Verification (`firebase-admin`) + +### 1. Install Firebase Admin SDK +```bash +npm install firebase-admin +``` + +### 2. Admin Initialization (`src/lib/firebase/admin.ts`) +```typescript +import * as admin from 'firebase-admin'; + +if (!admin.apps.length) { + const privateKey = process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n'); + admin.initializeApp({ + credential: admin.credential.cert({ + projectId: process.env.FIREBASE_PROJECT_ID, + clientEmail: process.env.FIREBASE_CLIENT_EMAIL, + privateKey: privateKey, + }), + }); +} + +export const adminAuth = admin.auth(); +export const adminAppCheck = admin.appCheck(); +``` + +### 3. Verification Guard (`src/lib/api/securityGuard.ts`) +```typescript +import { NextRequest } from 'next/server'; +import { adminAuth, adminAppCheck } from '@/lib/firebase/admin'; + +export interface VerifiedSecurityContext { + uid: string; + isAppCheckValid: boolean; +} + +export async function verifyRequestAuthenticity( + req: NextRequest +): Promise< + | { ok: true; context: VerifiedSecurityContext } + | { ok: false; status: number; code: string; message: string } +> { + const isDev = process.env.NODE_ENV === 'development'; + + // 1. App Check Verification (Device/Client attestation) + const appCheckToken = req.headers.get('X-Firebase-AppCheck'); + if (!appCheckToken && !isDev) { + return { + ok: false, + status: 401, + code: 'APP_CHECK_MISSING', + message: 'Missing device attestation token.', + }; + } + + if (appCheckToken) { + try { + await adminAppCheck.verifyToken(appCheckToken); + } catch (err) { + return { + ok: false, + status: 403, + code: 'APP_CHECK_INVALID', + message: 'Invalid or forged device attestation token.', + }; + } + } + + // 2. Auth ID Token Verification (User identity & cryptographic signature) + const authHeader = req.headers.get('Authorization') || ''; + const match = authHeader.match(/^Bearer\s+(.*)$/); + if (!match) { + return { + ok: false, + status: 401, + code: 'AUTH_TOKEN_MISSING', + message: 'Missing authentication token.', + }; + } + + const idToken = match[1]; + try { + const decodedToken = await adminAuth.verifyIdToken(idToken); + return { + ok: true, + context: { + uid: decodedToken.uid, + isAppCheckValid: true, + }, + }; + } catch (err) { + return { + ok: false, + status: 403, + code: 'AUTH_TOKEN_INVALID', + message: 'Authentication token is invalid or expired.', + }; + } +} +``` + +### 4. Integration into API Gateway Route +In [`src/app/api/try/[toolId]/route.ts`](file:///home/creserver/Desktop/WEBB/src/app/api/try/[toolId]/route.ts): + +```typescript +import { verifyRequestAuthenticity } from '@/lib/api/securityGuard'; + +export async function POST(req: NextRequest, { params }: { params: { toolId: string } }) { + // Step 1: Enforce Request Authenticity + const verification = await verifyRequestAuthenticity(req); + if (!verification.ok) { + return NextResponse.json( + { state: 'failed', error: { code: verification.code, message: verification.message } }, + { status: verification.status } + ); + } + + const { uid } = verification.context; + + // Step 2: Rate Limiting & User Quota based on verified UID + // (Prevents clearing cookies to bypass limits) + ... +``` + +--- + +## 6. How Remote GPU Servers Stay Protected + +1. **No Direct Remote Access**: The client browser never interacts with `https://apigp0006.creinnovations.in/`. +2. **Server-Side Secret Injection**: The `secretKey` (`abcdef`) is appended only within the Next.js server runtime ([`src/lib/api/requestBuilder.ts`](file:///home/creserver/Desktop/WEBB/src/lib/api/requestBuilder.ts)). +3. **Firewall / IP Whitelisting**: If your GPU server allows it, configure firewall rules (`iptables` / Security Groups) so port 8000 on the model server accepts incoming traffic **only from your Next.js server's IP address**. + +--- + +## 7. Local Development & Debugging + +When testing locally on `localhost:3000`: +1. When you run `npm run dev`, Firebase App Check will output a debug token in your browser console: + ``` + App Check debug token: 12345678-AAAA-BBBB-CCCC-1234567890AB. + ``` +2. Open **Firebase Console → App Check → Apps tab**. +3. Click the three dots (⋮) next to your Web App → **Manage debug tokens**. +4. Paste the debug token and label it `Local Dev`. +5. Now your local browser will pass App Check verification automatically. diff --git a/images_for_thumbnails/before/teeth_whitener.jpeg b/images_for_thumbnails/before/teeth_whitener.jpeg index 91fd9d7..a47e366 100644 Binary files a/images_for_thumbnails/before/teeth_whitener.jpeg and b/images_for_thumbnails/before/teeth_whitener.jpeg differ diff --git a/management/pages/home/sections/our-tools/teeth-whitener/after.jpg b/management/pages/home/sections/our-tools/teeth-whitener/after.jpg index c3e97af..966a680 100644 Binary files a/management/pages/home/sections/our-tools/teeth-whitener/after.jpg and b/management/pages/home/sections/our-tools/teeth-whitener/after.jpg differ diff --git a/management/pages/home/sections/our-tools/teeth-whitener/before.jpg b/management/pages/home/sections/our-tools/teeth-whitener/before.jpg index 1fe1358..1d5c776 100644 Binary files a/management/pages/home/sections/our-tools/teeth-whitener/before.jpg and b/management/pages/home/sections/our-tools/teeth-whitener/before.jpg differ diff --git a/management/pages/tools/page.config.json b/management/pages/tools/page.config.json index 0881f00..d64926c 100644 --- a/management/pages/tools/page.config.json +++ b/management/pages/tools/page.config.json @@ -23,7 +23,7 @@ "source": "all", "showCategoryFilter": true, "showSearch": true, - "columns": 2 + "columns": 3 } } ] diff --git a/management/pages/tools/teeth-whitener/media/after.jpg b/management/pages/tools/teeth-whitener/media/after.jpg index c3e97af..966a680 100644 Binary files a/management/pages/tools/teeth-whitener/media/after.jpg and b/management/pages/tools/teeth-whitener/media/after.jpg differ diff --git a/management/pages/tools/teeth-whitener/media/before.jpg b/management/pages/tools/teeth-whitener/media/before.jpg index 1fe1358..1d5c776 100644 Binary files a/management/pages/tools/teeth-whitener/media/before.jpg and b/management/pages/tools/teeth-whitener/media/before.jpg differ diff --git a/src/components/sections/RelatedToolsSection.tsx b/src/components/sections/RelatedToolsSection.tsx index 03e46fc..5a6b9da 100644 --- a/src/components/sections/RelatedToolsSection.tsx +++ b/src/components/sections/RelatedToolsSection.tsx @@ -32,7 +32,7 @@ export function RelatedToolsSection({ tools = [], locale = 'en' }: RelatedToolsS -
+
{tools.map((tool) => ( +
); @@ -303,14 +303,14 @@ function ToolCardImage({ tool, toolName }: { tool: ToolItem; toolName: string }) // 2. SINGLE IMAGE (Polaroid, etc.) if (media.type === 'single') { return ( -
+
{/* eslint-disable-next-line @next/next/no-img-element */} {toolName}
); @@ -323,7 +323,7 @@ function ToolCardImage({ tool, toolName }: { tool: ToolItem; toolName: string }) onPointerDown={handleContainerPointerDown} onPointerMove={handleContainerPointerMove} onPointerLeave={handleContainerPointerLeave} - className="relative w-full aspect-[4/3] rounded-xl overflow-hidden bg-paper-2 select-none cursor-ew-resize group/img shadow-inner touch-pan-y" + className="relative w-full aspect-square rounded-xl overflow-hidden bg-paper-2 select-none cursor-ew-resize group/img shadow-inner touch-pan-y" style={{ touchAction: 'pan-y' }} > {/* Enhanced / After Image (Underneath) */} @@ -333,7 +333,7 @@ function ToolCardImage({ tool, toolName }: { tool: ToolItem; toolName: string }) alt={`${toolName} after`} loading="lazy" decoding="async" - className="absolute inset-0 w-full h-full object-cover pointer-events-none" + className="absolute inset-0 w-full h-full object-cover object-top pointer-events-none" /> {/* Original / Before Image (Clipped overlay) */} @@ -350,7 +350,7 @@ function ToolCardImage({ tool, toolName }: { tool: ToolItem; toolName: string }) alt={`${toolName} before`} loading="lazy" decoding="async" - className="absolute inset-0 w-full h-full object-cover pointer-events-none" + className="absolute inset-0 w-full h-full object-cover object-top pointer-events-none" />
@@ -550,7 +550,7 @@ export function ToolGridSection({ {resolveLocalised(title, locale)} )} -
+
{tools.map((tool) => ( ))} @@ -912,7 +912,7 @@ export function ToolGridSection({
{searchResults.length > 0 ? ( -
+
{searchResults.map((tool) => ( ))} @@ -938,7 +938,7 @@ export function ToolGridSection({ ) : activeCategoryItem ? ( /* ================= SINGLE CATEGORY FOCUSED WORKSPACE (SHOWS ALL TOOLS IN CATEGORY) ================= */
-
+
{activeCategoryItem.tools.map((tool) => ( 8; + // In "All Tools" view, only 2 rows are visible (3 items per row * 2 rows = 6 tools) + const displayedTools = group.tools.slice(0, 6); + const hasMoreTools = group.tools.length > 6; return (
- {/* Tool Cards Grid: 4 items in a row, at most 2 rows (8 tools) visible */} -
+ {/* Tool Cards Grid: 3 items in a row, at most 2 rows (6 tools) visible */} +
{displayedTools.map((tool) => (