Files
webb/FIREBASE_SECURITY_SETUP.md
T

14 KiB

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: <appCheckToken>
                        │ 2. Header: Authorization: Bearer <idToken>
                        ▼
┌────────────────────────────────────────────────────────┐
│            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.
  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:

# ==============================================================================
# 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="[email protected]"
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

npm install firebase

2. Client Initialization (src/lib/firebase/client.ts)

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 <idToken>
 * - X-Firebase-AppCheck: <appCheckToken>
 */
export async function getSecurityHeaders(): Promise<Record<string, string>> {
  const headers: Record<string, string> = {};

  // 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:

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

npm install firebase-admin

2. Admin Initialization (src/lib/firebase/admin.ts)

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)

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:

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).
  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.