Compare commits

..
10 Commits
55 changed files with 1113 additions and 1750 deletions
+6 -17
View File
@@ -31,21 +31,10 @@ CATALOG_ADMIN_SECRET=REPLACE_WITH_32_CHAR_HEX
ALLOWED_ORIGIN=http://localhost:3000
# ---------------------------------------------------------------------------
# Firebase Client SDK Configuration (Required for Live Client Auth)
# Obtain from: Firebase Console > Project Settings > General > Your apps (Web)
# Cloudflare Turnstile Bot & Abuse Protection
# 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_FIREBASE_AUTH_DOMAIN=your_project_id.firebaseapp.com
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"
NEXT_PUBLIC_TURNSTILE_SITE_KEY=your_cloudflare_turnstile_site_key
CLOUDFLARE_TURNSTILE_SECRET_KEY=your_cloudflare_turnstile_secret_key
+192
View File
@@ -0,0 +1,192 @@
# Cloudflare Turnstile Integration & Activation Guide
This runbook documents the complete replacement of **Firebase Authentication** with **Cloudflare Turnstile** bot and abuse protection across the CRE Innovations Web Studio platform, and provides step-by-step instructions for activating and testing it.
---
## 📋 Table of Contents
1. [Overview & What Changed](#overview--what-changed)
2. [Quick Activation (2 Minutes)](#quick-activation-2-minutes)
3. [Environment Configuration](#environment-configuration)
4. [Testing Locally (Zero-Setup Test Keys)](#testing-locally-zero-setup-test-keys)
5. [Technical Architecture & Verification Flow](#technical-architecture--verification-flow)
6. [Production Deployment Guide](#production-deployment-guide)
7. [Troubleshooting & FAQs](#troubleshooting--faqs)
---
## 1. Overview & What Changed
Firebase Authentication has been **completely removed** from the repository to eliminate authentication friction, OAuth consent requirements, and complex Google Cloud service account setups.
In its place, **Cloudflare Turnstile** provides lightweight, privacy-preserving bot protection that verifies human visitors without frustrating puzzles (no crosswalks, traffic lights, or CAPTCHA solving):
### Files Removed (Firebase):
- `src/lib/firebase/` (`admin.ts`, `AuthContext.tsx`, `config.ts`, `serverAuth.ts`)
- `src/components/auth/` (`AuthModal.tsx`, `UserMenu.tsx`)
- `src/app/api/auth/session/route.ts`
- `tests/auth.test.ts`
- `FIREBASE_SETUP.md`
- `firebase` and `firebase-admin` dependencies removed from `package.json`
### Files Added / Updated (Cloudflare Turnstile):
- `src/lib/turnstile.ts`: Server-side token validation against `https://challenges.cloudflare.com/turnstile/v0/siteverify`.
- `src/components/turnstile/TurnstileWidget.tsx`: SSR-safe, dynamic client component with real-time status micro-badges.
- `src/app/api/try/[toolId]/route.ts`: Validates `cf-turnstile-response` token before executing GPU neural pipelines.
- `src/components/tools/DynamicToolWorkspace.tsx`: Turnstile widget embedded right above the Process button with automatic token attachment to `FormData`.
- `src/components/sections/TryItWidget.tsx`: Turnstile verification integrated into quick-try card.
- `src/components/ui/Navbar.tsx`: Restored clean header without Firebase login modals.
- `src/app/layout.tsx`: Restored clean root layout without `<AuthProvider>`.
---
## 2. Quick Activation (2 Minutes)
Activating Cloudflare Turnstile is **100% free** and takes under two minutes.
### Step 1: Open Cloudflare Dashboard
1. Navigate to the [Cloudflare Dashboard](https://dash.cloudflare.com/).
2. Log in with your Cloudflare account (or create a free account).
### Step 2: Create a Turnstile Widget
1. In the left navigation menu, expand **Application Services** and click **Turnstile**.
2. Click **Add widget** (or **Add site**).
3. Fill in the widget form:
- **Widget name**: `CRE Innovations Studio` (or your preferred name).
- **Domains**:
- `localhost` *(required for local development and testing)*
- `127.0.0.1` *(optional, for IP-based local tests)*
- Your production domain (e.g. `creinnovations.in` or `yourdomain.com`).
- Any preview / staging domains (e.g. `*.vercel.app` or `*.railway.app`).
- **Widget Mode**:
- **Managed** *(Recommended)*: Cloudflare automatically decides when to run an invisible background check vs. showing a single unobtrusive checkbox if risk is elevated.
- **Non-interactive**: Runs a purely automated browser challenge without user interaction.
- **Invisible**: Completely invisible background token verification.
4. Click **Create**.
### Step 3: Copy Your Keys
Cloudflare displays two API keys on the completion screen:
- **Site Key** (Public): Starts with `0x4AAAAAA...`
- **Secret Key** (Private): Starts with `0x4AAAAAA...`
---
## 3. Environment Configuration
### Local Environment (`.env.local`)
Create or edit `.env.local` in the project root:
```env
# ---------------------------------------------------------------------------
# Cloudflare Turnstile Bot & Anti-Abuse Protection
# ---------------------------------------------------------------------------
NEXT_PUBLIC_TURNSTILE_SITE_KEY=your_actual_site_key_from_cloudflare
CLOUDFLARE_TURNSTILE_SECRET_KEY=your_actual_secret_key_from_cloudflare
```
> [!NOTE]
> If `CLOUDFLARE_TURNSTILE_SECRET_KEY` is omitted or empty during local development, the server gracefully logs a notice and bypasses the check so developers are never blocked while provisioning keys.
---
## 4. Testing Locally (Zero-Setup Test Keys)
Cloudflare maintains official dummy keys that allow testing all pass, fail, and interactive scenarios immediately without creating a Cloudflare account:
| Testing Scenario | Public Site Key (`NEXT_PUBLIC_TURNSTILE_SITE_KEY`) | Server Secret Key (`CLOUDFLARE_TURNSTILE_SECRET_KEY`) | What Happens |
| :--- | :--- | :--- | :--- |
| **Always Passes** | `1x00000000000000000000AA` | `1x0000000000000000000000000000000AA` | Instantly validates without user clicking. Inference succeeds. |
| **Always Blocks / Fails** | `2x00000000000000000000AB` | `2x0000000000000000000000000000000AA` | Challenge fails. Server responds with HTTP `403 BOT_VERIFICATION_FAILED`. |
| **Interactive Checkbox** | `3x00000000000000000000FF` | `1x0000000000000000000000000000000AA` | Shows interactive "Verify you are human" checkbox. |
---
## 5. Technical Architecture & Verification Flow
```
[ User Browser ]
│
▼ (1) Loads /tools/[slug]
[ TurnstileWidget ] ───> Cloudflare CDN (challenges.cloudflare.com)
│
▼ (2) Human verification complete -> returns 'cf-turnstile-response' token
[ DynamicToolWorkspace ]
│
▼ (3) POST /api/try/[toolId] (FormData with file + 'cf-turnstile-response')
[ Next.js Server Route ]
│
▼ (4) POST https://challenges.cloudflare.com/turnstile/v0/siteverify
│ Body: { secret: CLOUDFLARE_TURNSTILE_SECRET_KEY, response: token, remoteip: ip }
│
├─► [FAIL] ──► Return HTTP 403 { code: 'BOT_VERIFICATION_FAILED' }
│
└─► [PASS] ──► Execute backend GPU model pipeline & stream lossless 4K result
```
---
## 6. Production Deployment Guide
### Vercel / Railway / Render / AWS
Add these two Environment Variables in your hosting dashboard:
- `NEXT_PUBLIC_TURNSTILE_SITE_KEY`: Your production Turnstile Site Key.
- `CLOUDFLARE_TURNSTILE_SECRET_KEY`: Your production Turnstile Secret Key.
### Restarting the Server
```bash
# 1. Clean build
npm run build
# 2. Start production server
npm run start
```
---
## 7. Troubleshooting & FAQs
### Q: Why do I see "Human verification confirmed" even without setting keys?
**A:** In development mode (`NODE_ENV !== 'production'`), if no keys are provided, the widget defaults to Cloudflare's official `Always Passes` test key so developers and testers can use the app offline or before creating a Cloudflare account.
### Q: What if a user has JavaScript disabled or an aggressive ad-blocker?
**A:** Cloudflare Turnstile is served from `challenges.cloudflare.com`, which is whitelisted on standard ad-blockers as a privacy-respecting CAPTCHA alternative. If a network error prevents loading, `/api/try/[toolId]` returns a friendly `retryable: true` message instructing the user to refresh.
---
## 8. Direct Backend Server Protection Architecture
To ensure **no one can send requests to the actual backend server on its own**, the system employs a two-tier zero-trust defense:
```
[ External Client / Bot / Scraper ]
│
│ (A) Attempt direct curl/script to /api/try/* without Turnstile token
▼
┌────────────────────────────────────────────────────────┐
│ Next.js Proxy Server (/api/try/[toolId]) │
│ 1. Validate 'cf-turnstile-response' / 'x-turnstile' │
│ 2. Missing/Invalid Token -> HTTP 403 FORBIDDEN │
│ Zero network traffic dispatched to backend │
└────────────────────────────────────────────────────────┘
│
│ (B) Valid Turnstile Token Verified with Cloudflare API
▼
┌────────────────────────────────────────────────────────┐
│ Next.js Server-Side Request Builder │
│ - Injects internal API_SECRET_DEFAULT (e.g. 'abcdef') │
│ - Backend URLs & secrets NEVER reach the browser │
└────────────────────────────────────────────────────────┘
│
│ (C) Proxied Server-to-Server Request with Secret
▼
┌────────────────────────────────────────────────────────┐
│ Actual FastAPI Backend (GPU Inference Servers) │
│ - Validates internal secretKey in middleware │
│ - Direct requests without secret -> HTTP 401 │
└────────────────────────────────────────────────────────┘
```
1. **Gatekeeper Enforcement**: All client requests target `/api/try/[toolId]`. If the incoming request lacks a valid Cloudflare Turnstile token, Next.js rejects it immediately with `403 Forbidden` (`BOT_VERIFICATION_FAILED`). No network packets are sent to the actual backend.
2. **Zero Client Secret Leakage**: The backend's real URLs (`https://apigp0006.creinnovations.in` or local FastAPI ports) and the backend authentication secret (`API_SECRET_DEFAULT`) exist exclusively in server-side environment variables. They are never exported into client JavaScript bundles.
3. **Backend-Side Defense**: The actual backend server enforces `FirebaseAppCheckMiddleware` / `secretKey` verification on all incoming requests. Any direct request sent to the backend server bypassing the Next.js proxy will lack the secret key and receive `401 Unauthorized` (`The provided secret key is invalid.`).
-229
View File
@@ -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. |
+13 -13
View File
@@ -8848,7 +8848,7 @@
"chips": [],
"curl": "",
"desc": "AnimeGAN & Cartoon Effects",
"full_url": "https://apigp0006.creinnovations.in/apis/mlm/cartoon_effects/image/",
"full_url": "https://apigp0006.creinnovations.in/apis/mlm/cartoonify_caricature_effects/image/",
"id": "api-cre-aws-cartoon-model",
"method": "POST",
"params": [
@@ -8879,7 +8879,7 @@
"title": "AnimeGAN & Cartoon Effects"
}
],
"full_url": "https://apigp0006.creinnovations.in/apis/mlm/cartoon_effects/image/",
"full_url": "https://apigp0006.creinnovations.in/apis/mlm/cartoonify_caricature_effects/image/",
"id": "api-cre-aws-cartoon-model",
"method": "POST",
"params": [
@@ -10053,7 +10053,7 @@
},
{
"al": "",
"df": "test_ref",
"df": "ref",
"ds": "Reference identifier or style preset key.",
"lc": "multipart/form-data",
"n": "reference",
@@ -10105,7 +10105,7 @@
},
{
"al": "",
"df": "test_ref",
"df": "ref",
"ds": "Reference identifier or style preset key.",
"lc": "multipart/form-data",
"n": "reference",
@@ -10914,7 +10914,7 @@
"chips": [],
"curl": "curl -X POST \"{{base}}:5925/face_swapper/couple_swap/\" \\\n -F \"[email protected]\" \\\n -F \"[email protected]\" \\\n -F \"reference=value\" \\\n -F \"app_name=value\"",
"desc": "Swaps two source faces onto both persons in a pre-stored couple reference template. Both source images are required. Reference template is loaded from server-side storage.",
"full_url": "https://apigp0006.creinnovations.in/apis/mlm/face_swapper/image/",
"full_url": "https://apigp0006.creinnovations.in/apis/mlm/face_swapper/couple_swap/",
"id": "ml-face-swapper-couple",
"method": "POST",
"params": [
@@ -10938,7 +10938,7 @@
},
{
"al": "",
"df": "test_ref",
"df": "ref",
"ds": "Reference identifier or style preset key.",
"lc": "multipart/form-data",
"n": "reference",
@@ -11009,7 +11009,7 @@
},
{
"al": "",
"df": "test_ref",
"df": "ref",
"ds": "Reference identifier or style preset key.",
"lc": "multipart/form-data",
"n": "reference",
@@ -11158,7 +11158,7 @@
},
{
"al": "",
"df": "test_ref",
"df": "ref",
"ds": "Reference identifier or style preset key.",
"lc": "multipart/form-data",
"n": "reference",
@@ -11458,7 +11458,7 @@
"chips": [],
"curl": "",
"desc": "Trendy AI Stylization Filter",
"full_url": "https://apigp0006.creinnovations.in/apis/mlm/trendy/image/",
"full_url": "https://apigp0006.creinnovations.in/apis/mlm/trendy/go/",
"id": "api-trendy",
"method": "POST",
"params": [
@@ -11482,7 +11482,7 @@
},
{
"al": "",
"df": "None",
"df": "http://127.0.0.1:5925/cartoonify_caricature_effects/",
"ds": "Target base API URL (e.g. `http://127.0.0.1:8005/sdxl/dress_pattern/`).",
"lc": "multipart/form-data",
"n": "api_url",
@@ -11491,7 +11491,7 @@
},
{
"al": "",
"df": "None",
"df": "image/",
"ds": "Target sub-endpoint (e.g. `image/` or `ping`).",
"lc": "multipart/form-data",
"n": "api_endpoint",
@@ -11601,11 +11601,11 @@
"method": "POST",
"params": [
{
"al": "file",
"al": "file, image",
"df": "None",
"ds": "Input photograph of person wearing clothes to replace.",
"lc": "multipart/form-data",
"n": "image",
"n": "original_image",
"rq": true,
"ty": "file (binary)"
},
@@ -20,7 +20,7 @@
"tryIt": {
"enabled": true,
"endpointRef": {
"id": "ml-new-enhancer-previous",
"id": "ml-new-enhancer",
"defaultVariant": "default"
},
"limits": {
-12
View File
@@ -136,18 +136,6 @@
"subtitle": "Dedicated iOS and Android clients for hardware-accelerated offline batch processing."
}
},
{
"id": "how-it-works",
"type": "howItWorks",
"tier": "workflow",
"tierLabel": "Tier 4: Neural Workflow",
"folderPath": "management/pages/home/sections/how-it-works",
"props": {
"badge": "Neural pipeline",
"title": "How the process works",
"subtitle": "Synchronous GPU inference in volatile memory, returning studio-quality exports in seconds."
}
},
{
"id": "community-reviews",
"type": "reviewsMarquee",
+2 -2
View File
@@ -18,8 +18,8 @@
"hi": "गोपनीयता नीति"
},
"subtitle": {
"en": "Effective Date: November 11, 2026. A legally binding commitment to ephemeral media processing, biometric privacy, and zero server storage.",
"hi": "प्रभावी तिथि: 11 नवंबर, 2026। अल्पकालिक मीडिया प्रोसेसिंग, बायोमेट्रिक गोपनीयता और शून्य सर्वर संग्रहण के लिए कानूनी प्रतिबद्धता।"
"en": "A legally binding commitment to ephemeral media processing, biometric privacy, and zero server storage.",
"hi": "अल्पकालिक मीडिया प्रोसेसिंग, बायोमेट्रिक गोपनीयता और शून्य सर्वर संग्रहण के लिए कानूनी प्रतिबद्धता।"
}
}
},
File diff suppressed because one or more lines are too long
-12
View File
@@ -136,18 +136,6 @@
"subtitle": "Dedicated iOS and Android clients for hardware-accelerated offline batch processing."
}
},
{
"id": "how-it-works",
"type": "howItWorks",
"tier": "workflow",
"tierLabel": "Tier 4: Neural Workflow",
"folderPath": "management/pages/home/sections/how-it-works",
"props": {
"badge": "Neural pipeline",
"title": "How the process works",
"subtitle": "Synchronous GPU inference in volatile memory, returning studio-quality exports in seconds."
}
},
{
"id": "community-reviews",
"type": "reviewsMarquee",
+2 -2
View File
@@ -18,8 +18,8 @@
"hi": "गोपनीयता नीति"
},
"subtitle": {
"en": "Effective Date: November 11, 2026. A legally binding commitment to ephemeral media processing, biometric privacy, and zero server storage.",
"hi": "प्रभावी तिथि: 11 नवंबर, 2026। अल्पकालिक मीडिया प्रोसेसिंग, बायोमेट्रिक गोपनीयता और शून्य सर्वर संग्रहण के लिए कानूनी प्रतिबद्धता।"
"en": "A legally binding commitment to ephemeral media processing, biometric privacy, and zero server storage.",
"hi": "अल्पकालिक मीडिया प्रोसेसिंग, बायोमेट्रिक गोपनीयता और शून्य सर्वर संग्रहण के लिए कानूनी प्रतिबद्धता।"
}
}
},
@@ -20,7 +20,7 @@
"tryIt": {
"enabled": true,
"endpointRef": {
"id": "ml-new-enhancer-previous",
"id": "ml-new-enhancer",
"defaultVariant": "default"
},
"limits": {
File diff suppressed because one or more lines are too long
+10 -5
View File
@@ -62,18 +62,23 @@ const nextConfig = {
key: 'Content-Security-Policy',
value: [
"default-src 'self'",
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://apis.google.com",
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
"font-src 'self' https://fonts.gstatic.com",
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://apis.google.com https://challenges.cloudflare.com",
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://fonts.cdnfonts.com",
"font-src 'self' https://fonts.gstatic.com https://fonts.cdnfonts.com data:",
"img-src 'self' data: blob: https:",
"connect-src 'self' https://*.firebaseapp.com https://*.googleapis.com https://identitytoolkit.googleapis.com https://securetoken.googleapis.com",
"frame-src 'self' https://accounts.google.com",
"connect-src 'self' https://*.firebaseapp.com https://*.googleapis.com https://identitytoolkit.googleapis.com https://securetoken.googleapis.com https://challenges.cloudflare.com",
"frame-src 'self' https://accounts.google.com https://challenges.cloudflare.com",
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
...(isProd ? ["upgrade-insecure-requests"] : []),
].join('; '),
},
// Strict Cache-Control to prevent browsers & CDNs from serving stale HTML
{ key: 'Cache-Control', value: 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0, s-maxage=0' },
{ key: 'Pragma', value: 'no-cache' },
{ key: 'Expires', value: '0' },
{ key: 'Surrogate-Control', value: 'no-store' },
// Block clickjacking
{ key: 'X-Frame-Options', value: 'SAMEORIGIN' },
// Prevent MIME sniffing
-2
View File
@@ -11,8 +11,6 @@
"dependencies": {
"@types/three": "^0.187.0",
"clsx": "^2.1.1",
"firebase": "^13.3.0",
"firebase-admin": "^14.5.1",
"framer-motion": "^14.9.0",
"lenis": "^1.3.27",
"lucide-react": "^0.468.0",
Binary file not shown.

After

Width:  |  Height:  |  Size: 663 B

-140
View File
@@ -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 });
}
}
+57 -1
View File
@@ -6,6 +6,7 @@ import { getToolById, getToolBySlug } from '@/lib/config/loader';
import { getEndpointById } from '@/lib/catalog/loader';
import { checkRateLimits, recordUsage } from '@/lib/api/rateLimiter';
import { checkFileSignature, executeBackendTryIt, isCircuitOpen } from '@/lib/api/requestBuilder';
import { verifyTurnstileToken } from '@/lib/turnstile';
let _visitorCookieMaxAge: number | null = null;
function getVisitorCookieMaxAge(): number {
@@ -80,8 +81,63 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str
return res;
}
// Safely parse FormData or reject unauthorized requests
let formData: FormData;
try {
formData = await req.formData();
} catch {
return NextResponse.json(
{
state: 'failed',
error: {
code: 'BOT_VERIFICATION_FAILED',
message: 'Cloudflare Turnstile verification token is missing or request is invalid. Direct access to the backend is strictly blocked.',
retryable: false,
},
},
{ status: 403 }
);
}
// Cloudflare Turnstile Bot & Abuse Verification (Gatekeeper)
const turnstileToken =
(formData.get('cf-turnstile-response') as string | null) ||
(formData.get('turnstileToken') as string | null) ||
req.headers.get('cf-turnstile-response') ||
req.headers.get('x-turnstile-token');
if (!turnstileToken || turnstileToken.trim() === '') {
return NextResponse.json(
{
state: 'failed',
error: {
code: 'BOT_VERIFICATION_FAILED',
message: 'Cloudflare Turnstile token is required. Automated requests directly to the backend are strictly blocked.',
retryable: true,
},
},
{ status: 403 }
);
}
const turnstileResult = await verifyTurnstileToken(turnstileToken, ip);
if (!turnstileResult.success) {
return NextResponse.json(
{
state: 'failed',
error: {
code: 'BOT_VERIFICATION_FAILED',
message:
turnstileResult.message ||
'Cloudflare Turnstile verification failed. Direct access to the backend is prohibited.',
retryable: true,
},
},
{ status: 403 }
);
}
try {
const formData = await req.formData();
// Primary image extraction: check 'image' first, then common aliases
let file = formData.get('image') as File | null;
+3
View File
@@ -31,6 +31,9 @@ export async function generateMetadata(): Promise<Metadata> {
};
}
export const dynamic = 'force-dynamic';
export const revalidate = 0;
export default function AppsIndexPage() {
const page = getPageConfig('apps');
if (!page) notFound();
+2 -2
View File
@@ -5,8 +5,8 @@ body { margin: 0; background: var(--color-paper); color: var(--color-ink); font-
::selection { background: color-mix(in oklab, var(--color-accent) 22%, transparent); color: var(--color-ink); }
:focus-visible { outline: 2px solid var(--color-focus); outline-offset: 2px; }
a { color: inherit; text-decoration-thickness: 1px; text-underline-offset: 0.16em; }
h1, h2, h3 { margin: 0; font-family: var(--font-display); font-weight: var(--display-weight, 700); font-synthesis: none; letter-spacing: var(--tracking-display); line-height: 1.05; overflow-wrap: break-word; min-width: 0; text-wrap: balance; }
h1 { max-width: 20ch; font-size: var(--text-display); } h2 { max-width: 30ch; font-size: var(--text-section); } h3 { max-width: 40ch; font-size: var(--text-title); line-height: 1.2; }
h1, h2, h3, h4, h5, h6 { margin: 0; font-family: var(--font-display); font-weight: var(--display-weight, 700); font-synthesis: none; letter-spacing: var(--tracking-display); line-height: 1.05; overflow-wrap: break-word; min-width: 0; text-wrap: balance; }
h1 { max-width: none; font-size: var(--text-display); } h2 { max-width: none; font-size: var(--text-section); } h3 { max-width: none; font-size: var(--text-title); line-height: 1.2; }
.lead { font-size: var(--text-lead); line-height: 1.45; max-width: 52ch; }
p { margin: 0; text-wrap: pretty; }
p:not([class]) { max-width: 65ch; }
+15 -3
View File
@@ -4,6 +4,7 @@
/* Hallmark · pre-emit critique: P5 H5 E5 S5 R5 V5 · elegant porcelain cream light studio with sapphire and indigo accents, smooth rounded pill geometry */
@import url("./tokens.css");
@import url("./base.css");
@import url("https://fonts.cdnfonts.com/css/sf-pro-display");
@import url("https://fonts.googleapis.com/css2?family=Geist:wght@300;400;500;600;700;800;900&family=Geist+Mono:wght@400;500&display=swap");
@tailwind base;
@@ -38,6 +39,10 @@
-webkit-perspective: 1000px !important;
}
.font-sf, .font-poppins, .font-inter, .font-display, .font-body, .font-sans {
font-family: var(--font-sf), "SF Pro Display", "SF Pro Text", "SF Pro", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
}
@layer base {
:root {
--color-primary: var(--color-accent);
@@ -48,8 +53,11 @@
--color-surface-card: var(--color-paper-hi);
--theme-radius: 24px;
--theme-max-width: 1440px;
--font-sans: var(--font-body);
--font-serif: var(--font-display);
--font-sf: "SF Pro Display", "SF Pro Text", "SF Pro", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--font-sans: var(--font-sf);
--font-body: var(--font-sf);
--font-serif: var(--font-sf);
--font-display: var(--font-sf);
}
html, body {
@@ -101,7 +109,7 @@
outline-offset: 2px;
}
h1, h2, h3, h4, .font-display {
h1, h2, h3, h4, h5, h6, .font-display {
font-family: var(--font-display);
color: var(--color-ink);
letter-spacing: var(--tracking-display);
@@ -130,6 +138,10 @@
transition-timing-function: var(--ease-out);
}
.studio-sheet:hover {
border-color: #1d4ed8; /* Darker royal blue line on hover */
}
.studio-sheet:hover {
border-color: color-mix(in oklab, var(--color-accent) 40%, var(--color-rule));
box-shadow: var(--shadow-glow);
+56 -36
View File
@@ -1,32 +1,9 @@
import type { Metadata } from 'next';
import { Poppins, Inter, JetBrains_Mono } from 'next/font/google';
import './globals.css';
import { getSiteConfig, getAllCategories, getAllTools } from '@/lib/config/loader';
import { Navbar } from '@/components/ui/Navbar';
import { Footer } from '@/components/ui/Footer';
import { SmoothScrollProvider } from '@/components/ui/SmoothScrollProvider';
import { AuthProvider } from '@/lib/firebase/AuthContext';
import { AuthModal } from '@/components/auth/AuthModal';
const poppinsFont = Poppins({
subsets: ['latin'],
weight: ['300', '400', '500', '600', '700', '800'],
variable: '--font-poppins',
display: 'swap',
});
const interFont = Inter({
subsets: ['latin'],
weight: ['300', '400', '500', '600', '700'],
variable: '--font-inter',
display: 'swap',
});
const monoFont = JetBrains_Mono({
subsets: ['latin'],
variable: '--font-mono',
display: 'swap',
});
export async function generateMetadata(): Promise<Metadata> {
const config = getSiteConfig();
@@ -91,6 +68,13 @@ export async function generateMetadata(): Promise<Metadata> {
},
},
manifest: '/manifest.webmanifest',
icons: {
icon: [
{ url: '/favicon.ico', sizes: 'any' },
{ url: '/brand/icon.svg', type: 'image/svg+xml' },
],
apple: '/brand/icon.svg',
},
appleWebApp: {
capable: true,
statusBarStyle: 'black-translucent',
@@ -162,8 +146,47 @@ export default function RootLayout({
};
return (
<html lang="en" className={`${poppinsFont.variable} ${interFont.variable} ${monoFont.variable} font-sans`}>
<html lang="en" className="font-sans">
<head>
<meta httpEquiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta httpEquiv="Pragma" content="no-cache" />
<meta httpEquiv="Expires" content="0" />
<script
dangerouslySetInnerHTML={{
__html: `
(function() {
try {
// 1. Unregister any stale Service Workers on client devices
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then(function(registrations) {
for (var i = 0; i < registrations.length; i++) {
registrations[i].unregister();
}
});
}
// 2. Clear stale Cache Storage API entries
if ('caches' in window) {
caches.keys().then(function(keys) {
for (var i = 0; i < keys.length; i++) {
caches.delete(keys[i]);
}
});
}
// 3. Automated cache-bust verification
var BUILD_TAG = '20261117_sfpro_v2';
var cachedTag = localStorage.getItem('__cre_build_tag');
if (cachedTag !== BUILD_TAG) {
localStorage.setItem('__cre_build_tag', BUILD_TAG);
if (cachedTag !== null && window.location.search.indexOf('v=') === -1) {
// Perform clean cache-busting reload once for returning visitors
window.location.replace(window.location.pathname + (window.location.search ? window.location.search + '&' : '?') + 'v=' + Date.now());
}
}
} catch(e) {}
})();
`,
}}
/>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(organizationJsonLd) }}
@@ -171,18 +194,15 @@ export default function RootLayout({
</head>
<body className="min-h-screen flex flex-col antialiased bg-paper text-ink relative font-sans overflow-x-clip">
<SmoothScrollProvider>
<AuthProvider>
<a href="#main-content" className="skip-link">Skip to main content</a>
<Navbar
config={config}
currentLocale="en"
categories={categories}
totalToolsCount={tools.length}
/>
<main id="main-content" className="flex-1">{children}</main>
<Footer config={config} currentLocale="en" />
<AuthModal />
</AuthProvider>
<a href="#main-content" className="skip-link">Skip to main content</a>
<Navbar
config={config}
currentLocale="en"
categories={categories}
totalToolsCount={tools.length}
/>
<main id="main-content" className="flex-1">{children}</main>
<Footer config={config} currentLocale="en" />
</SmoothScrollProvider>
</body>
</html>
+3
View File
@@ -45,6 +45,9 @@ export async function generateMetadata(): Promise<Metadata> {
};
}
export const dynamic = 'force-dynamic';
export const revalidate = 0;
export default function PrivacyPage() {
const page = getPageConfig('privacy');
if (!page) notFound();
+5 -4
View File
@@ -12,12 +12,13 @@
--color-paper: oklch(98% 0.006 85); --color-paper-2: oklch(95% 0.008 85); --color-paper-3: oklch(91.5% 0.012 85); --color-paper-hi: oklch(99.2% 0.006 85);
--color-ink: oklch(18% 0.03 260); --color-ink-2: oklch(36% 0.025 260); --color-muted: oklch(52% 0.02 260);
--color-rule: oklch(90% 0.008 260); --color-rule-2: oklch(82% 0.012 260);
--color-accent: oklch(54% 0.24 260); --color-accent-hi: oklch(48% 0.26 265); --color-accent-soft: oklch(96% 0.02 260); --color-accent-ink: oklch(99.2% 0.006 85); --color-focus: oklch(54% 0.24 260);
--color-accent: oklch(48% 0.26 265); --color-accent-hi: oklch(40% 0.28 268); --color-accent-soft: oklch(96% 0.02 260); --color-accent-ink: oklch(99.2% 0.006 85); --color-focus: oklch(48% 0.26 265);
--color-gold: oklch(76% 0.16 75);
--color-dot: color-mix(in oklab, var(--color-ink) 10%, transparent); --color-mark: color-mix(in oklab, var(--color-ink) 25%, transparent);
--font-display: "Geist", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
--font-body: "Geist", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
--font-outlier: "Geist Mono", monospace;
--font-sf: "SF Pro Display", "SF Pro Text", "SF Pro", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--font-display: var(--font-sf);
--font-body: var(--font-sf);
--font-outlier: "SF Pro Display", "SF Pro Text", "SF Pro", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, monospace;
--radius-card: 24px; --radius-pill: 9999px; --rule-hair: 1px;
--shadow-card: 0 10px 30px -10px rgba(15, 23, 42, 0.07), 0 0 0 1px rgba(15, 23, 42, 0.05);
--shadow-sheet: 0 20px 45px -15px rgba(15, 23, 42, 0.09), 0 0 0 1px rgba(15, 23, 42, 0.06);
+3
View File
@@ -45,6 +45,9 @@ export async function generateMetadata(): Promise<Metadata> {
};
}
export const dynamic = 'force-dynamic';
export const revalidate = 0;
export default function TrustPage() {
const page = getPageConfig('trust');
if (!page) notFound();
-379
View File
@@ -1,379 +0,0 @@
'use client';
import React, { useState, useEffect } from 'react';
import {
X,
Mail,
Lock,
User as UserIcon,
Eye,
EyeOff,
AlertCircle,
CheckCircle2,
Sparkles,
ArrowRight,
Loader2,
} from 'lucide-react';
import { useAuth } from '@/lib/firebase/AuthContext';
function GoogleIcon({ className = 'w-4 h-4' }: { className?: string }) {
return (
<svg viewBox="0 0 24 24" className={className} aria-hidden="true">
<path
d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
fill="#4285F4"
/>
<path
d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
fill="#34A853"
/>
<path
d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.06H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.94l2.85-2.22.81-.63z"
fill="#FBBC05"
/>
<path
d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84c.87-2.6 3.3-4.52 6.16-4.52z"
fill="#EA4335"
/>
</svg>
);
}
function parseAuthError(error: any): string {
const code = error?.code || '';
switch (code) {
case 'auth/user-not-found':
case 'auth/wrong-password':
case 'auth/invalid-credential':
return 'Invalid email address or password.';
case 'auth/email-already-in-use':
return 'An account already exists with this email address.';
case 'auth/invalid-email':
return 'Please enter a valid email address.';
case 'auth/weak-password':
return 'Password should be at least 6 characters.';
case 'auth/popup-closed-by-user':
return 'Sign in cancelled before completion.';
case 'auth/too-many-requests':
return 'Too many attempts. Please wait a few moments and try again.';
case 'auth/network-request-failed':
return 'Network error. Please check your internet connection.';
default:
return error?.message || 'Authentication failed. Please try again.';
}
}
export function AuthModal() {
const {
authModalOpen,
authModalMode,
closeAuthModal,
openAuthModal,
signInWithGoogle,
signInWithEmail,
signUpWithEmail,
sendPasswordReset,
isConfigured,
} = useAuth();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [name, setName] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
// Reset form when modal opens or mode changes
useEffect(() => {
setError(null);
setSuccess(null);
setEmail('');
setPassword('');
setName('');
}, [authModalOpen, authModalMode]);
// Handle ESC key to close modal
useEffect(() => {
if (!authModalOpen) return;
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') closeAuthModal();
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [authModalOpen, closeAuthModal]);
if (!authModalOpen) return null;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setSuccess(null);
setLoading(true);
try {
if (authModalMode === 'signin') {
if (!email.trim() || !password) {
setError('Please provide both email and password.');
setLoading(false);
return;
}
await signInWithEmail(email, password);
} else if (authModalMode === 'signup') {
if (!email.trim() || !password) {
setError('Please provide email and password.');
setLoading(false);
return;
}
if (password.length < 6) {
setError('Password must be at least 6 characters.');
setLoading(false);
return;
}
await signUpWithEmail(email, password, name);
} else if (authModalMode === 'reset') {
if (!email.trim()) {
setError('Please enter your account email.');
setLoading(false);
return;
}
await sendPasswordReset(email);
setSuccess('Password reset link sent! Check your inbox.');
}
} catch (err: any) {
setError(parseAuthError(err));
} finally {
setLoading(false);
}
};
const handleGoogleSignIn = async () => {
setError(null);
setSuccess(null);
setLoading(true);
try {
await signInWithGoogle();
} catch (err: any) {
setError(parseAuthError(err));
} finally {
setLoading(false);
}
};
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6 bg-slate-950/60 backdrop-blur-sm animate-in fade-in duration-200"
onClick={(e) => {
if (e.target === e.currentTarget) closeAuthModal();
}}
role="dialog"
aria-modal="true"
aria-labelledby="auth-modal-title"
>
<div className="relative w-full max-w-md bg-paper-hi border border-rule rounded-2xl p-6 sm:p-8 shadow-2xl overflow-hidden motion-safe:transition-all">
{/* Top Close Button */}
<button
onClick={closeAuthModal}
className="absolute right-4 top-4 p-1.5 rounded-full text-slate-400 hover:text-slate-900 hover:bg-slate-100 transition-colors cursor-pointer"
aria-label="Close dialog"
>
<X className="w-4 h-4" />
</button>
{/* Unconfigured Configuration Warning Banner */}
{!isConfigured && (
<div className="mb-5 p-3 rounded-xl bg-amber-500/10 border border-amber-500/20 text-amber-800 text-xs flex items-start gap-2.5">
<AlertCircle className="w-4 h-4 text-amber-600 shrink-0 mt-0.5" />
<div>
<span className="font-semibold block text-amber-900">Firebase Setup Ready</span>
Add your credentials to <code className="font-mono text-[11px] bg-amber-200/50 px-1 py-0.5 rounded">.env.local</code> to activate live authentication.
</div>
</div>
)}
{/* Header */}
<div className="text-center mb-6">
<div className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-accent/10 border border-accent/20 text-accent text-xs font-semibold mb-3">
<Sparkles className="w-3.5 h-3.5" />
<span>CRE Innovations Studio</span>
</div>
<h2 id="auth-modal-title" className="text-2xl font-display font-bold text-ink tracking-tight">
{authModalMode === 'signin' && 'Welcome back'}
{authModalMode === 'signup' && 'Create your account'}
{authModalMode === 'reset' && 'Reset your password'}
</h2>
<p className="mt-1 text-xs sm:text-sm text-slate-500 font-sans">
{authModalMode === 'signin' && 'Sign in to access your cloud studio workspace'}
{authModalMode === 'signup' && 'Start editing with lossless 4K neural vision tools'}
{authModalMode === 'reset' && "Enter your email and we'll send you a password recovery link"}
</p>
</div>
{/* Error & Success Messages */}
{error && (
<div className="mb-4 p-3 rounded-xl bg-rose-500/10 border border-rose-500/20 text-rose-700 text-xs flex items-start gap-2">
<AlertCircle className="w-4 h-4 shrink-0 mt-0.5" />
<span>{error}</span>
</div>
)}
{success && (
<div className="mb-4 p-3 rounded-xl bg-emerald-500/10 border border-emerald-500/20 text-emerald-700 text-xs flex items-start gap-2">
<CheckCircle2 className="w-4 h-4 shrink-0 mt-0.5" />
<span>{success}</span>
</div>
)}
{/* OAuth: Google One-Click Sign In (for signin & signup) */}
{authModalMode !== 'reset' && (
<div className="space-y-4 mb-5">
<button
type="button"
onClick={handleGoogleSignIn}
disabled={loading}
className="w-full h-11 inline-flex items-center justify-center gap-2.5 px-4 rounded-xl bg-white border border-slate-200 hover:border-slate-300 hover:bg-slate-50/80 text-slate-700 font-sans font-semibold text-xs sm:text-sm shadow-xs transition-all active:scale-[0.99] cursor-pointer disabled:opacity-60"
>
<GoogleIcon className="w-4 h-4" />
<span>Continue with Google</span>
</button>
<div className="relative flex items-center justify-center">
<div className="border-t border-slate-200 w-full" />
<span className="bg-paper-hi px-3 text-[11px] font-mono text-slate-400 uppercase tracking-wider">
or with email
</span>
</div>
</div>
)}
{/* Email & Password Form */}
<form onSubmit={handleSubmit} className="space-y-3.5">
{authModalMode === 'signup' && (
<div>
<label className="block text-xs font-semibold text-slate-700 mb-1">Full name</label>
<div className="relative">
<UserIcon className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
<input
type="text"
placeholder="Jane Doe"
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full pl-9 pr-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-xs sm:text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/20"
/>
</div>
</div>
)}
<div>
<label className="block text-xs font-semibold text-slate-700 mb-1">Email address</label>
<div className="relative">
<Mail className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
<input
type="email"
placeholder="[email protected]"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full pl-9 pr-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-xs sm:text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/20"
/>
</div>
</div>
{authModalMode !== 'reset' && (
<div>
<div className="flex items-center justify-between mb-1">
<label className="text-xs font-semibold text-slate-700">Password</label>
{authModalMode === 'signin' && (
<button
type="button"
onClick={() => openAuthModal('reset')}
className="text-[11px] text-accent hover:underline cursor-pointer"
>
Forgot password?
</button>
)}
</div>
<div className="relative">
<Lock className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
<input
type={showPassword ? 'text' : 'password'}
placeholder="••••••••"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="w-full pl-9 pr-10 py-2.5 rounded-xl border border-slate-200 bg-white text-xs sm:text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/20"
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-1"
aria-label={showPassword ? 'Hide password' : 'Show password'}
>
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
</div>
)}
<button
type="submit"
disabled={loading}
className="w-full h-11 inline-flex items-center justify-center gap-2 rounded-xl bg-slate-900 hover:bg-accent text-white font-sans font-semibold text-xs sm:text-sm transition-all shadow-xs hover:shadow-md cursor-pointer active:scale-[0.99] disabled:opacity-50 mt-1"
>
{loading ? (
<Loader2 className="w-4 h-4 animate-spin text-white" />
) : (
<>
<span>
{authModalMode === 'signin' && 'Sign In'}
{authModalMode === 'signup' && 'Create Account'}
{authModalMode === 'reset' && 'Send Reset Link'}
</span>
<ArrowRight className="w-4 h-4" />
</>
)}
</button>
</form>
{/* Footer Mode Switcher */}
<div className="mt-6 text-center text-xs text-slate-500 font-sans">
{authModalMode === 'signin' && (
<p>
Don&apos;t have an account?{' '}
<button
type="button"
onClick={() => openAuthModal('signup')}
className="font-semibold text-accent hover:underline cursor-pointer"
>
Sign up
</button>
</p>
)}
{authModalMode === 'signup' && (
<p>
Already have an account?{' '}
<button
type="button"
onClick={() => openAuthModal('signin')}
className="font-semibold text-accent hover:underline cursor-pointer"
>
Sign in
</button>
</p>
)}
{authModalMode === 'reset' && (
<p>
Remember your password?{' '}
<button
type="button"
onClick={() => openAuthModal('signin')}
className="font-semibold text-accent hover:underline cursor-pointer"
>
Back to Sign in
</button>
</p>
)}
</div>
</div>
</div>
);
}
-159
View File
@@ -1,159 +0,0 @@
'use client';
import React, { useState, useRef, useEffect } from 'react';
import Link from 'next/link';
import {
User as UserIcon,
LogOut,
Sparkles,
ChevronDown,
CheckCircle2,
AlertCircle,
ExternalLink,
} from 'lucide-react';
import { useAuth } from '@/lib/firebase/AuthContext';
export function UserMenu() {
const { user, loading, openAuthModal, logout } = useAuth();
const [dropdownOpen, setDropdownOpen] = useState(false);
const dropdownRef = useRef<HTMLDivElement>(null);
// Close dropdown on click outside
useEffect(() => {
if (!dropdownOpen) return;
const handleClickOutside = (e: MouseEvent) => {
if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
setDropdownOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, [dropdownOpen]);
// Close on Escape key
useEffect(() => {
if (!dropdownOpen) return;
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') setDropdownOpen(false);
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [dropdownOpen]);
if (loading) {
return (
<div className="w-8 h-8 rounded-full bg-slate-200/80 animate-pulse shrink-0" />
);
}
if (!user) {
return (
<button
type="button"
onClick={() => openAuthModal('signin')}
className="inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-full text-xs sm:text-sm font-sans font-semibold text-slate-700 hover:text-slate-950 bg-paper-2/90 hover:bg-paper-hi border border-rule transition-colors cursor-pointer active:scale-[0.98]"
aria-label="Sign in to your account"
>
<UserIcon className="w-3.5 h-3.5 text-accent" />
<span>Sign In</span>
</button>
);
}
const initial = (user.displayName || user.email || 'U').charAt(0).toUpperCase();
return (
<div className="relative shrink-0" ref={dropdownRef}>
<button
type="button"
onClick={() => setDropdownOpen(!dropdownOpen)}
className="inline-flex items-center gap-2 p-1 pr-2 rounded-full border border-rule bg-paper-hi hover:bg-slate-50 transition-colors shadow-2xs cursor-pointer focus:outline-none focus:ring-2 focus:ring-accent/20"
aria-expanded={dropdownOpen}
aria-haspopup="true"
aria-label="User account menu"
>
{user.photoURL ? (
<img
src={user.photoURL}
alt={user.displayName || 'User profile'}
className="w-7 h-7 rounded-full object-cover border border-slate-200"
/>
) : (
<div className="w-7 h-7 rounded-full bg-accent/15 text-accent font-sans font-bold text-xs flex items-center justify-center border border-accent/20">
{initial}
</div>
)}
<span className="hidden sm:inline text-xs font-sans font-medium text-slate-800 max-w-[100px] truncate">
{user.displayName || user.email?.split('@')[0]}
</span>
<ChevronDown className={`w-3.5 h-3.5 text-slate-400 transition-transform ${dropdownOpen ? 'rotate-180' : ''}`} />
</button>
{dropdownOpen && (
<div
className="absolute right-0 mt-2 w-64 rounded-2xl bg-paper-hi border border-rule shadow-2xl p-2 z-50 animate-in fade-in-0 zoom-in-95 duration-150"
role="menu"
>
{/* User Profile Summary */}
<div className="p-3 border-b border-rule">
<div className="font-semibold text-xs text-slate-900 truncate">
{user.displayName || 'Studio Member'}
</div>
<div className="text-[11px] font-mono text-slate-500 truncate mt-0.5">
{user.email}
</div>
{user.emailVerified ? (
<span className="inline-flex items-center gap-1 text-[10px] text-emerald-600 mt-1.5 font-medium">
<CheckCircle2 className="w-3 h-3" />
<span>Verified Account</span>
</span>
) : (
<span className="inline-flex items-center gap-1 text-[10px] text-amber-600 mt-1.5 font-medium">
<AlertCircle className="w-3 h-3" />
<span>Unverified Email</span>
</span>
)}
</div>
{/* Quick Links */}
<div className="py-1">
<Link
href="/tools"
onClick={() => setDropdownOpen(false)}
className="flex items-center gap-2.5 px-3 py-2 rounded-xl text-xs font-sans text-slate-700 hover:bg-slate-100 hover:text-slate-950 transition-colors"
role="menuitem"
>
<Sparkles className="w-3.5 h-3.5 text-accent" />
<span>Studio Workspaces</span>
</Link>
<Link
href="/apps"
onClick={() => setDropdownOpen(false)}
className="flex items-center gap-2.5 px-3 py-2 rounded-xl text-xs font-sans text-slate-700 hover:bg-slate-100 hover:text-slate-950 transition-colors"
role="menuitem"
>
<ExternalLink className="w-3.5 h-3.5 text-slate-400" />
<span>Mobile App Suite</span>
</Link>
</div>
{/* Sign Out */}
<div className="pt-1 border-t border-rule">
<button
type="button"
onClick={async () => {
setDropdownOpen(false);
await logout();
}}
className="w-full flex items-center gap-2.5 px-3 py-2 rounded-xl text-xs font-sans text-rose-600 hover:bg-rose-50 transition-colors cursor-pointer font-medium"
role="menuitem"
>
<LogOut className="w-3.5 h-3.5" />
<span>Sign Out</span>
</button>
</div>
</div>
)}
</div>
);
}
+1 -1
View File
@@ -39,7 +39,7 @@ export function VideoText({
fontWeight = 900,
textAnchor = 'start',
dominantBaseline = 'central',
fontFamily = 'var(--font-display), var(--font-poppins), system-ui, sans-serif',
fontFamily = 'var(--font-display), var(--font-inter), system-ui, sans-serif',
poster,
}: VideoTextProps) {
const rawId = useId();
+1 -1
View File
@@ -42,7 +42,7 @@ export function AppCardsSection({
{apps.map((app) => (
<div
key={app.id}
className="bg-white rounded-3xl p-7 border border-slate-900/[0.08] shadow-cream-sm hover:shadow-cream-md hover:border-blue-400 hover:-translate-y-1 transition-all duration-300 flex flex-col justify-between preserve-3d"
className="bg-white rounded-3xl p-7 border border-slate-900/[0.08] shadow-cream-sm hover:shadow-cream-md hover:border-blue-700 hover:-translate-y-1 transition-all duration-300 flex flex-col justify-between preserve-3d"
>
<div>
{/* Header: Icon & Rating */}
+1 -1
View File
@@ -96,7 +96,7 @@ export function AppPickerSection({
<Icon className="w-5 h-5" />
</div>
<div>
<p className="font-display font-bold text-base text-slate-900">
<p className="font-inter font-bold text-base text-slate-900">
{opt.title}
</p>
<p className="text-xs text-slate-600 mt-1 leading-relaxed font-normal">
+4 -4
View File
@@ -44,10 +44,10 @@ export function FaqSection({
const displayItems = items && items.length > 0 ? items : defaultItems;
return (
<section id="faq" className="py-16 sm:py-24 bg-paper border-b border-rule relative">
<div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 space-y-10">
{/* Section Header */}
<div className="space-y-2 border-b border-rule pb-5">
<section id="faq" className="py-8 sm:py-12 bg-paper relative">
<div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 space-y-6">
{/* Section Header without thin separator */}
<div className="space-y-1.5 pb-1">
<h2 className="text-3xl sm:text-4xl font-display font-bold text-ink tracking-tight">
<KineticText>{resolvedTitle}</KineticText>
</h2>
+103 -52
View File
@@ -52,10 +52,10 @@ function HeroHeadlineItem({
<AnimatedShinyText
shimmerWidth={220}
hoverOnly={true}
className="font-display font-black text-ink tracking-tight inline-block cursor-pointer select-none overflow-visible pb-[0.25em] -mb-[0.25em]"
className="font-display font-black font-[950] text-ink tracking-tight inline-block cursor-pointer select-none overflow-visible pb-[0.25em] -mb-[0.25em] [text-shadow:_0_0.5px_0_currentColor]"
>
{isEntranceDone ? (
<span className="font-display font-black text-ink tracking-tight inline-block overflow-visible pb-[0.25em] -mb-[0.25em]">
<span className="font-display font-black font-[950] text-ink tracking-tight inline-block overflow-visible pb-[0.25em] -mb-[0.25em] [text-shadow:_0_0.5px_0_currentColor]">
{text}
</span>
) : (
@@ -67,7 +67,7 @@ function HeroHeadlineItem({
startOnView={false}
accessible={false}
as="span"
className="font-display font-black text-ink tracking-tight inline-block overflow-visible pb-[0.25em] -mb-[0.25em]"
className="font-display font-black font-[950] text-ink tracking-tight inline-block overflow-visible pb-[0.25em] -mb-[0.25em] [text-shadow:_0_0.5px_0_currentColor]"
segmentClassName="inline-block whitespace-pre overflow-visible pb-[0.25em] -mb-[0.25em]"
>
{text}
@@ -201,6 +201,11 @@ export function HeroSection({
const resolvedTitle = resolveLocalised(title, locale) || 'Creative studio';
const resolvedSubtitle = resolveLocalised(subtitle, locale);
const isTrustOrPrivacy =
resolvedTitle.toLowerCase().includes('trust') ||
resolvedTitle.toLowerCase().includes('privacy') ||
resolvedTitle.toLowerCase().includes('security');
return (
<section className="relative pt-24 sm:pt-28 pb-16 sm:pb-20 text-center bg-paper border-b border-rule overflow-hidden">
{/* Layered Studio Lighting Ambient Glow */}
@@ -216,25 +221,37 @@ export function HeroSection({
{/* Layered Light Rays */}
<LightRays className="opacity-40" />
<div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 space-y-6 relative z-10">
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 space-y-6 relative z-10">
<BlurFade delay={0.06}>
<div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-paper-hi border border-rule text-xs font-body text-ink shadow-xs">
<span className="w-2 h-2 rounded-full bg-accent animate-pulse" />
<span className="font-semibold text-accent">Studio Neural Directory</span>
<span className="font-semibold text-accent">
{isTrustOrPrivacy ? 'Security & Biometric Architecture' : 'Studio Neural Directory'}
</span>
<span className="w-1 h-1 rounded-full bg-muted/40" />
<span className="text-muted">Direct browser trials</span>
<span className="text-muted">
{isTrustOrPrivacy ? 'Zero photo retention' : 'Direct browser trials'}
</span>
</div>
</BlurFade>
<BlurFade delay={0.12}>
<h1 className="text-3xl sm:text-5xl lg:text-6xl font-display font-extrabold text-ink tracking-tight text-balance">
<KineticText>{resolvedTitle}</KineticText>
<h1 className="text-3xl sm:text-4xl md:text-5xl lg:text-6xl font-display font-extrabold text-ink tracking-tight max-w-4xl mx-auto leading-[1.12]">
{resolvedTitle.includes('\n') ? (
resolvedTitle.split('\n').map((line, idx) => (
<span key={idx} className="block">
<KineticText>{line.trim()}</KineticText>
</span>
))
) : (
<KineticText>{resolvedTitle}</KineticText>
)}
</h1>
</BlurFade>
{resolvedSubtitle && (
<BlurFade delay={0.18}>
<p className="text-sm sm:text-base lg:text-lg text-ink-2 font-body max-w-xl mx-auto leading-relaxed text-pretty">
<p className="text-sm sm:text-base lg:text-lg text-ink-2 font-body max-w-2xl mx-auto leading-relaxed text-pretty">
{resolvedSubtitle}
</p>
</BlurFade>
@@ -243,28 +260,59 @@ export function HeroSection({
{/* Studio Capability Highlights */}
<BlurFade delay={0.22}>
<div className="pt-1 flex flex-wrap items-center justify-center gap-2 text-xs font-body text-muted">
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-paper-hi/90 border border-rule shadow-2xs">
<Sparkles className="w-3.5 h-3.5 text-accent" />
<span>12 neural models</span>
</span>
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-paper-hi/90 border border-rule shadow-2xs">
<ShieldCheck className="w-3.5 h-3.5 text-emerald-600" />
<span>Zero server storage</span>
</span>
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-paper-hi/90 border border-rule shadow-2xs">
<Zap className="w-3.5 h-3.5 text-amber-500" />
<span>Live comparison sliders</span>
</span>
{isTrustOrPrivacy ? (
<>
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-paper-hi/90 border border-rule shadow-2xs">
<ShieldCheck className="w-3.5 h-3.5 text-emerald-600" />
<span>0-Second server retention</span>
</span>
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-paper-hi/90 border border-rule shadow-2xs">
<Zap className="w-3.5 h-3.5 text-blue-600" />
<span>Volatile RAM only</span>
</span>
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-paper-hi/90 border border-rule shadow-2xs">
<Sparkles className="w-3.5 h-3.5 text-accent" />
<span>Zero AI model training</span>
</span>
</>
) : (
<>
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-paper-hi/90 border border-rule shadow-2xs">
<Sparkles className="w-3.5 h-3.5 text-accent" />
<span>12 neural models</span>
</span>
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-paper-hi/90 border border-rule shadow-2xs">
<ShieldCheck className="w-3.5 h-3.5 text-emerald-600" />
<span>Zero server storage</span>
</span>
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-paper-hi/90 border border-rule shadow-2xs">
<Zap className="w-3.5 h-3.5 text-amber-500" />
<span>Live comparison sliders</span>
</span>
</>
)}
</div>
</BlurFade>
<BlurFade delay={0.26}>
<div className="flex flex-wrap items-center justify-center gap-4 pt-2">
<RainbowButton href="#tools-catalog">
<span>Browse all tools</span>
<ArrowRight className="w-4 h-4 ml-1.5 inline" aria-hidden="true" />
</RainbowButton>
<InteractiveHoverButton text="Mobile apps suite" href="/apps" />
{isTrustOrPrivacy ? (
<>
<RainbowButton href="/tools">
<span>Explore Free AI Tools</span>
<ArrowRight className="w-4 h-4 ml-1.5 inline" aria-hidden="true" />
</RainbowButton>
<InteractiveHoverButton text="View Privacy Policy" href="/privacy" />
</>
) : (
<>
<RainbowButton href="#tools-catalog">
<span>Browse all tools</span>
<ArrowRight className="w-4 h-4 ml-1.5 inline" aria-hidden="true" />
</RainbowButton>
<InteractiveHoverButton text="Mobile apps suite" href="/apps" />
</>
)}
</div>
</BlurFade>
</div>
@@ -276,32 +324,35 @@ export function HeroSection({
return (
<section
id="hero-section"
className="relative min-h-[90vh] sm:min-h-screen flex items-center overflow-hidden bg-paper pt-20 sm:pt-24 pb-14 sm:pb-20 lg:pb-24"
className="relative min-h-[80vh] sm:min-h-[85vh] flex items-center overflow-hidden bg-paper pt-16 sm:pt-20 pb-8 sm:pb-12"
>
{/* Background Layer 1: High-Resolution Responsive Background Image */}
<div className="absolute inset-0 z-0 overflow-hidden">
<picture>
<picture
className="absolute inset-0 block w-full h-full"
style={{
maskImage: 'linear-gradient(to top, transparent 0%, rgba(0,0,0,0.3) 15%, black 45%)',
WebkitMaskImage: 'linear-gradient(to top, transparent 0%, rgba(0,0,0,0.3) 15%, black 45%)',
}}
>
<source media="(max-width: 768px)" srcSet="/management/pages/home/hero_mobile.webp" type="image/webp" />
<source media="(max-width: 768px)" srcSet="/management/pages/home/hero_mobile.jpg" type="image/jpeg" />
<source srcSet="/management/pages/home/hero_desktop.webp" type="image/webp" />
<img
src="/management/pages/home/hero_desktop.jpg"
alt="CRE Innovations Photo Studio"
className="w-full h-full object-cover object-[75%_25%] sm:object-right select-none pointer-events-none opacity-70 sm:opacity-90 brightness-[0.98] sm:brightness-[0.97] translate-y-0 sm:translate-y-6 sm:scale-[1.02]"
className="w-full h-full object-cover object-[right_top] sm:object-[right_top] -translate-y-3 sm:-translate-y-5 scale-[1.03] sm:scale-[1.04] origin-top-right select-none pointer-events-none opacity-85 sm:opacity-95 brightness-[0.98] sm:brightness-[0.97]"
loading="eager"
decoding="sync"
/>
</picture>
{/* Dynamic Studio Gradient Feathering (Light Theme Porcelain Scrims) */}
{/* Top Edge Feathering */}
<div className="absolute inset-x-0 top-0 h-28 sm:h-36 bg-gradient-to-b from-paper from-40% via-paper/90 via-70% to-transparent pointer-events-none" />
{/* Left Side Scrim for Desktop: Ensures 100% typography contrast while keeping the photography vibrant */}
<div className="absolute inset-0 bg-gradient-to-r from-paper via-paper/85 via-35% to-transparent to-60% hidden sm:block pointer-events-none" />
{/* Mobile Scrim: Studio porcelain gradient covering headline, subtitle, and action buttons (top 70%), transitioning smoothly into vibrant photography */}
<div className="absolute inset-x-0 top-0 h-[70%] bg-gradient-to-b from-paper from-25% via-paper/92 via-65% to-transparent sm:hidden pointer-events-none" />
{/* Soft Bottom Fade */}
<div className="absolute inset-x-0 bottom-0 h-20 sm:h-24 bg-gradient-to-t from-paper via-paper/85 via-45% to-transparent pointer-events-none" />
{/* Ultra-Deep Soft Bottom Fade: Seamlessly dissolves into pure white/porcelain theme */}
<div className="absolute inset-x-0 bottom-0 h-48 sm:h-72 md:h-96 lg:h-[450px] bg-gradient-to-t from-paper from-15% via-paper/95 via-40% via-paper/60 via-70% to-transparent to-100% pointer-events-none" />
<div className="absolute inset-x-0 bottom-0 h-24 sm:h-36 bg-gradient-to-t from-paper to-paper/90 pointer-events-none" />
</div>
{/* Background Layer 2: Magic UI Atmospheric Light Rays */}
@@ -314,36 +365,36 @@ export function HeroSection({
/>
{/* Content Container (Website Introduction, Visual Hierarchy, Kinetic Motion) */}
<div className="relative z-10 max-w-[1720px] w-full mx-auto px-4 sm:px-8 lg:px-14 flex flex-col justify-center min-h-[85vh] sm:min-h-[90vh]">
<div className="max-w-2xl sm:max-w-3xl lg:max-w-4xl space-y-6 sm:space-y-8 text-center sm:text-left mx-auto sm:mx-0">
<div className="relative z-10 max-w-[1720px] w-full mx-auto px-4 sm:px-8 lg:px-14 flex flex-col justify-center min-h-[75vh] sm:min-h-[80vh]">
<div className="max-w-2xl sm:max-w-3xl lg:max-w-4xl space-y-4 sm:space-y-6 text-center sm:text-left mx-auto sm:mx-0">
{/* Masterpiece 3-Line Headline:
Line 1: Imagine. -> Magic UI TextAnimate on first, AnimatedShinyText on hover
Line 2: Transform. -> Magic UI TextAnimate on first, AnimatedShinyText on hover
Line 3: Create Impossible -> Simple bluish-purple accent */}
Line 1: Imagine -> Magic UI TextAnimate on first, AnimatedShinyText on hover
Line 2: Transform -> Magic UI TextAnimate on first, AnimatedShinyText on hover
Line 3: Create Impossible -> Bold bluish-purple accent */}
<div className="space-y-0.5 sm:space-y-1">
<h1 className="sr-only">Imagine. Transform. Create Impossible.</h1>
<h1 className="sr-only">Imagine Transform Create Impossible</h1>
{/* Line 1 - Imagine. with Magic UI TextAnimate (black) -> AnimatedShinyText on hover */}
<div className="text-4xl sm:text-6xl md:text-7xl lg:text-8xl font-display font-black tracking-tight leading-[1.22] sm:leading-[1.18] pb-2 sm:pb-3 block overflow-visible">
<HeroHeadlineItem text="Imagine." delay={0.08} />
{/* Line 1 - Imagine */}
<div className="text-3xl sm:text-5xl md:text-6xl lg:text-7xl font-display font-black font-[950] tracking-tight leading-[1.2] sm:leading-[1.15] pb-1.5 sm:pb-2 block overflow-visible [text-shadow:_0_0.5px_0_currentColor]">
<HeroHeadlineItem text="Imagine" delay={0.08} />
</div>
{/* Line 2 - Transform. with Magic UI TextAnimate (black) -> AnimatedShinyText on hover */}
<div className="text-4xl sm:text-6xl md:text-7xl lg:text-8xl font-display font-black tracking-tight leading-[1.22] sm:leading-[1.18] pb-2 sm:pb-3 block overflow-visible">
<HeroHeadlineItem text="Transform." delay={0.28} />
{/* Line 2 - Transform */}
<div className="text-3xl sm:text-5xl md:text-6xl lg:text-7xl font-display font-black font-[950] tracking-tight leading-[1.2] sm:leading-[1.15] pb-1.5 sm:pb-2 block overflow-visible [text-shadow:_0_0.5px_0_currentColor]">
<HeroHeadlineItem text="Transform" delay={0.28} />
</div>
{/* Line 3 - Create Impossible: Simple bluish-purple accent text */}
<div className="text-4xl sm:text-6xl md:text-7xl lg:text-8xl font-display font-extrabold tracking-tight bg-gradient-to-r from-blue-600 via-indigo-600 to-purple-600 bg-clip-text text-transparent leading-[1.22] sm:leading-[1.18] pt-1 block overflow-visible">
{/* Line 3 - Create Impossible */}
<div className="text-3xl sm:text-5xl md:text-6xl lg:text-7xl font-display font-black font-[950] tracking-tight bg-gradient-to-r from-blue-600 via-indigo-600 to-purple-600 bg-clip-text text-transparent leading-[1.2] sm:leading-[1.15] pt-0.5 block overflow-visible [text-shadow:_0_0.5px_0_rgba(37,99,235,0.2)]">
Create Impossible
</div>
</div>
{/* Subtitle */}
{/* Subtitle - reduced by 1 */}
<BlurFade delay={0.16}>
<div className="space-y-4 max-w-xl mx-auto sm:mx-0">
<p className="text-base sm:text-xl md:text-2xl text-ink-2 font-body font-normal leading-relaxed text-pretty">
<div className="space-y-3 max-w-xl mx-auto sm:mx-0">
<p className="text-sm sm:text-lg md:text-xl text-ink-2 font-body font-normal leading-relaxed text-pretty">
Turn ordinary moments into extraordinary visual art. Instant and private photo transformation right in your browser with hardware acceleration.
</p>
</div>
@@ -134,7 +134,7 @@ export function RecommendedAppsSection({
return (
<section
id="recommended-apps"
className="py-16 sm:py-24 px-4 sm:px-6 md:px-8 lg:px-10 bg-paper border-b border-rule relative overflow-hidden"
className="py-8 sm:py-12 px-4 sm:px-6 md:px-8 lg:px-10 bg-paper relative overflow-hidden"
>
{/* Studio Lighting Ambient Glow */}
<div
@@ -146,9 +146,9 @@ export function RecommendedAppsSection({
aria-hidden="true"
/>
<div className="max-w-container mx-auto space-y-10 relative z-10">
{/* Section Header */}
<div className="max-w-2xl space-y-2 border-b border-rule pb-5">
<div className="max-w-container mx-auto space-y-6 relative z-10">
{/* Section Header without thin separator */}
<div className="max-w-2xl space-y-1.5 pb-1">
<div className="flex items-center gap-2">
<span className="w-2 h-2 rounded-full bg-accent animate-pulse" aria-hidden="true" />
<span className="text-xs font-semibold text-accent font-body">
@@ -175,7 +175,7 @@ export function RecommendedAppsSection({
return (
<div
key={slug}
className="group relative studio-sheet p-6 sm:p-7 rounded-3xl bg-paper-hi border border-rule shadow-sheet hover:border-accent hover:shadow-glow hover:-translate-y-1 motion-safe:transition-[border-color,box-shadow,transform] duration-200 flex flex-col justify-between overflow-hidden"
className="group relative studio-sheet p-6 sm:p-7 rounded-3xl bg-paper-hi border border-rule shadow-sheet hover:border-blue-700 hover:shadow-glow hover:-translate-y-1 motion-safe:transition-[border-color,box-shadow,transform] duration-200 flex flex-col justify-between overflow-hidden"
>
{/* Colorful ambient corner glow */}
<div
@@ -137,7 +137,7 @@ export function ReviewsMarqueeSection({
return (
<section
id="user-reviews"
className="py-16 sm:py-24 bg-paper border-b border-rule relative overflow-hidden"
className="py-8 sm:py-12 bg-paper relative overflow-hidden"
>
{/* Studio Lighting Ambient Glow */}
<div
@@ -149,9 +149,9 @@ export function ReviewsMarqueeSection({
aria-hidden="true"
/>
<div className="max-w-container mx-auto px-4 sm:px-6 md:px-8 lg:px-10 space-y-10 relative z-10">
{/* Section Header */}
<div className="max-w-2xl space-y-2 border-b border-rule pb-5">
<div className="max-w-container mx-auto px-4 sm:px-6 md:px-8 lg:px-10 space-y-6 relative z-10">
{/* Section Header without thin separator */}
<div className="max-w-2xl space-y-1.5 pb-1">
<div className="flex items-center gap-2">
<span className="w-2 h-2 rounded-full bg-accent animate-pulse" aria-hidden="true" />
<span className="text-xs font-semibold text-accent font-body">
@@ -182,7 +182,7 @@ export function ReviewsMarqueeSection({
{displayReviews.map((rev, i) => (
<div
key={i}
className="w-[320px] sm:w-[380px] p-5 sm:p-6 mx-3 rounded-3xl bg-paper-hi border border-rule shadow-sheet hover:border-accent hover:shadow-glow hover:-translate-y-0.5 motion-safe:transition-[border-color,box-shadow,transform] duration-200 flex flex-col justify-between"
className="w-[320px] sm:w-[380px] p-5 sm:p-6 mx-3 rounded-3xl bg-paper-hi border border-rule shadow-sheet hover:border-blue-700 hover:shadow-glow hover:-translate-y-0.5 motion-safe:transition-[border-color,box-shadow,transform] duration-200 flex flex-col justify-between"
>
<div>
{/* Top Bar: Tool Pill & 5 Stars */}
+61 -12
View File
@@ -79,26 +79,75 @@ export function RichTextSection({ markdown = '' }: RichTextSectionProps) {
const headers = tableRows[0];
const rows = tableRows.slice(2); // Skip separator row
const isComparisonTable = headers.some(
(h) =>
h.toLowerCase().includes('standard') ||
h.toLowerCase().includes('cre innovations') ||
h.toLowerCase().includes('architecture')
);
const tableNode = (
<div key={`table-${keyIdx}`} className="my-6 overflow-x-auto rounded-2xl border border-slate-200 shadow-2xs">
<table className="w-full text-left text-xs font-sans">
<thead className="bg-slate-100 text-slate-900 uppercase font-bold tracking-wider border-b border-slate-200">
<thead className="border-b border-slate-200">
<tr>
{headers.map((h, hIdx) => (
<th key={hIdx} className="px-4 py-3">
{renderInline(h.trim())}
</th>
))}
{headers.map((h, hIdx) => {
let thClass = "px-4 py-3.5 uppercase font-bold tracking-wider text-xs";
if (isComparisonTable) {
if (hIdx === 0) thClass += " bg-slate-100 text-slate-900";
else if (hIdx === 1) thClass += " bg-rose-100/70 text-rose-900 border-x border-rose-200/80";
else if (hIdx === 2) thClass += " bg-emerald-100/80 text-emerald-950 border-r border-emerald-200/90";
} else {
thClass += " bg-slate-100 text-slate-900";
}
return (
<th key={hIdx} className={thClass}>
{renderInline(h.trim())}
</th>
);
})}
</tr>
</thead>
<tbody className="divide-y divide-slate-100 bg-white">
{rows.map((row, rIdx) => (
<tr key={rIdx} className="hover:bg-slate-50/80 transition-colors">
{row.map((cell, cIdx) => (
<td key={cIdx} className="px-4 py-3 text-slate-700 leading-relaxed">
{renderInline(cell.trim())}
</td>
))}
<tr key={rIdx} className="hover:brightness-98 transition-all">
{row.map((cell, cIdx) => {
let tdClass = "px-4 py-3.5 leading-relaxed text-xs";
let contentNode: React.ReactNode = renderInline(cell.trim());
if (isComparisonTable) {
if (cIdx === 0) {
tdClass += " font-semibold text-slate-800 bg-slate-50/60";
} else if (cIdx === 1) {
// Light reddish cell for "not good" / standard cloud editors
tdClass += " bg-rose-50/50 text-rose-950 border-x border-rose-100/70 font-medium";
contentNode = (
<span className="inline-flex items-center gap-2">
<span className="w-1.5 h-1.5 rounded-full bg-rose-500 shrink-0" aria-hidden="true" />
<span>{renderInline(cell.trim())}</span>
</span>
);
} else if (cIdx === 2) {
// Light greenish cell for "good" / CRE Innovations architecture
tdClass += " bg-emerald-50/70 text-emerald-950 border-r border-emerald-100/80 font-semibold";
contentNode = (
<span className="inline-flex items-center gap-1.5">
<CheckCircle2 className="w-4 h-4 text-emerald-600 shrink-0 inline" aria-hidden="true" />
<span>{renderInline(cell.trim())}</span>
</span>
);
}
} else {
tdClass += " text-slate-700";
}
return (
<td key={cIdx} className={tdClass}>
{contentNode}
</td>
);
})}
</tr>
))}
</tbody>
@@ -106,7 +106,7 @@ export function ShiftableToolsGridSection({
const row2 = displayItems.slice(4, 8);
return (
<section id="our-tools" className="py-16 sm:py-24 px-4 sm:px-6 md:px-8 lg:px-10 bg-paper border-b border-rule relative overflow-hidden">
<section id="our-tools" className="py-8 sm:py-12 px-4 sm:px-6 md:px-8 lg:px-10 bg-paper relative overflow-hidden">
{/* Studio Lighting Ambient Glow */}
<div
className="pointer-events-none absolute top-10 left-10 w-[550px] h-[350px] [background:radial-gradient(circle_at_center,color-mix(in_oklab,var(--color-accent)_10%,transparent)_0%,transparent_70%)]"
@@ -121,9 +121,9 @@ export function ShiftableToolsGridSection({
aria-hidden="true"
/>
<div className="max-w-container mx-auto space-y-10 relative z-10">
{/* Section Header - Clean editorial layout with kinetic typography */}
<div className="max-w-2xl space-y-2 border-b border-rule pb-5">
<div className="max-w-container mx-auto space-y-6 relative z-10">
{/* Section Header - Clean editorial layout without thin separator */}
<div className="max-w-2xl space-y-1.5 pb-1">
<h2 className="text-3xl sm:text-4xl font-display font-bold text-ink tracking-tight">
<KineticText>{title}</KineticText>
</h2>
@@ -164,7 +164,7 @@ function MobileVerticalToolsList({ items }: { items: ToolMediaItem[] }) {
<div className="flex flex-col gap-8 w-full">
{items.map((item) => (
<div key={item.id} className="w-full flex flex-col">
<div className="relative w-full h-[230px] rounded-2xl overflow-hidden bg-paper-2 border border-rule/80 hover:border-accent transition-[border-color,box-shadow]">
<div className="relative w-full h-[230px] rounded-2xl overflow-hidden bg-paper-2 border border-rule/80 hover:border-blue-700 transition-[border-color,box-shadow]">
<ToolWindowMedia item={item} isHovered={false} />
<Link
href={`/tools/${item.slug}`}
@@ -208,7 +208,7 @@ function ShiftableRow({ items }: { items: ToolMediaItem[] }) {
style={{ flexGrow: flexGrowValue }}
>
<div className={`relative w-full h-[220px] lg:h-[240px] rounded-2xl overflow-hidden bg-paper-2 border transition-[border-color,box-shadow] duration-500 ease-[cubic-bezier(0.16,1,0.3,1)] ${
isHovered ? 'border-accent shadow-glow' : 'border-rule/80 hover:border-accent/60'
isHovered ? 'border-blue-700 shadow-glow' : 'border-rule/80 hover:border-blue-700'
}`}>
<ToolWindowMedia item={item} isHovered={isHovered} />
+28 -28
View File
@@ -614,7 +614,7 @@ function ToolCard({
const toolName = resolveLocalised(tool.name, locale);
return (
<div className="group studio-sheet p-3 sm:p-3.5 rounded-2xl bg-paper-hi border border-rule shadow-[0_4px_20px_-4px_rgba(0,0,0,0.03)] hover:border-accent hover:shadow-glow motion-safe:transition-[border-color,box-shadow,transform] duration-300 hover:-translate-y-1 flex flex-col justify-between h-full">
<div className="group studio-sheet p-3 sm:p-3.5 rounded-2xl bg-paper-hi border border-rule shadow-[0_4px_20px_-4px_rgba(0,0,0,0.03)] hover:border-blue-700 hover:shadow-glow motion-safe:transition-[border-color,box-shadow,transform] duration-300 hover:-translate-y-1 flex flex-col justify-between h-full">
{/* Image Dominant Preview Frame */}
<ToolCardImage tool={tool} toolName={toolName} />
@@ -812,18 +812,18 @@ export function ToolGridSection({
<aside
onScroll={() => setHoveredCategory(null)}
onMouseLeave={() => setHoveredCategory(null)}
className="hidden lg:flex flex-col justify-between w-56 xl:w-60 shrink-0 border-r border-rule bg-paper-hi sticky top-[73px] h-[calc(100vh-73px)] overflow-y-auto no-scrollbar p-3.5 xl:p-4 z-20"
className="hidden lg:flex flex-col justify-between w-56 xl:w-60 shrink-0 border-r border-rule bg-paper-hi sticky top-[73px] h-[calc(100vh-73px)] overflow-y-auto no-scrollbar p-3.5 xl:p-4 z-20 font-inter"
>
{/* Top: Header, Search, Categories Nav */}
<div className="space-y-4">
<div className="space-y-3.5">
{/* Categories Header */}
<div className="pb-2.5 border-b border-rule flex items-center justify-between">
<h2 className="text-xs font-bold text-slate-800 font-sans tracking-tight uppercase">
<div className="pb-2 flex items-center justify-between">
<h2 className="text-xs font-bold text-slate-800 font-inter tracking-tight uppercase">
Categories
</h2>
<span className="text-[10px] font-mono text-slate-400 font-semibold">{tools.length} tools</span>
<span className="text-[10px] font-inter text-slate-400 font-semibold">{tools.length} tools</span>
</div>
{/* Instant Search Bar with shortcut hint */}
@@ -835,7 +835,7 @@ export function ToolGridSection({
placeholder="Search tools..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pl-8 pr-7 py-2 rounded-lg text-xs border border-slate-200 bg-white text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/20 shadow-2xs font-sans transition-colors"
className="w-full pl-8 pr-7 py-2 rounded-lg text-xs border border-slate-200 bg-white text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/20 shadow-2xs font-inter transition-colors"
/>
{searchQuery ? (
<button
@@ -855,7 +855,7 @@ export function ToolGridSection({
{/* Categories Navigation */}
<div className="space-y-1.5">
<div className="flex items-center justify-between px-1 font-sans">
<div className="flex items-center justify-between px-1 font-inter">
<span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Workspaces</span>
{(selectedCategory !== 'all' || searchQuery) && (
<button
@@ -864,7 +864,7 @@ export function ToolGridSection({
setSearchQuery('');
setHoveredCategory(null);
}}
className="inline-flex items-center gap-1 text-[11px] font-semibold text-accent hover:underline cursor-pointer lowercase"
className="inline-flex items-center gap-1 text-[11px] font-semibold text-accent hover:underline cursor-pointer lowercase font-inter"
>
<RotateCcw className="w-2.5 h-2.5" />
<span>reset</span>
@@ -891,7 +891,7 @@ export function ToolGridSection({
});
}}
onMouseLeave={() => setHoveredCategory(null)}
className={`w-full flex items-center justify-between px-2.5 py-1.5 rounded-lg text-xs font-sans transition-all duration-150 cursor-pointer ${
className={`w-full flex items-center justify-between px-2.5 py-1.5 rounded-lg text-xs font-inter transition-all duration-150 cursor-pointer ${
selectedCategory === 'all' && !searchQuery
? 'bg-slate-900 text-white shadow-xs font-semibold'
: 'bg-transparent text-slate-700 hover:bg-slate-100 hover:text-slate-950 font-medium'
@@ -912,7 +912,7 @@ export function ToolGridSection({
<span className="truncate">All Studio Tools</span>
</div>
<span
className={`text-[10px] font-mono px-1.5 py-0.5 rounded font-bold shrink-0 ${
className={`text-[10px] font-inter px-1.5 py-0.5 rounded font-bold shrink-0 ${
selectedCategory === 'all' && !searchQuery
? 'bg-white/20 text-white'
: 'bg-slate-100 text-slate-600'
@@ -949,7 +949,7 @@ export function ToolGridSection({
});
}}
onMouseLeave={() => setHoveredCategory(null)}
className={`w-full flex items-center justify-between px-2.5 py-1.5 rounded-lg text-xs font-sans transition-all duration-150 cursor-pointer ${
className={`w-full flex items-center justify-between px-2.5 py-1.5 rounded-lg text-xs font-inter transition-all duration-150 cursor-pointer ${
isSelected
? 'bg-slate-900 text-white shadow-xs font-semibold'
: 'bg-transparent text-slate-700 hover:bg-slate-100 hover:text-slate-950 font-medium'
@@ -968,7 +968,7 @@ export function ToolGridSection({
<span className="truncate">{catName}</span>
</div>
<span
className={`text-[10px] font-mono px-1.5 py-0.5 rounded font-bold shrink-0 ${
className={`text-[10px] font-inter px-1.5 py-0.5 rounded font-bold shrink-0 ${
isSelected
? 'bg-white/20 text-white'
: 'bg-slate-100 text-slate-600'
@@ -988,7 +988,7 @@ export function ToolGridSection({
<div className="pt-3 border-t border-rule space-y-2">
<Link
href="/apps"
className="w-full inline-flex items-center justify-between px-2.5 py-2 rounded-lg text-xs font-sans font-medium text-slate-700 bg-slate-100/80 hover:bg-slate-900 hover:text-white transition-colors duration-150 group shadow-2xs"
className="w-full inline-flex items-center justify-between px-2.5 py-2 rounded-lg text-xs font-inter font-medium text-slate-700 bg-slate-100/80 hover:bg-slate-900 hover:text-white transition-colors duration-150 group shadow-2xs"
>
<div className="flex items-center gap-1.5">
<Smartphone className="w-3.5 h-3.5 text-accent group-hover:text-white" />
@@ -1006,7 +1006,7 @@ export function ToolGridSection({
========================================================================= */}
{hoveredCategory && (
<div
className="fixed z-50 pointer-events-none px-3 py-1.5 rounded-lg bg-slate-900/95 backdrop-blur-md text-white text-xs font-sans font-medium shadow-xl border border-slate-700/80 flex items-center gap-2.5 transition-opacity duration-150 animate-in fade-in-0 zoom-in-95"
className="fixed z-50 pointer-events-none px-3 py-1.5 rounded-lg bg-slate-900/95 backdrop-blur-md text-white text-xs font-inter font-medium shadow-xl border border-slate-700/80 flex items-center gap-2.5 transition-opacity duration-150 animate-in fade-in-0 zoom-in-95"
style={{
top: `${hoveredCategory.top}px`,
left: `${hoveredCategory.left}px`,
@@ -1016,10 +1016,10 @@ export function ToolGridSection({
>
{/* Subtle pointer arrow pointing left toward the sidebar category */}
<div className="absolute -left-1.5 top-1/2 -translate-y-1/2 w-2.5 h-2.5 bg-slate-900 rotate-45 border-l border-b border-slate-700/80" />
<span className="font-semibold tracking-tight text-white whitespace-nowrap">
<span className="font-semibold tracking-tight text-white whitespace-nowrap font-inter">
{hoveredCategory.name}
</span>
<span className="text-[10px] font-mono text-slate-300 bg-slate-800 px-1.5 py-0.5 rounded font-bold border border-slate-700/60 whitespace-nowrap">
<span className="text-[10px] font-inter text-slate-300 bg-slate-800 px-1.5 py-0.5 rounded font-bold border border-slate-700/60 whitespace-nowrap">
{hoveredCategory.count} {hoveredCategory.count === 1 ? 'tool' : 'tools'}
</span>
</div>
@@ -1028,15 +1028,15 @@ export function ToolGridSection({
{/* =========================================================================
RIGHT MAIN STUDIO WORKSPACE (SPACIOUS 4-COLUMN CARDS GALLERY)
========================================================================= */}
<div className="flex-1 min-w-0 px-4 sm:px-6 xl:px-8 py-8 xl:py-10 space-y-10 relative z-10">
<div className="flex-1 min-w-0 px-4 sm:px-6 xl:px-8 py-5 xl:py-6 space-y-6 relative z-10">
{/* ================= MOBILE FILTER HEADER (< lg) ================= */}
<div className="lg:hidden space-y-3 pb-4 border-b border-rule">
<div className="lg:hidden space-y-3 pb-3 font-inter">
<div className="flex items-center justify-between">
<span className="text-sm font-bold text-slate-900 font-sans">
<span className="text-sm font-bold text-slate-900 font-inter">
Categories
</span>
<span className="text-xs font-medium text-slate-500 font-sans">
<span className="text-xs font-medium text-slate-500 font-inter">
{tools.length} tools
</span>
</div>
@@ -1049,7 +1049,7 @@ export function ToolGridSection({
placeholder="Search studio tools..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pl-9 pr-8 py-2.5 rounded-xl text-xs sm:text-sm border border-slate-200 bg-white text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-accent focus:ring-2 focus:ring-accent/20 shadow-2xs font-sans transition-colors"
className="w-full pl-9 pr-8 py-2.5 rounded-xl text-xs sm:text-sm border border-slate-200 bg-white text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-accent focus:ring-2 focus:ring-accent/20 shadow-2xs font-inter transition-colors"
/>
{searchQuery && (
<button
@@ -1067,7 +1067,7 @@ export function ToolGridSection({
<button
type="button"
onClick={() => handleSelectCategory('all')}
className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-sans font-semibold shrink-0 transition-colors ${
className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-inter font-semibold shrink-0 transition-colors ${
selectedCategory === 'all' && !searchQuery
? 'bg-slate-900 text-white shadow-xs'
: 'bg-white text-slate-800 border border-slate-200 hover:text-slate-950'
@@ -1088,7 +1088,7 @@ export function ToolGridSection({
key={group.id}
type="button"
onClick={() => handleSelectCategory(group.id)}
className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-sans font-semibold shrink-0 transition-colors ${
className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-inter font-semibold shrink-0 transition-colors ${
isSelected
? 'bg-slate-900 text-white shadow-xs'
: 'bg-white text-slate-800 border border-slate-200 hover:text-slate-950'
@@ -1108,7 +1108,7 @@ export function ToolGridSection({
</div>
{/* ================= INTEGRATED STUDIO HEADER ================= */}
<div className="space-y-4 border-b border-rule pb-8">
<div className="space-y-2.5 pb-2">
{/* Breadcrumb row */}
<div className="flex items-center gap-2 text-xs font-sans text-slate-500">
<span>Studio Directory</span>
@@ -1237,7 +1237,7 @@ export function ToolGridSection({
</div>
) : (
/* ================= CATEGORIZED TOOLS GALLERY (2 ROWS PER CATEGORY + SEE MORE) ================= */
<div className="space-y-12 sm:space-y-16">
<div className="space-y-6 sm:space-y-8">
{/* Displayed Categories */}
{categorizedTools.map((group) => {
const theme = CATEGORY_THEMES[group.id];
@@ -1254,10 +1254,10 @@ export function ToolGridSection({
<div
key={group.id}
id={`category-${group.id}`}
className="space-y-6 scroll-mt-28"
className="space-y-3.5 scroll-mt-24"
>
{/* Section Category Header */}
<div className="flex flex-col sm:flex-row sm:items-end justify-between gap-3 pb-4 border-b border-rule">
<div className="flex flex-col sm:flex-row sm:items-end justify-between gap-2.5 pb-1.5">
<div className="flex items-center gap-3.5">
<div className="w-11 h-11 rounded-2xl flex items-center justify-center bg-paper-hi shadow-xs border border-rule shrink-0">
{theme?.largeIcon || theme?.icon || <LayoutGrid className="w-6 h-6 text-slate-700" />}
@@ -112,7 +112,7 @@ export function TrendyBentoSection({
const tiles = INITIAL_TILES;
return (
<section id="trendy-effects" className="py-16 sm:py-24 px-4 sm:px-6 md:px-8 lg:px-10 bg-paper border-b border-rule relative overflow-hidden">
<section id="trendy-effects" className="py-8 sm:py-12 px-4 sm:px-6 md:px-8 lg:px-10 bg-paper relative overflow-hidden">
{/* Studio Lighting Ambient Glow */}
<div
className="pointer-events-none absolute bottom-0 right-1/4 w-[500px] h-[350px] [background:radial-gradient(circle_at_center,color-mix(in_oklab,var(--color-accent)_10%,transparent)_0%,transparent_70%)]"
@@ -123,9 +123,9 @@ export function TrendyBentoSection({
aria-hidden="true"
/>
<div className="max-w-container mx-auto space-y-10 relative z-10">
{/* Header with Kinetic Text Animation */}
<div className="max-w-2xl space-y-2 border-b border-rule pb-5">
<div className="max-w-container mx-auto space-y-6 relative z-10">
{/* Header without thin separator */}
<div className="max-w-2xl space-y-1.5 pb-1">
<h2 className="text-3xl sm:text-4xl font-display font-bold text-ink tracking-tight">
<KineticText>{title}</KineticText>
</h2>
@@ -143,7 +143,7 @@ export function TrendyBentoSection({
<Link
key={tile.id}
href={tile.href}
className="studio-sheet p-4 rounded-3xl bg-paper-hi border border-rule shadow-sheet hover:border-accent hover:shadow-glow flex flex-col justify-between group motion-safe:transition-[border-color,box-shadow,transform] duration-200"
className="studio-sheet p-4 rounded-3xl bg-paper-hi border border-rule shadow-sheet hover:border-blue-700 hover:shadow-glow flex flex-col justify-between group motion-safe:transition-[border-color,box-shadow,transform] duration-200"
>
{/* Image Specimen */}
<div className="relative aspect-[4/3] rounded-2xl overflow-hidden bg-paper-2 border border-rule mb-3.5">
+28
View File
@@ -13,6 +13,7 @@ import {
} from 'lucide-react';
import { ToolItem, AppItem, VariantSpec, resolveLocalised } from '@/types';
import { CardBeforeAfterSlider } from '../ui/CardBeforeAfterSlider';
import { TurnstileWidget, TurnstileWidgetRef } from '@/components/turnstile/TurnstileWidget';
interface TryItWidgetProps {
tool: ToolItem;
@@ -43,6 +44,8 @@ export function TryItWidget({
const [status, setStatus] = useState<'idle' | 'selected' | 'processing' | 'success' | 'limit' | 'error' | 'unavailable'>('idle');
const [errorMessage, setErrorMessage] = useState<string>('');
const [remainingTries, setRemainingTries] = useState<number>(tool.tryIt?.limits?.perDay || 5);
const [turnstileToken, setTurnstileToken] = useState<string>('');
const turnstileRef = useRef<TurnstileWidgetRef>(null);
const [isDragOver, setIsDragOver] = useState<boolean>(false);
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -108,6 +111,12 @@ export function TryItWidget({
const runTryIt = async () => {
if (!selectedFile && !previewUrl) return;
if (!turnstileToken) {
setStatus('error');
setErrorMessage('Please complete the Cloudflare Turnstile security check before processing.');
return;
}
setStatus('processing');
setErrorMessage('');
@@ -125,6 +134,8 @@ export function TryItWidget({
formData.append('variant', activeVariant);
}
formData.append('cf-turnstile-response', turnstileToken);
const response = await fetch(`/api/try/${tool.id}`, {
method: 'POST',
body: formData,
@@ -156,6 +167,10 @@ export function TryItWidget({
} catch {
setStatus('error');
setErrorMessage('Network error connecting to inference API.');
} finally {
// Cloudflare Turnstile tokens are single-use per siteverify; reset for subsequent operations
setTurnstileToken('');
turnstileRef.current?.reset();
}
};
@@ -316,6 +331,19 @@ export function TryItWidget({
</div>
)}
<div className="py-2 flex justify-center">
<TurnstileWidget
ref={turnstileRef}
onVerify={(tok) => {
setTurnstileToken(tok);
setErrorMessage('');
}}
onExpire={() => setTurnstileToken('')}
theme="auto"
size="flexible"
/>
</div>
<button
type="button"
onClick={runTryIt}
@@ -87,7 +87,7 @@ function ToolCard({ tool, app, locale }: { tool: ToolItem; app?: AppItem; locale
const image = example?.after || example?.before || fallbackImage;
return (
<article className="group overflow-hidden rounded-3xl border border-slate-900/[0.08] bg-white shadow-cream-sm transition-[box-shadow,border-color,transform] duration-300 hover:-translate-y-0.5 hover:border-blue-300 hover:shadow-cream-md">
<article className="group overflow-hidden rounded-3xl border border-slate-900/[0.08] bg-white shadow-cream-sm transition-[box-shadow,border-color,transform] duration-300 hover:-translate-y-0.5 hover:border-blue-700 hover:shadow-cream-md">
<div className="relative aspect-[16/10] overflow-hidden bg-slate-100">
{hasComparison ? (
<CardBeforeAfterSlider
@@ -52,7 +52,7 @@ export function WorkflowVisualizerSection() {
return (
<div
key={idx}
className="relative bg-white rounded-3xl p-8 border border-slate-900/[0.08] hover:border-blue-400 shadow-cream-sm hover:shadow-cream-md transition-all duration-300 flex flex-col justify-between group"
className="relative bg-white rounded-3xl p-8 border border-slate-900/[0.08] hover:border-blue-700 shadow-cream-sm hover:shadow-cream-md transition-all duration-300 flex flex-col justify-between group"
>
<div>
<div className="flex items-center justify-between mb-6">
+42 -10
View File
@@ -36,6 +36,7 @@ import { ImageCropper } from './ImageCropper';
import { PostResultAppHandoff } from './PostResultAppHandoff';
import { AnimatedShinyText } from '@/components/magicui/animated-shiny-text';
import { BorderBeam } from '@/components/magicui/border-beam';
import { TurnstileWidget, TurnstileWidgetRef } from '@/components/turnstile/TurnstileWidget';
interface DynamicToolWorkspaceProps {
tool: ToolItem;
@@ -110,6 +111,8 @@ export function DynamicToolWorkspace({
const [errorMessage, setErrorMessage] = useState<string>('');
const [remainingTries, setRemainingTries] = useState<number>(tool.tryIt?.limits?.perDay || 5);
const [hasDownloadedResult, setHasDownloadedResult] = useState<boolean>(false);
const [turnstileToken, setTurnstileToken] = useState<string>('');
const turnstileRef = useRef<TurnstileWidgetRef>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const secondaryFileInputRef = useRef<HTMLInputElement>(null);
@@ -206,6 +209,14 @@ export function DynamicToolWorkspace({
// Execute Request dynamically according to pageType
const handleExecute = async () => {
if (status === 'processing') return;
if (!turnstileToken) {
setStatus('error');
setErrorMessage('Please complete the Cloudflare Turnstile security check before processing.');
return;
}
if (remainingTries <= 0) {
setStatus('limit');
setErrorMessage('You have reached the free operations limit for today. Try again tomorrow or get the mobile app.');
@@ -326,6 +337,11 @@ export function DynamicToolWorkspace({
}
}
// Attach Cloudflare Turnstile token for human verification
if (turnstileToken) {
formData.append('cf-turnstile-response', turnstileToken);
}
const res = await fetch(`/api/try/${tool.id}`, {
method: 'POST',
body: formData,
@@ -359,6 +375,10 @@ export function DynamicToolWorkspace({
} catch {
setStatus('error');
setErrorMessage('Network error during model inference.');
} finally {
// Cloudflare Turnstile tokens are single-use per siteverify; reset for subsequent operations
setTurnstileToken('');
turnstileRef.current?.reset();
}
};
@@ -516,7 +536,7 @@ export function DynamicToolWorkspace({
<button
type="button"
onClick={handleDownloadResult}
className="w-full sm:w-auto inline-flex items-center justify-center gap-3 px-8 sm:px-12 py-4 rounded-2xl sm:rounded-full bg-ink hover:bg-slate-900 text-paper-hi font-display font-bold text-sm sm:text-base shadow-xl hover:scale-[1.02] active:scale-98 transition-all cursor-pointer order-1 sm:order-2"
className="w-full sm:w-auto inline-flex items-center justify-center gap-3 px-8 sm:px-12 py-4 rounded-2xl sm:rounded-full bg-ink hover:bg-slate-900 text-paper-hi font-sans font-bold text-sm sm:text-base shadow-xl hover:scale-[1.02] active:scale-98 transition-all cursor-pointer order-1 sm:order-2"
>
<Download className="w-5 h-5 text-accent" />
<span>Download Result (HD PNG)</span>
@@ -793,12 +813,24 @@ export function DynamicToolWorkspace({
</div>
{/* Right: Massive High-Visibility Main Process Button with Dynamic Server-backed Quota Icon */}
<div className="w-full sm:w-auto order-1 sm:order-2">
<div className="w-full sm:w-auto order-1 sm:order-2 flex flex-col items-center sm:items-end gap-3">
{/* Cloudflare Turnstile Human Verification Widget */}
<TurnstileWidget
ref={turnstileRef}
onVerify={(tok) => {
setTurnstileToken(tok);
setErrorMessage('');
}}
onExpire={() => setTurnstileToken('')}
theme="auto"
size="flexible"
/>
<button
type="button"
onClick={handleExecute}
disabled={status === 'processing' || remainingTries <= 0}
className="w-full sm:w-auto inline-flex items-center justify-center gap-3 px-8 sm:px-10 py-4 rounded-2xl sm:rounded-full bg-accent hover:bg-accent-hi text-white font-display font-extrabold text-sm sm:text-base shadow-xl shadow-accent/25 hover:shadow-accent/40 hover:scale-[1.02] active:scale-98 transition-all cursor-pointer disabled:opacity-50 disabled:hover:scale-100"
className="w-full sm:w-auto inline-flex items-center justify-center gap-3 px-8 sm:px-10 py-4 rounded-2xl sm:rounded-full bg-accent hover:bg-accent-hi text-white font-sans font-extrabold text-sm sm:text-base shadow-xl shadow-accent/25 hover:shadow-accent/40 hover:scale-[1.02] active:scale-98 transition-all cursor-pointer disabled:opacity-50 disabled:hover:scale-100"
>
{status === 'processing' ? (
<>
@@ -850,7 +882,7 @@ export function DynamicToolWorkspace({
<div className="min-h-screen bg-paper">
{/* ================= HERO SECTION ================= */}
<section className="relative pt-6 sm:pt-10 pb-12 sm:pb-16 bg-paper border-b border-rule overflow-hidden">
<section className="relative pt-6 sm:pt-8 pb-8 sm:pb-10 bg-paper overflow-hidden">
{/* Ambient Radial Spotlight */}
<div
className="pointer-events-none absolute top-0 left-1/2 -translate-x-1/2 w-[900px] h-[400px] [background:radial-gradient(ellipse_at_top,color-mix(in_oklab,var(--color-accent)_12%,transparent)_0%,transparent_70%)]"
@@ -885,18 +917,18 @@ export function DynamicToolWorkspace({
<div id="studio-upload-box" className="lg:col-span-6 bg-paper-hi border border-rule rounded-3xl p-6 sm:p-8 shadow-sheet relative overflow-hidden">
<BorderBeam size={120} duration={10} borderWidth={1.5} colorFrom="var(--color-accent)" colorTo="var(--color-accent-hi)" />
<div className="border-b border-rule pb-3.5 mb-6 flex items-center justify-between">
<div className="pb-2.5 mb-4 flex items-center justify-between">
<span className="text-sm font-bold font-sans text-slate-900">
{pageType === 'text-to-image' ? 'Generate AI Image' : 'Select Photo to Edit'}
</span>
</div>
{/* Dynamic Upload Input by Type */}
<div className="space-y-6">
<div className="space-y-4">
{/* Style Thumbnail Selector on Landing Card (Before-Upload / Both) */}
{tool.thumbnails && tool.thumbnails.length > 0 && tool.thumbnailPlacement !== 'after-upload' && (
<div className="space-y-3 pb-4 border-b border-rule/60">
<div className="space-y-2.5 pb-2">
<div className="flex items-center justify-between text-xs sm:text-sm font-sans">
<span className="font-semibold text-slate-900">1. Select Effect Style</span>
{selectedThumbnail && (
@@ -1116,7 +1148,7 @@ export function DynamicToolWorkspace({
window.scrollTo({ top: 0, behavior: 'smooth' });
}
}}
className="w-full py-4 rounded-2xl bg-accent hover:bg-accent-hi text-white font-display font-bold text-sm shadow-md hover:shadow-lg transition-all cursor-pointer flex items-center justify-center gap-2.5"
className="w-full py-4 rounded-2xl bg-accent hover:bg-accent-hi text-white font-sans font-bold text-sm shadow-md hover:shadow-lg transition-all cursor-pointer flex items-center justify-center gap-2.5"
>
<Sparkles className="w-4 h-4 text-amber-300" />
<span>
@@ -1171,7 +1203,7 @@ export function DynamicToolWorkspace({
}
}}
disabled={!promptText.trim()}
className="w-full py-4 rounded-2xl bg-accent hover:bg-accent-hi disabled:opacity-50 text-white font-display font-bold text-sm shadow-md hover:shadow-lg transition-all cursor-pointer flex items-center justify-center gap-2.5"
className="w-full py-4 rounded-2xl bg-accent hover:bg-accent-hi disabled:opacity-50 text-white font-sans font-bold text-sm shadow-md hover:shadow-lg transition-all cursor-pointer flex items-center justify-center gap-2.5"
>
<Sparkles className="w-4 h-4 text-amber-300" />
<span>Open Creation Studio</span>
@@ -1258,7 +1290,7 @@ export function DynamicToolWorkspace({
key={idx}
className="studio-sheet p-5 rounded-2xl bg-paper-hi border border-rule shadow-xs space-y-2.5"
>
<div className="w-9 h-9 rounded-xl bg-slate-900 text-white flex items-center justify-center font-display font-bold text-xs">
<div className="w-9 h-9 rounded-xl bg-slate-900 text-white flex items-center justify-center font-sans font-bold text-xs">
0{idx + 1}
</div>
<h3 className="text-sm sm:text-base font-display font-bold text-ink">
@@ -0,0 +1,179 @@
'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 ||
process.env.NEXT_PUBLIC_CLOUDFLARE_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>
);
}
);
+2 -2
View File
@@ -68,10 +68,10 @@ export function BrandLogo({
{showWordmark && (
<div className="flex flex-col text-left">
<div className="flex items-baseline gap-1.5 leading-none">
<span className={`font-display font-bold text-ink ${iconDimensions.title}`}>
<span className={`font-inter font-bold text-ink ${iconDimensions.title}`}>
CRE
</span>
<span className={`font-display font-normal text-ink-2 ${iconDimensions.title}`}>
<span className={`font-inter font-normal text-ink-2 ${iconDimensions.title}`}>
Innovations
</span>
</div>
+4 -10
View File
@@ -20,7 +20,6 @@ import {
import { SiteConfig, CategoryItem, resolveLocalised } from '@/types';
import { BrandLogo } from './BrandLogo';
import { RainbowButton } from '@/components/magicui/rainbow-button';
import { UserMenu } from '@/components/auth/UserMenu';
interface NavbarProps {
config: SiteConfig;
@@ -101,10 +100,10 @@ export function Navbar({ config, currentLocale, categories = [], totalToolsCount
return (
<header
className={`sticky top-0 left-0 right-0 w-full z-40 motion-safe:transition-[background-color,border-color,box-shadow] duration-200 bg-paper border-b border-rule shadow-xs ${
className={`sticky top-0 left-0 right-0 w-full z-40 motion-safe:transition-[background-color,border-color,box-shadow] duration-200 bg-paper ${
scrolled
? 'md:bg-paper/95 md:backdrop-blur-xl shadow-[0_2px_16px_-4px_color-mix(in_oklab,var(--color-ink)_6%,transparent)]'
: 'md:bg-paper'
? 'border-b border-rule shadow-[0_2px_16px_-4px_color-mix(in_oklab,var(--color-ink)_6%,transparent)] md:bg-paper/95 md:backdrop-blur-xl'
: 'border-b border-transparent shadow-none md:bg-paper'
}`}
>
<div className="max-w-container mx-auto px-4 sm:px-6 lg:px-8 h-18 py-3 flex items-center justify-between">
@@ -148,9 +147,8 @@ export function Navbar({ config, currentLocale, categories = [], totalToolsCount
})}
</nav>
{/* Right CTA Actions from JSON + User Authentication */}
{/* Right CTA Actions from JSON */}
<div className="hidden md:flex items-center gap-3 relative z-20 flex-shrink-0">
<UserMenu />
<RainbowButton href={ctaHref}>
<span>{ctaLabel}</span>
<ArrowRight className="w-3.5 h-3.5 ml-1 inline" aria-hidden="true" />
@@ -210,10 +208,6 @@ export function Navbar({ config, currentLocale, categories = [], totalToolsCount
</nav>
<div className="pt-6 border-t border-rule space-y-3">
<div className="flex items-center justify-between pb-3 border-b border-rule/70">
<span className="text-xs font-semibold text-slate-700">Studio Account</span>
<UserMenu />
</div>
<RainbowButton
href={ctaHref}
onClick={() => setMobileMenuOpen(false)}
+6
View File
@@ -92,6 +92,12 @@ export async function executeBackendTryIt(
const backendBase = new URL(envBackendUrl);
parsed.protocol = backendBase.protocol;
parsed.host = backendBase.host;
for (const pfx of ['/apis/mlm', '/apis/flxf', '/apis/flxk', '/apis/lxds', '/apis/cmf']) {
if (parsed.pathname.startsWith(pfx)) {
parsed.pathname = parsed.pathname.substring(pfx.length);
break;
}
}
targetUrl = parsed.toString();
} catch {
// Keep original targetUrl
+2 -2
View File
@@ -58,7 +58,7 @@ export function getAllTools(): ToolItem[] {
const files = fs.readdirSync(toolsDir).filter((f) => f.endsWith('.json'));
for (const file of files) {
const tool = readJsonFile<ToolItem>(path.join(toolsDir, file));
if (tool && tool.status === 'published') {
if (tool && tool.status !== 'archived') {
toolsCache.set(tool.slug, tool);
}
}
@@ -72,7 +72,7 @@ export function getAllTools(): ToolItem[] {
const configPath = path.join(mgmtToolsDir, slug, 'tool.config.json');
if (fs.existsSync(configPath)) {
const mgmtTool = readJsonFile<any>(configPath);
if (mgmtTool && mgmtTool.status === 'published') {
if (mgmtTool && mgmtTool.status !== 'archived') {
// Normalize media paths so before/after point to live management media
if (mgmtTool.media?.before && mgmtTool.content?.examples?.[0]) {
mgmtTool.content.examples[0].before = mgmtTool.media.before;
-202
View File
@@ -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;
}
-125
View File
@@ -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;
}
}
-79
View File
@@ -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;
}
-80
View File
@@ -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;
}
+134
View File
@@ -0,0 +1,134 @@
/**
* Cloudflare Turnstile Server-side Verification Utility
*
* Validates cf-turnstile-response tokens against Cloudflare's verification API:
* https://challenges.cloudflare.com/turnstile/v0/siteverify
*
* Enforces strict bot and abuse protection so that no automated client can send
* requests to the actual backend server on its own without passing Turnstile verification.
*/
export interface TurnstileVerificationResult {
success: boolean;
errorCodes?: string[];
challengeTs?: string;
hostname?: string;
message?: string;
}
const CLOUDFLARE_VERIFY_ENDPOINT = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
// Cloudflare official testing keys:
// Test Site Key (Always Passes): 1x00000000000000000000AA
// Test Secret Key (Always Passes): 1x0000000000000000000000000000000AA
// Test Site Key (Always Blocks): 2x00000000000000000000AB
// Test Secret Key (Always Blocks): 2x0000000000000000000000000000000AA
export const CLOUDFLARE_TEST_SECRET_ALWAYS_PASS = '1x0000000000000000000000000000000AA';
export const CLOUDFLARE_TEST_SECRET_ALWAYS_FAIL = '2x0000000000000000000000000000000AA';
/**
* Verifies a Turnstile response token with Cloudflare's verification API.
*
* Verification is strictly enforced:
* - Empty or missing tokens are immediately rejected with success: false.
* - Secret key is resolved from CLOUDFLARE_TURNSTILE_SECRET_KEY / TURNSTILE_SECRET_KEY.
* - Test keys allow offline/dev testing while maintaining strict token presence requirements.
*/
export async function verifyTurnstileToken(
token: string | null | undefined,
remoteIp?: string
): Promise<TurnstileVerificationResult> {
// 1. Mandatory token check: Never allow empty/missing tokens
if (!token || typeof token !== 'string' || token.trim() === '') {
return {
success: false,
message: 'Cloudflare Turnstile token is required. Automated requests directly to the backend are strictly blocked.',
};
}
const cleanToken = token.trim();
// 2. Secret Key resolution
const secretKey =
process.env.CLOUDFLARE_TURNSTILE_SECRET_KEY ||
process.env.TURNSTILE_SECRET_KEY ||
CLOUDFLARE_TEST_SECRET_ALWAYS_PASS;
// 3. Official test key block scenario
if (secretKey === CLOUDFLARE_TEST_SECRET_ALWAYS_FAIL) {
return {
success: false,
errorCodes: ['invalid-input-response'],
message: 'Cloudflare Turnstile challenge failed (testing key configured to block).',
};
}
// Support test key offline fallback for local dev / testing without network dependency
if (
secretKey === CLOUDFLARE_TEST_SECRET_ALWAYS_PASS &&
(cleanToken === '1x00000000000000000000AA' || cleanToken === 'XXXX.DUMMY.TOKEN.XXXX')
) {
return {
success: true,
challengeTs: new Date().toISOString(),
hostname: 'localhost',
};
}
// 4. Remote Cloudflare Siteverify API verification
try {
const formData = new URLSearchParams();
formData.append('secret', secretKey);
formData.append('response', cleanToken);
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}`);
// Fallback for Always-Pass testing key if network to Cloudflare is unreachable
if (secretKey === CLOUDFLARE_TEST_SECRET_ALWAYS_PASS) {
return {
success: true,
message: 'Cloudflare test key verification passed (offline fallback).',
};
}
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);
// Graceful offline fallback for testing key only
if (secretKey === CLOUDFLARE_TEST_SECRET_ALWAYS_PASS) {
return {
success: true,
message: 'Cloudflare test key verification passed (offline network error).',
};
}
return {
success: false,
message: error?.message || 'Error communicating with Turnstile verification service.',
};
}
}
+37
View File
@@ -0,0 +1,37 @@
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const response = NextResponse.next();
const pathname = request.nextUrl.pathname;
// Don't override hashed Next.js static asset chunks (they are immutable by hash)
const isHashedStatic =
pathname.startsWith('/_next/static') ||
pathname.startsWith('/_next/image');
if (!isHashedStatic) {
// Strictly disable caching for all HTML pages, API responses, and routes
response.headers.set(
'Cache-Control',
'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0, s-maxage=0'
);
response.headers.set('Pragma', 'no-cache');
response.headers.set('Expires', '0');
response.headers.set('Surrogate-Control', 'no-store');
response.headers.set('CDN-Cache-Control', 'no-store');
response.headers.set('Cloudflare-CDN-Cache-Control', 'no-store');
response.headers.set('X-Deploy-Version', '20261117_sfpro');
}
return response;
}
export const config = {
matcher: [
/*
* Match all request paths except static files with extensions (.png, .jpg, .svg, etc.)
*/
'/((?!_next/static|_next/image|brand/|favicon.ico|manifest.webmanifest).*)',
],
};
+7 -4
View File
@@ -12,10 +12,13 @@ const config: Config = {
theme: {
extend: {
fontFamily: {
display: ["var(--font-display)", "Hedvig Letters Serif", "Georgia", "serif"],
body: ["var(--font-body)", "Geist", "ui-sans-serif", "system-ui", "sans-serif"],
sans: ["var(--font-body)", "Geist", "ui-sans-serif", "system-ui", "sans-serif"],
mono: ["var(--font-mono)", "ui-monospace", "monospace"],
display: ["var(--font-sf)", "SF Pro Display", "SF Pro Text", "SF Pro", "-apple-system", "BlinkMacSystemFont", "system-ui", "sans-serif"],
body: ["var(--font-sf)", "SF Pro Display", "SF Pro Text", "SF Pro", "-apple-system", "BlinkMacSystemFont", "system-ui", "sans-serif"],
sans: ["var(--font-sf)", "SF Pro Display", "SF Pro Text", "SF Pro", "-apple-system", "BlinkMacSystemFont", "system-ui", "sans-serif"],
sf: ["var(--font-sf)", "SF Pro Display", "SF Pro Text", "SF Pro", "-apple-system", "BlinkMacSystemFont", "system-ui", "sans-serif"],
inter: ["var(--font-sf)", "SF Pro Display", "SF Pro Text", "SF Pro", "-apple-system", "BlinkMacSystemFont", "sans-serif"],
mono: ["var(--font-sf)", "SF Pro Display", "SF Pro Text", "SF Pro", "-apple-system", "BlinkMacSystemFont", "ui-monospace", "monospace"],
poppins: ["var(--font-sf)", "SF Pro Display", "SF Pro Text", "SF Pro", "-apple-system", "BlinkMacSystemFont", "sans-serif"],
},
colors: {
paper: "var(--color-paper)",
-84
View File
@@ -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();
});
});
+69
View File
@@ -0,0 +1,69 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
verifyTurnstileToken,
CLOUDFLARE_TEST_SECRET_ALWAYS_PASS,
CLOUDFLARE_TEST_SECRET_ALWAYS_FAIL,
} from '../src/lib/turnstile';
describe('Cloudflare Turnstile Security Verification', () => {
const originalEnv = process.env;
beforeEach(() => {
vi.resetModules();
process.env = { ...originalEnv };
});
afterEach(() => {
process.env = originalEnv;
});
it('strictly rejects null, undefined, or empty tokens', async () => {
process.env.CLOUDFLARE_TURNSTILE_SECRET_KEY = CLOUDFLARE_TEST_SECRET_ALWAYS_PASS;
const resNull = await verifyTurnstileToken(null);
expect(resNull.success).toBe(false);
expect(resNull.message).toContain('Turnstile token is required');
const resUndefined = await verifyTurnstileToken(undefined);
expect(resUndefined.success).toBe(false);
const resEmpty = await verifyTurnstileToken(' ');
expect(resEmpty.success).toBe(false);
});
it('rejects verification when using Always-Fail secret key', async () => {
process.env.CLOUDFLARE_TURNSTILE_SECRET_KEY = CLOUDFLARE_TEST_SECRET_ALWAYS_FAIL;
const res = await verifyTurnstileToken('XXXX.DUMMY.TOKEN.XXXX');
expect(res.success).toBe(false);
expect(res.message).toContain('challenge failed');
});
it('verifies successfully with official Cloudflare test token and Always-Pass key', async () => {
process.env.CLOUDFLARE_TURNSTILE_SECRET_KEY = CLOUDFLARE_TEST_SECRET_ALWAYS_PASS;
const res = await verifyTurnstileToken('XXXX.DUMMY.TOKEN.XXXX');
expect(res.success).toBe(true);
expect(res.hostname).toBeDefined();
});
it('verifies successfully with site key test token 1x00000000000000000000AA', async () => {
process.env.CLOUDFLARE_TURNSTILE_SECRET_KEY = CLOUDFLARE_TEST_SECRET_ALWAYS_PASS;
const res = await verifyTurnstileToken('1x00000000000000000000AA');
expect(res.success).toBe(true);
});
it('falls back to Always-Pass testing key when env variable is omitted', async () => {
delete process.env.CLOUDFLARE_TURNSTILE_SECRET_KEY;
delete process.env.TURNSTILE_SECRET_KEY;
// Even without env key, empty token MUST STILL fail
const emptyRes = await verifyTurnstileToken('');
expect(emptyRes.success).toBe(false);
// Valid test token passes
const validRes = await verifyTurnstileToken('XXXX.DUMMY.TOKEN.XXXX');
expect(validRes.success).toBe(true);
});
});