feat(security): replace Firebase with Cloudflare Turnstile bot verification
This commit is contained in:
+6
-17
@@ -31,21 +31,10 @@ CATALOG_ADMIN_SECRET=REPLACE_WITH_32_CHAR_HEX
|
|||||||
ALLOWED_ORIGIN=http://localhost:3000
|
ALLOWED_ORIGIN=http://localhost:3000
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Firebase Client SDK Configuration (Required for Live Client Auth)
|
# Cloudflare Turnstile Bot & Abuse Protection
|
||||||
# Obtain from: Firebase Console > Project Settings > General > Your apps (Web)
|
# Obtain from: Cloudflare Dashboard > Turnstile > Add Widget
|
||||||
|
# Test Site Key (Always Passes): 1x00000000000000000000AA
|
||||||
|
# Test Secret Key (Always Passes): 1x0000000000000000000000000000000AA
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
NEXT_PUBLIC_FIREBASE_API_KEY=your_api_key_here
|
NEXT_PUBLIC_TURNSTILE_SITE_KEY=your_cloudflare_turnstile_site_key
|
||||||
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your_project_id.firebaseapp.com
|
CLOUDFLARE_TURNSTILE_SECRET_KEY=your_cloudflare_turnstile_secret_key
|
||||||
NEXT_PUBLIC_FIREBASE_PROJECT_ID=your_project_id
|
|
||||||
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=your_project_id.appspot.com
|
|
||||||
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=your_messaging_sender_id
|
|
||||||
NEXT_PUBLIC_FIREBASE_APP_ID=1:your_app_id:web:your_web_id
|
|
||||||
NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID=G-XXXXXXXXXX
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Firebase Admin SDK Configuration (Required for Server Session Minting)
|
|
||||||
# Obtain from: Firebase Console > Project Settings > Service accounts > Generate new private key
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
FIREBASE_PROJECT_ID=your_project_id
|
|
||||||
FIREBASE_CLIENT_EMAIL=firebase-adminsdk-xxxxx@your_project_id.iam.gserviceaccount.com
|
|
||||||
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC....\n-----END PRIVATE KEY-----\n"
|
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# Cloudflare Turnstile Integration & Activation Guide
|
||||||
|
|
||||||
|
This document explains how to activate and manage **Cloudflare Turnstile** bot protection on the CRE Innovations Web Studio platform.
|
||||||
|
|
||||||
|
Firebase Authentication has been completely replaced with **Cloudflare Turnstile**, providing frictionless, privacy-preserving bot and abuse protection across all AI inference tools and forms.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ⚡ Quick Activation (2 Minutes)
|
||||||
|
|
||||||
|
To activate Cloudflare Turnstile, follow these simple steps:
|
||||||
|
|
||||||
|
### Step 1: Open Cloudflare Dashboard
|
||||||
|
1. Go to the [Cloudflare Dashboard](https://dash.cloudflare.com/).
|
||||||
|
2. Log in (or create a free Cloudflare account if you don't have one).
|
||||||
|
|
||||||
|
### Step 2: Create a Turnstile Widget
|
||||||
|
1. In the left navigation menu, click **Turnstile** (under Application Services).
|
||||||
|
2. Click **Add widget** (or **Add site**).
|
||||||
|
3. Fill in the widget details:
|
||||||
|
- **Widget name**: `CRE Innovations Studio` (or any name you prefer).
|
||||||
|
- **Domains**:
|
||||||
|
- Add `localhost` (for local development and testing).
|
||||||
|
- Add your production domain (e.g., `creinnovations.in` or `yourdomain.com`).
|
||||||
|
- Add staging / preview domains if applicable (e.g. `*.vercel.app`).
|
||||||
|
- **Widget Mode**:
|
||||||
|
- Select **Managed** *(Recommended)*: Cloudflare decides when to run an invisible background check vs. showing an interactive checkbox based on risk level.
|
||||||
|
- Or select **Non-interactive** / **Invisible** based on your security preference.
|
||||||
|
4. Click **Create**.
|
||||||
|
|
||||||
|
### Step 3: Copy Your Keys
|
||||||
|
Cloudflare will display two keys:
|
||||||
|
1. **Site Key** (Public, starts with `0x4AAAAAA...`)
|
||||||
|
2. **Secret Key** (Private, starts with `0x4AAAAAA...`)
|
||||||
|
|
||||||
|
### Step 4: Add Keys to `.env.local`
|
||||||
|
In the root directory of `WEBB` (and `WEBB_EDITOR` if running separately), open or create `.env.local` and add:
|
||||||
|
|
||||||
|
```env
|
||||||
|
# Cloudflare Turnstile Keys
|
||||||
|
NEXT_PUBLIC_TURNSTILE_SITE_KEY=your_copied_site_key_here
|
||||||
|
CLOUDFLARE_TURNSTILE_SECRET_KEY=your_copied_secret_key_here
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 5: Restart the Server
|
||||||
|
Restart the Next.js process:
|
||||||
|
```bash
|
||||||
|
npm run build && npm run start
|
||||||
|
```
|
||||||
|
Done! Cloudflare Turnstile is now active and protecting all AI inference calls against automated bots and scrapers.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🧪 Testing Locally (Zero Setup Test Keys)
|
||||||
|
|
||||||
|
Cloudflare provides official testing keys so you can test all scenarios immediately without needing a Cloudflare account:
|
||||||
|
|
||||||
|
| Scenario | Site Key (Public) | Secret Key (Server) | Expected Behavior |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Always Passes** | `1x00000000000000000000AA` | `1x0000000000000000000000000000000AA` | Automatically passes verification without interaction. |
|
||||||
|
| **Always Fails / Blocks** | `2x00000000000000000000AB` | `2x0000000000000000000000000000000AA` | Verification always fails; server rejects with HTTP 403. |
|
||||||
|
| **Interactive Challenge** | `3x00000000000000000000FF` | `1x0000000000000000000000000000000AA` | Forces user to click the verification checkbox. |
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> If neither `NEXT_PUBLIC_TURNSTILE_SITE_KEY` nor `CLOUDFLARE_TURNSTILE_SECRET_KEY` is set in `.env.local`, the app defaults to the **Always Passes** test key in development so you are never locked out during development.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🛡️ Architecture & Verification Flow
|
||||||
|
|
||||||
|
1. **Client**:
|
||||||
|
- The user opens a tool workspace (e.g. `/tools/blemish-remover`).
|
||||||
|
- The lightweight `<TurnstileWidget />` loads dynamically from `challenges.cloudflare.com`.
|
||||||
|
- Upon successful verification, a temporary token `cf-turnstile-response` is generated.
|
||||||
|
2. **Execution**:
|
||||||
|
- When the user clicks **Process / Run**, `cf-turnstile-response` is included in the multipart `FormData` sent to `/api/try/[toolId]`.
|
||||||
|
3. **Server Verification**:
|
||||||
|
- `/api/try/[toolId]` validates the token against `https://challenges.cloudflare.com/turnstile/v0/siteverify` using `CLOUDFLARE_TURNSTILE_SECRET_KEY`.
|
||||||
|
- If verification succeeds, GPU inference proceeds.
|
||||||
|
- If verification fails or is omitted by a bot, the request is immediately rejected with HTTP `403 BOT_VERIFICATION_FAILED`.
|
||||||
@@ -1,229 +0,0 @@
|
|||||||
# Complete Firebase Authentication Setup & Post-Implementation Guide
|
|
||||||
|
|
||||||
This comprehensive runbook details everything you need to do in the **Firebase Console**, **Google Cloud Platform**, and your **Hosting Environment** to take the authentication system live.
|
|
||||||
|
|
||||||
All code, cryptographic session handling, CSRF protections, UI modals, and fallback states are already fully implemented. Follow this checklist to complete the credentials and security setup.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 📋 Executive Checklist
|
|
||||||
|
|
||||||
- [ ] **Step 1:** Create or select your Firebase Project.
|
|
||||||
- [ ] **Step 2:** Enable Sign-In Methods (Google & Email/Password).
|
|
||||||
- [ ] **Step 3:** Configure Google Cloud OAuth Consent Screen (Production Mode).
|
|
||||||
- [ ] **Step 4:** Whitelist Authorized Domains.
|
|
||||||
- [ ] **Step 5:** Retrieve Client SDK Config & Paste into `.env.local`.
|
|
||||||
- [ ] **Step 6:** Generate Admin Service Account Private Key & Paste into `.env.local`.
|
|
||||||
- [ ] **Step 7:** Customize Authentication Email Templates.
|
|
||||||
- [ ] **Step 8:** Enable Account Enumeration Protection (Anti-Scraping).
|
|
||||||
- [ ] **Step 9:** Restart & Perform End-to-End Verification.
|
|
||||||
- [ ] **Step 10:** Production Deployment Setup (Vercel, Railway, VPS, etc.).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Firebase Project Setup
|
|
||||||
|
|
||||||
1. Navigate to the [Firebase Console](https://console.firebase.google.com/).
|
|
||||||
2. Click **Add project** (or select your existing project).
|
|
||||||
3. Name your project (e.g., `cre-innovations-studio`).
|
|
||||||
4. Google Analytics can be enabled or disabled based on your preference (if enabled, you'll receive a `NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID`).
|
|
||||||
5. Click **Create project** and wait for provisioning to complete.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Enable Authentication Providers
|
|
||||||
|
|
||||||
1. In the left navigation menu, go to **Build** > **Authentication**.
|
|
||||||
2. Click **Get Started** if Authentication is not yet activated.
|
|
||||||
3. In the **Sign-in method** tab:
|
|
||||||
- **Google**:
|
|
||||||
1. Click **Google** under Additional providers.
|
|
||||||
2. Toggle **Enable**.
|
|
||||||
3. Enter a **Public-facing name for project** (e.g., `CRE Innovations Studio`).
|
|
||||||
4. Select your **Project support email** from the dropdown.
|
|
||||||
5. Click **Save**.
|
|
||||||
- **Email/Password**:
|
|
||||||
1. Click **Email/Password** under Native providers.
|
|
||||||
2. Toggle **Email/Password** to **Enable**.
|
|
||||||
3. Leave *Email link (passwordless sign-in)* disabled unless explicitly required.
|
|
||||||
4. Click **Save**.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Configure Google Cloud OAuth Consent Screen (Critical)
|
|
||||||
|
|
||||||
> [!IMPORTANT]
|
|
||||||
> If this step is skipped, users outside your workspace or developer account will receive an "Access Blocked / Unverified App" error when attempting Google Sign-In.
|
|
||||||
|
|
||||||
1. Open the [Google Cloud Console](https://console.cloud.google.com/) with the same Google account.
|
|
||||||
2. Select your Firebase project from the top project selector dropdown.
|
|
||||||
3. In the navigation menu, go to **APIs & Services** > **OAuth consent screen**.
|
|
||||||
4. If prompted, select User Type **External** and click **Create**.
|
|
||||||
5. Fill in the required fields:
|
|
||||||
- **App name**: `CRE Innovations Studio`
|
|
||||||
- **User support email**: Your support or admin email.
|
|
||||||
- **Developer contact information**: Your contact email.
|
|
||||||
- *(Optional)* Upload your app logo and links to Privacy Policy / Terms of Service.
|
|
||||||
6. Click **Save and Continue** through the Scopes step (standard `openid`, `email`, `profile` are pre-selected).
|
|
||||||
7. Under **Publishing status**:
|
|
||||||
- If it says **Testing**, only specific test users can sign in.
|
|
||||||
- Click **Publish App** to switch to **In production** so any user can authenticate with Google.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Whitelist Authorized Domains
|
|
||||||
|
|
||||||
Firebase blocks OAuth popups from unlisted origins to prevent phishing:
|
|
||||||
|
|
||||||
1. In the Firebase Console, go to **Authentication** > **Settings** tab.
|
|
||||||
2. Click **Authorized domains**.
|
|
||||||
3. Verify that `localhost` is listed (included by default).
|
|
||||||
4. Click **Add domain** and enter your production and staging domains:
|
|
||||||
- Your production domain (e.g. `creinnovations.com` or `studio.creinnovations.com`)
|
|
||||||
- Your deployment host domain (e.g. `your-app.vercel.app` or `your-app.up.railway.app`)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Retrieve Client Web SDK Keys
|
|
||||||
|
|
||||||
1. In the Firebase Console, click the **Settings gear icon ⚙️** (top left) > **Project settings**.
|
|
||||||
2. In the **General** tab, scroll down to the **Your apps** card.
|
|
||||||
3. If no web app exists:
|
|
||||||
- Click the **Web icon `</>`**.
|
|
||||||
- Enter an App nickname (e.g., `CRE Studio Web`).
|
|
||||||
- Do **not** check "Also set up Firebase Hosting" (since this Next.js app is hosted independently).
|
|
||||||
- Click **Register app**.
|
|
||||||
4. Under **SDK setup and configuration**, select **Config**.
|
|
||||||
5. Copy the configuration values into your local `.env.local` file:
|
|
||||||
|
|
||||||
```env
|
|
||||||
NEXT_PUBLIC_FIREBASE_API_KEY=AIzaSy...
|
|
||||||
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=cre-innovations-studio.firebaseapp.com
|
|
||||||
NEXT_PUBLIC_FIREBASE_PROJECT_ID=cre-innovations-studio
|
|
||||||
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=cre-innovations-studio.appspot.com
|
|
||||||
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=123456789012
|
|
||||||
NEXT_PUBLIC_FIREBASE_APP_ID=1:123456789012:web:abcdef123456
|
|
||||||
NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID=G-XXXXXXXXXX
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. Generate Admin SDK Service Account Keys (Zero-Loophole Security)
|
|
||||||
|
|
||||||
The server requires service account credentials to verify ID tokens, set cryptographically signed `httpOnly` session cookies, and protect against XSS token theft:
|
|
||||||
|
|
||||||
1. In **Project settings**, click the **Service accounts** tab.
|
|
||||||
2. Confirm **Firebase Admin SDK** is selected (Node.js snippet displayed).
|
|
||||||
3. Click **Generate new private key** and confirm the dialog.
|
|
||||||
4. A JSON key file (e.g., `cre-innovations-studio-firebase-adminsdk-xxxxx.json`) will download to your machine.
|
|
||||||
5. Open the downloaded file in a text editor and extract the three fields into `.env.local`:
|
|
||||||
|
|
||||||
```env
|
|
||||||
FIREBASE_PROJECT_ID=cre-innovations-studio
|
|
||||||
FIREBASE_CLIENT_EMAIL=firebase-adminsdk-xxxxx@cre-innovations-studio.iam.gserviceaccount.com
|
|
||||||
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC...\n-----END PRIVATE KEY-----\n"
|
|
||||||
```
|
|
||||||
|
|
||||||
> [!CAUTION]
|
|
||||||
> - Never commit `.env.local` or the downloaded JSON file to Git.
|
|
||||||
> - Ensure the `FIREBASE_PRIVATE_KEY` is wrapped in double quotes and keeps the `\n` characters intact. Our code automatically handles replacing `\n` strings with real line breaks.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. Customize Authentication Email Templates
|
|
||||||
|
|
||||||
Make sure outbound emails reflect your brand:
|
|
||||||
|
|
||||||
1. In Firebase Console, go to **Authentication** > **Templates** tab.
|
|
||||||
2. Select **Password reset**:
|
|
||||||
- Click the pencil icon to edit.
|
|
||||||
- Customize the **Sender name** (e.g. `CRE Innovations Studio`).
|
|
||||||
- Set **Reply-to** address.
|
|
||||||
- Adjust message subject and body if desired.
|
|
||||||
3. Select **Email address verification**:
|
|
||||||
- Customize sender name and reply-to address.
|
|
||||||
4. *(Optional / Recommended for Custom Domain Branding)*:
|
|
||||||
- Click the edit icon next to **From** address to configure your custom domain email (via Mailgun, SendGrid, or custom SMTP/DNS records) so emails don't come from `@firebaseapp.com`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. Anti-Abuse & Account Enumeration Protection
|
|
||||||
|
|
||||||
1. In Firebase Console, go to **Authentication** > **Settings** tab.
|
|
||||||
2. Under **User actions**, verify that **Email enumeration protection** is **Enabled**.
|
|
||||||
- This prevents attackers from guessing whether an email is registered by returning identical response codes.
|
|
||||||
3. Under **Authorized domains**, ensure unneeded domains are not present.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 9. Local Verification Checklist
|
|
||||||
|
|
||||||
Once your `.env.local` file contains all keys:
|
|
||||||
|
|
||||||
1. **Restart your server**:
|
|
||||||
```bash
|
|
||||||
cd /home/creserver/Desktop/WEBB
|
|
||||||
npm run build && npm run start
|
|
||||||
# or for development:
|
|
||||||
# npm run dev
|
|
||||||
```
|
|
||||||
2. **Open the browser** at `http://localhost:3000`.
|
|
||||||
3. **Verify the UI**:
|
|
||||||
- Click the **Sign In** button in the top navbar.
|
|
||||||
- Notice the amber "Firebase not configured" banner is now **gone**.
|
|
||||||
- You should see the sleek dark-glass Sign In modal with Google OAuth and Email/Password fields.
|
|
||||||
4. **Test Email/Password Flow**:
|
|
||||||
- Switch to **Create account** tab.
|
|
||||||
- Enter a test email and password (minimum 8 characters with at least one number).
|
|
||||||
- Click **Create Account**.
|
|
||||||
- Verify that you are signed in, the modal closes, and the Navbar shows your user avatar dropdown.
|
|
||||||
5. **Inspect the Session Cookie**:
|
|
||||||
- Open Chrome DevTools > **Application** tab > **Cookies** > `http://localhost:3000`.
|
|
||||||
- Confirm that `__session` is present and marked `HttpOnly` and `SameSite: Lax`.
|
|
||||||
6. **Test Google Sign-In**:
|
|
||||||
- Click your avatar > **Sign Out**.
|
|
||||||
- Click **Sign In** > **Continue with Google**.
|
|
||||||
- Select your Google account in the popup.
|
|
||||||
- Confirm you are logged in and your Google profile photo / name appears in the UserMenu.
|
|
||||||
7. **Verify in Firebase Console**:
|
|
||||||
- Go to **Authentication** > **Users** tab.
|
|
||||||
- Confirm your registered test users appear with their correct Provider, Created, and Last Signed In timestamps.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 10. Production Deployment Setup (Vercel, Railway, Docker, etc.)
|
|
||||||
|
|
||||||
When deploying to production:
|
|
||||||
|
|
||||||
1. **Add Environment Variables**:
|
|
||||||
In your hosting dashboard (e.g., Vercel Project Settings > Environment Variables), add all keys:
|
|
||||||
- `NEXT_PUBLIC_FIREBASE_API_KEY`
|
|
||||||
- `NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN`
|
|
||||||
- `NEXT_PUBLIC_FIREBASE_PROJECT_ID`
|
|
||||||
- `NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET`
|
|
||||||
- `NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID`
|
|
||||||
- `NEXT_PUBLIC_FIREBASE_APP_ID`
|
|
||||||
- `NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID`
|
|
||||||
- `FIREBASE_PROJECT_ID`
|
|
||||||
- `FIREBASE_CLIENT_EMAIL`
|
|
||||||
- `FIREBASE_PRIVATE_KEY`
|
|
||||||
|
|
||||||
> **Vercel / Multi-line Variable Tip**: When pasting `FIREBASE_PRIVATE_KEY` in Vercel or cloud dashboards, you can paste the entire string including `\n` or the raw multiline PEM block. The app's `formatPrivateKey` normalizer automatically sanitizes either format.
|
|
||||||
|
|
||||||
2. **Add Production URL to Authorized Domains**:
|
|
||||||
- In Firebase Console > **Authentication** > **Settings** > **Authorized domains**, add your final domain (`https://creinnovations.com`).
|
|
||||||
|
|
||||||
3. **Verify HTTPS**:
|
|
||||||
- In production (`NODE_ENV === 'production'`), the session cookie automatically sets the `Secure` flag. HTTPS is required for the session cookie to be stored by the browser.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 11. Common Troubleshooting
|
|
||||||
|
|
||||||
| Issue | Cause | Fix |
|
|
||||||
|---|---|---|
|
|
||||||
| `auth/unauthorized-domain` | Current domain not in whitelist | Add domain to Firebase Console > Authentication > Settings > Authorized domains. |
|
|
||||||
| `auth/popup-blocked` | Browser blocked Google OAuth popup | Allow popups for your domain or test in standard browser window. |
|
|
||||||
| "Access blocked: This app's request is invalid" | OAuth consent screen not configured | Complete Step 3 in Google Cloud Console > APIs & Services > OAuth consent screen. |
|
|
||||||
| "Admin token verification failed" | Malformed `FIREBASE_PRIVATE_KEY` | Ensure `FIREBASE_PRIVATE_KEY` is wrapped in double quotes in `.env.local` with `\n` escapes intact. |
|
|
||||||
| Session cookie missing after refresh | HTTP used instead of HTTPS in production | Ensure your production host has SSL/HTTPS enabled; cookies enforce `Secure` in production. |
|
|
||||||
@@ -11,8 +11,6 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@types/three": "^0.187.0",
|
"@types/three": "^0.187.0",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"firebase": "^13.3.0",
|
|
||||||
"firebase-admin": "^14.5.1",
|
|
||||||
"framer-motion": "^14.9.0",
|
"framer-motion": "^14.9.0",
|
||||||
"lenis": "^1.3.27",
|
"lenis": "^1.3.27",
|
||||||
"lucide-react": "^0.468.0",
|
"lucide-react": "^0.468.0",
|
||||||
|
|||||||
@@ -1,140 +0,0 @@
|
|||||||
import { NextRequest, NextResponse } from 'next/server';
|
|
||||||
import {
|
|
||||||
createFirebaseSessionCookie,
|
|
||||||
verifyFirebaseIdToken,
|
|
||||||
isFirebaseAdminConfigured,
|
|
||||||
} from '@/lib/firebase/admin';
|
|
||||||
import { getServerUser, SESSION_COOKIE_NAME } from '@/lib/firebase/serverAuth';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validates that requests come from the same origin to mitigate CSRF attacks.
|
|
||||||
* In production, the Origin header MUST be present and match the host.
|
|
||||||
*/
|
|
||||||
function isValidOrigin(req: NextRequest): boolean {
|
|
||||||
const origin = req.headers.get('origin');
|
|
||||||
const host = req.headers.get('host');
|
|
||||||
|
|
||||||
if (!host) return false;
|
|
||||||
|
|
||||||
// In production, always require an Origin header on mutating requests
|
|
||||||
if (process.env.NODE_ENV === 'production') {
|
|
||||||
if (!origin) return false;
|
|
||||||
try {
|
|
||||||
const originUrl = new URL(origin);
|
|
||||||
return originUrl.host === host;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// In development, allow missing Origin (e.g. curl / local testing)
|
|
||||||
if (!origin) return true;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const originUrl = new URL(origin);
|
|
||||||
return originUrl.host === host;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* POST /api/auth/session
|
|
||||||
* Securely creates an httpOnly session cookie after client authentication.
|
|
||||||
*/
|
|
||||||
export async function POST(req: NextRequest) {
|
|
||||||
if (!isValidOrigin(req)) {
|
|
||||||
return NextResponse.json({ error: 'Invalid origin / CSRF rejection' }, { status: 403 });
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const body = await req.json().catch(() => ({}));
|
|
||||||
const idToken = body.idToken;
|
|
||||||
|
|
||||||
if (!idToken || typeof idToken !== 'string') {
|
|
||||||
return NextResponse.json({ error: 'Valid idToken required' }, { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const res = NextResponse.json({ success: true });
|
|
||||||
|
|
||||||
const fiveDaysInMs = 60 * 60 * 24 * 5 * 1000;
|
|
||||||
const isProduction = process.env.NODE_ENV === 'production';
|
|
||||||
|
|
||||||
if (isFirebaseAdminConfigured()) {
|
|
||||||
// Cryptographically mint a Firebase Session Cookie
|
|
||||||
const sessionCookie = await createFirebaseSessionCookie(idToken, fiveDaysInMs);
|
|
||||||
|
|
||||||
if (sessionCookie) {
|
|
||||||
res.cookies.set(SESSION_COOKIE_NAME, sessionCookie, {
|
|
||||||
maxAge: Math.floor(fiveDaysInMs / 1000),
|
|
||||||
httpOnly: true,
|
|
||||||
secure: isProduction,
|
|
||||||
path: '/',
|
|
||||||
sameSite: 'lax',
|
|
||||||
});
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Could not mint a server cookie even though admin is configured — reject
|
|
||||||
return NextResponse.json({ error: 'Session creation failed' }, { status: 500 });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Admin SDK not configured: verify the ID token signature directly (dev mode only)
|
|
||||||
if (isProduction) {
|
|
||||||
return NextResponse.json({ error: 'Auth backend not configured' }, { status: 503 });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback: Dev only — store raw ID token with 1-hour expiry
|
|
||||||
res.cookies.set(SESSION_COOKIE_NAME, idToken, {
|
|
||||||
maxAge: 3600,
|
|
||||||
httpOnly: true,
|
|
||||||
secure: false,
|
|
||||||
path: '/',
|
|
||||||
sameSite: 'lax',
|
|
||||||
});
|
|
||||||
|
|
||||||
return res;
|
|
||||||
} catch (error: any) {
|
|
||||||
console.error('[Auth API] Session creation error:', error);
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Failed to create session' },
|
|
||||||
{ status: 500 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* DELETE /api/auth/session
|
|
||||||
* Clears the session cookie on logout.
|
|
||||||
*/
|
|
||||||
export async function DELETE(req: NextRequest) {
|
|
||||||
if (!isValidOrigin(req)) {
|
|
||||||
return NextResponse.json({ error: 'Invalid origin / CSRF rejection' }, { status: 403 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const res = NextResponse.json({ success: true, message: 'Logged out successfully' });
|
|
||||||
res.cookies.set(SESSION_COOKIE_NAME, '', {
|
|
||||||
maxAge: 0,
|
|
||||||
httpOnly: true,
|
|
||||||
secure: process.env.NODE_ENV === 'production',
|
|
||||||
path: '/',
|
|
||||||
sameSite: 'lax',
|
|
||||||
});
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* GET /api/auth/session
|
|
||||||
* Returns the currently authenticated user's profile claims.
|
|
||||||
*/
|
|
||||||
export async function GET(req: NextRequest) {
|
|
||||||
try {
|
|
||||||
const user = await getServerUser(req);
|
|
||||||
return NextResponse.json({
|
|
||||||
authenticated: Boolean(user),
|
|
||||||
user: user || null,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
return NextResponse.json({ authenticated: false, user: null });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -6,6 +6,7 @@ import { getToolById, getToolBySlug } from '@/lib/config/loader';
|
|||||||
import { getEndpointById } from '@/lib/catalog/loader';
|
import { getEndpointById } from '@/lib/catalog/loader';
|
||||||
import { checkRateLimits, recordUsage } from '@/lib/api/rateLimiter';
|
import { checkRateLimits, recordUsage } from '@/lib/api/rateLimiter';
|
||||||
import { checkFileSignature, executeBackendTryIt, isCircuitOpen } from '@/lib/api/requestBuilder';
|
import { checkFileSignature, executeBackendTryIt, isCircuitOpen } from '@/lib/api/requestBuilder';
|
||||||
|
import { verifyTurnstileToken } from '@/lib/turnstile';
|
||||||
|
|
||||||
let _visitorCookieMaxAge: number | null = null;
|
let _visitorCookieMaxAge: number | null = null;
|
||||||
function getVisitorCookieMaxAge(): number {
|
function getVisitorCookieMaxAge(): number {
|
||||||
@@ -83,6 +84,28 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str
|
|||||||
try {
|
try {
|
||||||
const formData = await req.formData();
|
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,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ status: 403 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Primary image extraction: check 'image' first, then common aliases
|
// Primary image extraction: check 'image' first, then common aliases
|
||||||
let file = formData.get('image') as File | null;
|
let file = formData.get('image') as File | null;
|
||||||
if (!file || typeof file === 'string') {
|
if (!file || typeof file === 'string') {
|
||||||
|
|||||||
+9
-14
@@ -5,8 +5,6 @@ import { getSiteConfig, getAllCategories, getAllTools } from '@/lib/config/loade
|
|||||||
import { Navbar } from '@/components/ui/Navbar';
|
import { Navbar } from '@/components/ui/Navbar';
|
||||||
import { Footer } from '@/components/ui/Footer';
|
import { Footer } from '@/components/ui/Footer';
|
||||||
import { SmoothScrollProvider } from '@/components/ui/SmoothScrollProvider';
|
import { SmoothScrollProvider } from '@/components/ui/SmoothScrollProvider';
|
||||||
import { AuthProvider } from '@/lib/firebase/AuthContext';
|
|
||||||
import { AuthModal } from '@/components/auth/AuthModal';
|
|
||||||
|
|
||||||
const poppinsFont = Poppins({
|
const poppinsFont = Poppins({
|
||||||
subsets: ['latin'],
|
subsets: ['latin'],
|
||||||
@@ -178,18 +176,15 @@ export default function RootLayout({
|
|||||||
</head>
|
</head>
|
||||||
<body className="min-h-screen flex flex-col antialiased bg-paper text-ink relative font-sans overflow-x-clip">
|
<body className="min-h-screen flex flex-col antialiased bg-paper text-ink relative font-sans overflow-x-clip">
|
||||||
<SmoothScrollProvider>
|
<SmoothScrollProvider>
|
||||||
<AuthProvider>
|
<a href="#main-content" className="skip-link">Skip to main content</a>
|
||||||
<a href="#main-content" className="skip-link">Skip to main content</a>
|
<Navbar
|
||||||
<Navbar
|
config={config}
|
||||||
config={config}
|
currentLocale="en"
|
||||||
currentLocale="en"
|
categories={categories}
|
||||||
categories={categories}
|
totalToolsCount={tools.length}
|
||||||
totalToolsCount={tools.length}
|
/>
|
||||||
/>
|
<main id="main-content" className="flex-1">{children}</main>
|
||||||
<main id="main-content" className="flex-1">{children}</main>
|
<Footer config={config} currentLocale="en" />
|
||||||
<Footer config={config} currentLocale="en" />
|
|
||||||
<AuthModal />
|
|
||||||
</AuthProvider>
|
|
||||||
</SmoothScrollProvider>
|
</SmoothScrollProvider>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -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'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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { ToolItem, AppItem, VariantSpec, resolveLocalised } from '@/types';
|
import { ToolItem, AppItem, VariantSpec, resolveLocalised } from '@/types';
|
||||||
import { CardBeforeAfterSlider } from '../ui/CardBeforeAfterSlider';
|
import { CardBeforeAfterSlider } from '../ui/CardBeforeAfterSlider';
|
||||||
|
import { TurnstileWidget } from '@/components/turnstile/TurnstileWidget';
|
||||||
|
|
||||||
interface TryItWidgetProps {
|
interface TryItWidgetProps {
|
||||||
tool: ToolItem;
|
tool: ToolItem;
|
||||||
@@ -43,6 +44,7 @@ export function TryItWidget({
|
|||||||
const [status, setStatus] = useState<'idle' | 'selected' | 'processing' | 'success' | 'limit' | 'error' | 'unavailable'>('idle');
|
const [status, setStatus] = useState<'idle' | 'selected' | 'processing' | 'success' | 'limit' | 'error' | 'unavailable'>('idle');
|
||||||
const [errorMessage, setErrorMessage] = useState<string>('');
|
const [errorMessage, setErrorMessage] = useState<string>('');
|
||||||
const [remainingTries, setRemainingTries] = useState<number>(tool.tryIt?.limits?.perDay || 5);
|
const [remainingTries, setRemainingTries] = useState<number>(tool.tryIt?.limits?.perDay || 5);
|
||||||
|
const [turnstileToken, setTurnstileToken] = useState<string>('');
|
||||||
const [isDragOver, setIsDragOver] = useState<boolean>(false);
|
const [isDragOver, setIsDragOver] = useState<boolean>(false);
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
@@ -125,6 +127,10 @@ export function TryItWidget({
|
|||||||
formData.append('variant', activeVariant);
|
formData.append('variant', activeVariant);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (turnstileToken) {
|
||||||
|
formData.append('cf-turnstile-response', turnstileToken);
|
||||||
|
}
|
||||||
|
|
||||||
const response = await fetch(`/api/try/${tool.id}`, {
|
const response = await fetch(`/api/try/${tool.id}`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: formData,
|
body: formData,
|
||||||
@@ -316,6 +322,15 @@ export function TryItWidget({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<div className="py-2 flex justify-center">
|
||||||
|
<TurnstileWidget
|
||||||
|
onVerify={(tok) => setTurnstileToken(tok)}
|
||||||
|
onExpire={() => setTurnstileToken('')}
|
||||||
|
theme="auto"
|
||||||
|
size="flexible"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={runTryIt}
|
onClick={runTryIt}
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ import { ImageCropper } from './ImageCropper';
|
|||||||
import { PostResultAppHandoff } from './PostResultAppHandoff';
|
import { PostResultAppHandoff } from './PostResultAppHandoff';
|
||||||
import { AnimatedShinyText } from '@/components/magicui/animated-shiny-text';
|
import { AnimatedShinyText } from '@/components/magicui/animated-shiny-text';
|
||||||
import { BorderBeam } from '@/components/magicui/border-beam';
|
import { BorderBeam } from '@/components/magicui/border-beam';
|
||||||
|
import { TurnstileWidget, TurnstileWidgetRef } from '@/components/turnstile/TurnstileWidget';
|
||||||
|
|
||||||
interface DynamicToolWorkspaceProps {
|
interface DynamicToolWorkspaceProps {
|
||||||
tool: ToolItem;
|
tool: ToolItem;
|
||||||
@@ -110,6 +111,8 @@ export function DynamicToolWorkspace({
|
|||||||
const [errorMessage, setErrorMessage] = useState<string>('');
|
const [errorMessage, setErrorMessage] = useState<string>('');
|
||||||
const [remainingTries, setRemainingTries] = useState<number>(tool.tryIt?.limits?.perDay || 5);
|
const [remainingTries, setRemainingTries] = useState<number>(tool.tryIt?.limits?.perDay || 5);
|
||||||
const [hasDownloadedResult, setHasDownloadedResult] = useState<boolean>(false);
|
const [hasDownloadedResult, setHasDownloadedResult] = useState<boolean>(false);
|
||||||
|
const [turnstileToken, setTurnstileToken] = useState<string>('');
|
||||||
|
const turnstileRef = useRef<TurnstileWidgetRef>(null);
|
||||||
|
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
const secondaryFileInputRef = 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}`, {
|
const res = await fetch(`/api/try/${tool.id}`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: formData,
|
body: formData,
|
||||||
@@ -793,7 +801,16 @@ export function DynamicToolWorkspace({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Right: Massive High-Visibility Main Process Button with Dynamic Server-backed Quota Icon */}
|
{/* 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
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={handleExecute}
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
);
|
||||||
@@ -20,7 +20,6 @@ import {
|
|||||||
import { SiteConfig, CategoryItem, resolveLocalised } from '@/types';
|
import { SiteConfig, CategoryItem, resolveLocalised } from '@/types';
|
||||||
import { BrandLogo } from './BrandLogo';
|
import { BrandLogo } from './BrandLogo';
|
||||||
import { RainbowButton } from '@/components/magicui/rainbow-button';
|
import { RainbowButton } from '@/components/magicui/rainbow-button';
|
||||||
import { UserMenu } from '@/components/auth/UserMenu';
|
|
||||||
|
|
||||||
interface NavbarProps {
|
interface NavbarProps {
|
||||||
config: SiteConfig;
|
config: SiteConfig;
|
||||||
@@ -148,9 +147,8 @@ export function Navbar({ config, currentLocale, categories = [], totalToolsCount
|
|||||||
})}
|
})}
|
||||||
</nav>
|
</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">
|
<div className="hidden md:flex items-center gap-3 relative z-20 flex-shrink-0">
|
||||||
<UserMenu />
|
|
||||||
<RainbowButton href={ctaHref}>
|
<RainbowButton href={ctaHref}>
|
||||||
<span>{ctaLabel}</span>
|
<span>{ctaLabel}</span>
|
||||||
<ArrowRight className="w-3.5 h-3.5 ml-1 inline" aria-hidden="true" />
|
<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>
|
</nav>
|
||||||
|
|
||||||
<div className="pt-6 border-t border-rule space-y-3">
|
<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
|
<RainbowButton
|
||||||
href={ctaHref}
|
href={ctaHref}
|
||||||
onClick={() => setMobileMenuOpen(false)}
|
onClick={() => setMobileMenuOpen(false)}
|
||||||
|
|||||||
@@ -1,202 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import React, { createContext, useContext, useEffect, useState, useCallback } from 'react';
|
|
||||||
import {
|
|
||||||
User,
|
|
||||||
onIdTokenChanged,
|
|
||||||
signInWithPopup,
|
|
||||||
signInWithEmailAndPassword,
|
|
||||||
createUserWithEmailAndPassword,
|
|
||||||
sendPasswordResetEmail,
|
|
||||||
signOut as firebaseSignOut,
|
|
||||||
updateProfile,
|
|
||||||
} from 'firebase/auth';
|
|
||||||
import { getClientAuth, getGoogleProvider, isFirebaseClientConfigured } from './config';
|
|
||||||
|
|
||||||
export type AuthModalMode = 'signin' | 'signup' | 'reset';
|
|
||||||
|
|
||||||
interface AuthContextType {
|
|
||||||
user: User | null;
|
|
||||||
loading: boolean;
|
|
||||||
isConfigured: boolean;
|
|
||||||
signInWithGoogle: () => Promise<void>;
|
|
||||||
signInWithEmail: (email: string, pass: string) => Promise<void>;
|
|
||||||
signUpWithEmail: (email: string, pass: string, displayName?: string) => Promise<void>;
|
|
||||||
sendPasswordReset: (email: string) => Promise<void>;
|
|
||||||
logout: () => Promise<void>;
|
|
||||||
authModalOpen: boolean;
|
|
||||||
authModalMode: AuthModalMode;
|
|
||||||
openAuthModal: (mode?: AuthModalMode) => void;
|
|
||||||
closeAuthModal: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
|
||||||
|
|
||||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|
||||||
const [user, setUser] = useState<User | null>(null);
|
|
||||||
const [loading, setLoading] = useState<boolean>(true);
|
|
||||||
const [authModalOpen, setAuthModalOpen] = useState<boolean>(false);
|
|
||||||
const [authModalMode, setAuthModalMode] = useState<AuthModalMode>('signin');
|
|
||||||
|
|
||||||
const isConfigured = isFirebaseClientConfigured();
|
|
||||||
|
|
||||||
// Synchronize Firebase Auth state with Server Session Cookie
|
|
||||||
useEffect(() => {
|
|
||||||
if (!isConfigured) {
|
|
||||||
setLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const auth = getClientAuth();
|
|
||||||
if (!auth) {
|
|
||||||
setLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const unsubscribe = onIdTokenChanged(auth, async (currentUser) => {
|
|
||||||
setUser(currentUser);
|
|
||||||
setLoading(false);
|
|
||||||
|
|
||||||
if (currentUser) {
|
|
||||||
try {
|
|
||||||
const idToken = await currentUser.getIdToken();
|
|
||||||
await fetch('/api/auth/session', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ idToken }),
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('[Auth] Failed to sync session cookie:', error);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
await fetch('/api/auth/session', { method: 'DELETE' });
|
|
||||||
} catch {
|
|
||||||
// Ignore logout error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return () => unsubscribe();
|
|
||||||
}, [isConfigured]);
|
|
||||||
|
|
||||||
const openAuthModal = useCallback((mode: AuthModalMode = 'signin') => {
|
|
||||||
setAuthModalMode(mode);
|
|
||||||
setAuthModalOpen(true);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const closeAuthModal = useCallback(() => {
|
|
||||||
setAuthModalOpen(false);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const signInWithGoogle = useCallback(async () => {
|
|
||||||
if (!isConfigured) {
|
|
||||||
throw new Error('Firebase is not yet configured. Please set your credentials in .env.local.');
|
|
||||||
}
|
|
||||||
const auth = getClientAuth();
|
|
||||||
const provider = getGoogleProvider();
|
|
||||||
if (!auth || !provider) {
|
|
||||||
throw new Error('Firebase Auth client could not be initialized.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await signInWithPopup(auth, provider);
|
|
||||||
const idToken = await result.user.getIdToken();
|
|
||||||
await fetch('/api/auth/session', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ idToken }),
|
|
||||||
});
|
|
||||||
setAuthModalOpen(false);
|
|
||||||
}, [isConfigured]);
|
|
||||||
|
|
||||||
const signInWithEmail = useCallback(async (email: string, pass: string) => {
|
|
||||||
if (!isConfigured) {
|
|
||||||
throw new Error('Firebase is not yet configured. Please set your credentials in .env.local.');
|
|
||||||
}
|
|
||||||
const auth = getClientAuth();
|
|
||||||
if (!auth) {
|
|
||||||
throw new Error('Firebase Auth client could not be initialized.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await signInWithEmailAndPassword(auth, email.trim(), pass);
|
|
||||||
const idToken = await result.user.getIdToken();
|
|
||||||
await fetch('/api/auth/session', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ idToken }),
|
|
||||||
});
|
|
||||||
setAuthModalOpen(false);
|
|
||||||
}, [isConfigured]);
|
|
||||||
|
|
||||||
const signUpWithEmail = useCallback(async (email: string, pass: string, displayName?: string) => {
|
|
||||||
if (!isConfigured) {
|
|
||||||
throw new Error('Firebase is not yet configured. Please set your credentials in .env.local.');
|
|
||||||
}
|
|
||||||
const auth = getClientAuth();
|
|
||||||
if (!auth) {
|
|
||||||
throw new Error('Firebase Auth client could not be initialized.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await createUserWithEmailAndPassword(auth, email.trim(), pass);
|
|
||||||
if (displayName && displayName.trim()) {
|
|
||||||
await updateProfile(result.user, { displayName: displayName.trim() });
|
|
||||||
}
|
|
||||||
const idToken = await result.user.getIdToken();
|
|
||||||
await fetch('/api/auth/session', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ idToken }),
|
|
||||||
});
|
|
||||||
setAuthModalOpen(false);
|
|
||||||
}, [isConfigured]);
|
|
||||||
|
|
||||||
const sendPasswordReset = useCallback(async (email: string) => {
|
|
||||||
if (!isConfigured) {
|
|
||||||
throw new Error('Firebase is not yet configured. Please set your credentials in .env.local.');
|
|
||||||
}
|
|
||||||
const auth = getClientAuth();
|
|
||||||
if (!auth) {
|
|
||||||
throw new Error('Firebase Auth client could not be initialized.');
|
|
||||||
}
|
|
||||||
|
|
||||||
await sendPasswordResetEmail(auth, email.trim());
|
|
||||||
}, [isConfigured]);
|
|
||||||
|
|
||||||
const logout = useCallback(async () => {
|
|
||||||
const auth = getClientAuth();
|
|
||||||
if (auth) {
|
|
||||||
await firebaseSignOut(auth);
|
|
||||||
}
|
|
||||||
await fetch('/api/auth/session', { method: 'DELETE' });
|
|
||||||
setUser(null);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<AuthContext.Provider
|
|
||||||
value={{
|
|
||||||
user,
|
|
||||||
loading,
|
|
||||||
isConfigured,
|
|
||||||
signInWithGoogle,
|
|
||||||
signInWithEmail,
|
|
||||||
signUpWithEmail,
|
|
||||||
sendPasswordReset,
|
|
||||||
logout,
|
|
||||||
authModalOpen,
|
|
||||||
authModalMode,
|
|
||||||
openAuthModal,
|
|
||||||
closeAuthModal,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</AuthContext.Provider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useAuth() {
|
|
||||||
const context = useContext(AuthContext);
|
|
||||||
if (!context) {
|
|
||||||
throw new Error('useAuth must be used within an AuthProvider');
|
|
||||||
}
|
|
||||||
return context;
|
|
||||||
}
|
|
||||||
@@ -1,125 +0,0 @@
|
|||||||
import { getApps, initializeApp, cert, App } from 'firebase-admin/app';
|
|
||||||
import { getAuth, Auth, DecodedIdToken } from 'firebase-admin/auth';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Firebase Admin SDK Initialization (Server-side only)
|
|
||||||
* Provides cryptographically secure verification of ID tokens and session cookies.
|
|
||||||
*/
|
|
||||||
|
|
||||||
function formatPrivateKey(key: string | undefined): string | undefined {
|
|
||||||
if (!key) return undefined;
|
|
||||||
return key.replace(/\\n/g, '\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
const projectId =
|
|
||||||
process.env.FIREBASE_PROJECT_ID ||
|
|
||||||
process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID ||
|
|
||||||
'';
|
|
||||||
const clientEmail = process.env.FIREBASE_CLIENT_EMAIL || '';
|
|
||||||
const privateKey = formatPrivateKey(process.env.FIREBASE_PRIVATE_KEY);
|
|
||||||
|
|
||||||
export function isFirebaseAdminConfigured(): boolean {
|
|
||||||
return Boolean(projectId && clientEmail && privateKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
function initAdmin(): App | null {
|
|
||||||
const currentApps = getApps();
|
|
||||||
if (currentApps.length > 0) {
|
|
||||||
return currentApps[0]!;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isFirebaseAdminConfigured()) {
|
|
||||||
try {
|
|
||||||
return initializeApp({
|
|
||||||
credential: cert({
|
|
||||||
projectId,
|
|
||||||
clientEmail,
|
|
||||||
privateKey,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('[Firebase Admin] Initialization with cert failed:', error);
|
|
||||||
}
|
|
||||||
} else if (projectId) {
|
|
||||||
// Project ID only (e.g. Google Cloud Run or GCP environment with ADC)
|
|
||||||
try {
|
|
||||||
return initializeApp({
|
|
||||||
projectId,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('[Firebase Admin] Initialization with projectId failed:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getAdminAuth(): Auth | null {
|
|
||||||
const currentApp = getApps().length > 0 ? getApps()[0]! : initAdmin();
|
|
||||||
if (!currentApp) return null;
|
|
||||||
return getAuth(currentApp);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Verifies a client-provided Firebase ID Token.
|
|
||||||
* Rejects revoked or expired tokens.
|
|
||||||
*/
|
|
||||||
export async function verifyFirebaseIdToken(
|
|
||||||
idToken: string,
|
|
||||||
checkRevoked = true
|
|
||||||
): Promise<DecodedIdToken | null> {
|
|
||||||
const auth = getAdminAuth();
|
|
||||||
if (!auth) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const decoded = await auth.verifyIdToken(idToken, checkRevoked);
|
|
||||||
return decoded;
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('[Firebase Admin] ID token verification failed:', error);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Verifies a server-side session cookie.
|
|
||||||
*/
|
|
||||||
export async function verifyFirebaseSessionCookie(
|
|
||||||
sessionCookie: string,
|
|
||||||
checkRevoked = true
|
|
||||||
): Promise<DecodedIdToken | null> {
|
|
||||||
const auth = getAdminAuth();
|
|
||||||
if (!auth) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const decoded = await auth.verifySessionCookie(sessionCookie, checkRevoked);
|
|
||||||
return decoded;
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('[Firebase Admin] Session cookie verification failed:', error);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a server session cookie valid for the specified duration (e.g., 5 days).
|
|
||||||
*/
|
|
||||||
export async function createFirebaseSessionCookie(
|
|
||||||
idToken: string,
|
|
||||||
expiresInMs = 60 * 60 * 24 * 5 * 1000 // 5 days
|
|
||||||
): Promise<string | null> {
|
|
||||||
const auth = getAdminAuth();
|
|
||||||
if (!auth) return null;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const sessionCookie = await auth.createSessionCookie(idToken, {
|
|
||||||
expiresIn: expiresInMs,
|
|
||||||
});
|
|
||||||
return sessionCookie;
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('[Firebase Admin] Failed to create session cookie:', error);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
import { initializeApp, getApps, getApp, FirebaseApp } from 'firebase/app';
|
|
||||||
import { getAuth, Auth, GoogleAuthProvider } from 'firebase/auth';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Firebase Client SDK Configuration
|
|
||||||
* Loaded dynamically from environment variables.
|
|
||||||
* Safe fallback prevents build-time crashes when credentials are not yet configured.
|
|
||||||
*/
|
|
||||||
export 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 || '',
|
|
||||||
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID || '',
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validates whether the essential client configuration keys are set.
|
|
||||||
*/
|
|
||||||
export function isFirebaseClientConfigured(): boolean {
|
|
||||||
return Boolean(
|
|
||||||
firebaseConfig.apiKey &&
|
|
||||||
firebaseConfig.authDomain &&
|
|
||||||
firebaseConfig.projectId &&
|
|
||||||
firebaseConfig.appId
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let app: FirebaseApp | null = null;
|
|
||||||
let auth: Auth | null = null;
|
|
||||||
let googleProvider: GoogleAuthProvider | null = null;
|
|
||||||
|
|
||||||
if (typeof window !== 'undefined') {
|
|
||||||
if (isFirebaseClientConfigured()) {
|
|
||||||
try {
|
|
||||||
app = getApps().length > 0 ? getApp() : initializeApp(firebaseConfig);
|
|
||||||
auth = getAuth(app);
|
|
||||||
googleProvider = new GoogleAuthProvider();
|
|
||||||
googleProvider.setCustomParameters({ prompt: 'select_account' });
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('[Firebase] Client initialization failed:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getClientApp(): FirebaseApp | null {
|
|
||||||
if (!app && typeof window !== 'undefined' && isFirebaseClientConfigured()) {
|
|
||||||
try {
|
|
||||||
app = getApps().length > 0 ? getApp() : initializeApp(firebaseConfig);
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[Firebase] Failed to get client app:', err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return app;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getClientAuth(): Auth | null {
|
|
||||||
if (!auth && typeof window !== 'undefined' && isFirebaseClientConfigured()) {
|
|
||||||
const clientApp = getClientApp();
|
|
||||||
if (clientApp) {
|
|
||||||
try {
|
|
||||||
auth = getAuth(clientApp);
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[Firebase] Failed to get client auth:', err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return auth;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getGoogleProvider(): GoogleAuthProvider | null {
|
|
||||||
if (!googleProvider && typeof window !== 'undefined') {
|
|
||||||
googleProvider = new GoogleAuthProvider();
|
|
||||||
googleProvider.setCustomParameters({ prompt: 'select_account' });
|
|
||||||
}
|
|
||||||
return googleProvider;
|
|
||||||
}
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
import { cookies, headers } from 'next/headers';
|
|
||||||
import { NextRequest } from 'next/server';
|
|
||||||
import { verifyFirebaseSessionCookie, verifyFirebaseIdToken } from './admin';
|
|
||||||
|
|
||||||
export interface AuthenticatedUser {
|
|
||||||
uid: string;
|
|
||||||
email: string | null;
|
|
||||||
displayName: string | null;
|
|
||||||
photoURL: string | null;
|
|
||||||
emailVerified: boolean;
|
|
||||||
claims: Record<string, any>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const SESSION_COOKIE_NAME = '__session';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Extracts and verifies the authenticated user from cookies or Authorization header.
|
|
||||||
* Server-only verification: Cannot be spoofed by client headers alone.
|
|
||||||
*/
|
|
||||||
export async function getServerUser(req?: NextRequest): Promise<AuthenticatedUser | null> {
|
|
||||||
// 1. Try session cookie first (httpOnly)
|
|
||||||
let sessionToken: string | undefined;
|
|
||||||
|
|
||||||
if (req) {
|
|
||||||
sessionToken = req.cookies.get(SESSION_COOKIE_NAME)?.value;
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
const cookieStore = cookies();
|
|
||||||
sessionToken = cookieStore.get(SESSION_COOKIE_NAME)?.value;
|
|
||||||
} catch {
|
|
||||||
// Outside request context
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (sessionToken) {
|
|
||||||
const decoded = await verifyFirebaseSessionCookie(sessionToken);
|
|
||||||
if (decoded) {
|
|
||||||
return {
|
|
||||||
uid: decoded.uid,
|
|
||||||
email: decoded.email || null,
|
|
||||||
displayName: (decoded.name as string) || null,
|
|
||||||
photoURL: (decoded.picture as string) || null,
|
|
||||||
emailVerified: Boolean(decoded.email_verified),
|
|
||||||
claims: decoded,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Fallback to Authorization: Bearer <idToken> header (e.g. for API clients)
|
|
||||||
let authHeader: string | null = null;
|
|
||||||
if (req) {
|
|
||||||
authHeader = req.headers.get('authorization');
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
const headerStore = headers();
|
|
||||||
authHeader = headerStore.get('authorization');
|
|
||||||
} catch {
|
|
||||||
// Outside request context
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
|
||||||
const idToken = authHeader.substring(7).trim();
|
|
||||||
if (idToken) {
|
|
||||||
const decoded = await verifyFirebaseIdToken(idToken);
|
|
||||||
if (decoded) {
|
|
||||||
return {
|
|
||||||
uid: decoded.uid,
|
|
||||||
email: decoded.email || null,
|
|
||||||
displayName: (decoded.name as string) || null,
|
|
||||||
photoURL: (decoded.picture as string) || null,
|
|
||||||
emailVerified: Boolean(decoded.email_verified),
|
|
||||||
claims: decoded,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
/**
|
||||||
|
* Cloudflare Turnstile Server-side Verification Utility
|
||||||
|
*
|
||||||
|
* Validates cf-turnstile-response tokens against Cloudflare's verification API:
|
||||||
|
* https://challenges.cloudflare.com/turnstile/v0/siteverify
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface TurnstileVerificationResult {
|
||||||
|
success: boolean;
|
||||||
|
errorCodes?: string[];
|
||||||
|
challengeTs?: string;
|
||||||
|
hostname?: string;
|
||||||
|
message?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const CLOUDFLARE_VERIFY_ENDPOINT = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifies a Turnstile response token with Cloudflare's verification API.
|
||||||
|
*
|
||||||
|
* If CLOUDFLARE_TURNSTILE_SECRET_KEY is not defined (e.g. initial setup or local dev),
|
||||||
|
* verification is gracefully bypassed with a console notice, allowing the application
|
||||||
|
* to function normally until the user configures their keys.
|
||||||
|
*/
|
||||||
|
export async function verifyTurnstileToken(
|
||||||
|
token: string | null | undefined,
|
||||||
|
remoteIp?: string
|
||||||
|
): Promise<TurnstileVerificationResult> {
|
||||||
|
const secretKey = process.env.CLOUDFLARE_TURNSTILE_SECRET_KEY;
|
||||||
|
|
||||||
|
// Graceful development fallback when keys are not configured yet
|
||||||
|
if (!secretKey || secretKey.trim() === '') {
|
||||||
|
if (process.env.NODE_ENV !== 'production') {
|
||||||
|
console.warn(
|
||||||
|
'[Turnstile] Notice: CLOUDFLARE_TURNSTILE_SECRET_KEY is not set. Bypassing check in development mode. Set CLOUDFLARE_TURNSTILE_SECRET_KEY in .env.local to enforce security.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: 'Turnstile verification bypassed (no secret key configured).',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// If secret is set, token is strictly required
|
||||||
|
if (!token || token.trim() === '') {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: 'Human verification token is missing. Please complete the security check.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const formData = new URLSearchParams();
|
||||||
|
formData.append('secret', secretKey);
|
||||||
|
formData.append('response', token);
|
||||||
|
if (remoteIp && remoteIp !== '127.0.0.1' && remoteIp !== '::1') {
|
||||||
|
formData.append('remoteip', remoteIp);
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(CLOUDFLARE_VERIFY_ENDPOINT, {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
|
},
|
||||||
|
cache: 'no-store',
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
console.error(`[Turnstile] Cloudflare verify endpoint returned HTTP ${response.status}`);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: 'Could not communicate with Cloudflare verification service.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: Boolean(data.success),
|
||||||
|
errorCodes: data['error-codes'] || [],
|
||||||
|
challengeTs: data.challenge_ts,
|
||||||
|
hostname: data.hostname,
|
||||||
|
message: data.success ? undefined : 'Bot verification challenge failed.',
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error('[Turnstile] Error during token verification:', error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: error?.message || 'Error communicating with Turnstile verification service.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
import { describe, it, expect, vi } from 'vitest';
|
|
||||||
import { isFirebaseClientConfigured } from '@/lib/firebase/config';
|
|
||||||
import { isFirebaseAdminConfigured } from '@/lib/firebase/admin';
|
|
||||||
import { POST as sessionPost, DELETE as sessionDelete, GET as sessionGet } from '@/app/api/auth/session/route';
|
|
||||||
import { NextRequest } from 'next/server';
|
|
||||||
|
|
||||||
describe('Firebase Authentication Architecture & Security Guards', () => {
|
|
||||||
it('correctly evaluates client configuration state', () => {
|
|
||||||
// In unconfigured state (empty env vars)
|
|
||||||
const configured = isFirebaseClientConfigured();
|
|
||||||
expect(typeof configured).toBe('boolean');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('correctly evaluates admin configuration state', () => {
|
|
||||||
const adminConfigured = isFirebaseAdminConfigured();
|
|
||||||
expect(typeof adminConfigured).toBe('boolean');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects POST /api/auth/session requests with mismatched or forged origin (CSRF defense)', async () => {
|
|
||||||
const fakeReq = new NextRequest('http://localhost:3000/api/auth/session', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
host: 'localhost:3000',
|
|
||||||
origin: 'https://malicious-attacker.com',
|
|
||||||
'content-type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ idToken: 'fake-token' }),
|
|
||||||
});
|
|
||||||
|
|
||||||
const res = await sessionPost(fakeReq);
|
|
||||||
expect(res.status).toBe(403);
|
|
||||||
const data = await res.json();
|
|
||||||
expect(data.error).toContain('CSRF');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects POST /api/auth/session requests with missing idToken', async () => {
|
|
||||||
const req = new NextRequest('http://localhost:3000/api/auth/session', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
host: 'localhost:3000',
|
|
||||||
origin: 'http://localhost:3000',
|
|
||||||
'content-type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify({}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const res = await sessionPost(req);
|
|
||||||
expect(res.status).toBe(400);
|
|
||||||
const data = await res.json();
|
|
||||||
expect(data.error).toBe('Valid idToken required');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('accepts valid origin on DELETE /api/auth/session and clears cookie', async () => {
|
|
||||||
const req = new NextRequest('http://localhost:3000/api/auth/session', {
|
|
||||||
method: 'DELETE',
|
|
||||||
headers: {
|
|
||||||
host: 'localhost:3000',
|
|
||||||
origin: 'http://localhost:3000',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const res = await sessionDelete(req);
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
const data = await res.json();
|
|
||||||
expect(data.success).toBe(true);
|
|
||||||
const setCookie = res.headers.get('set-cookie');
|
|
||||||
expect(setCookie).toContain('__session=;');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns unauthenticated on GET /api/auth/session when no session cookie is provided', async () => {
|
|
||||||
const req = new NextRequest('http://localhost:3000/api/auth/session', {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
host: 'localhost:3000',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const res = await sessionGet(req);
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
const data = await res.json();
|
|
||||||
expect(data.authenticated).toBe(false);
|
|
||||||
expect(data.user).toBeNull();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
Reference in New Issue
Block a user