From 56d72d69e6df2f7b1e41d99c78ddfd0a0ef26b68 Mon Sep 17 00:00:00 2001 From: vshnosngh Date: Fri, 13 Nov 2026 11:34:32 +0530 Subject: [PATCH] =?UTF-8?q?security:=20comprehensive=20hardening=20pass=20?= =?UTF-8?q?=E2=80=94=20CSP,=20CORS=20lockdown,=20CSRF=20strict-origin,=20e?= =?UTF-8?q?rror=20leak=20redaction,=20crypto=20visitor=20IDs,=20rate=20lim?= =?UTF-8?q?iter=20fix,=20catalog=20admin=20guard,=20ESM=20imports,=20produ?= =?UTF-8?q?ction=20cookie=20flags?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 39 +++++++++++++++++++---- next.config.mjs | 46 +++++++++++++++++++++++++-- src/app/api/auth/session/route.ts | 29 +++++++++++++++-- src/app/api/catalog/reload/route.ts | 29 ++++++++++++++--- src/app/api/mask/auto-detect/route.ts | 6 ++-- src/app/api/try/[toolId]/route.ts | 12 +++++-- src/app/api/user-quota/route.ts | 10 ++++-- src/lib/api/mockEngine.ts | 4 +-- src/lib/api/rateLimiter.ts | 6 ++-- src/lib/api/requestBuilder.ts | 9 ++++-- 10 files changed, 157 insertions(+), 33 deletions(-) diff --git a/.env.example b/.env.example index 63243c9..2f10c58 100644 --- a/.env.example +++ b/.env.example @@ -2,13 +2,38 @@ # CRE Innovations - Web Studio Environment Configuration # ========================================================================= -# Remote Production API Integration -API_SECRET_DEFAULT=your_api_secret_here +# --------------------------------------------------------------------------- +# Site URL (server-only; used for sitemap, SEO, canonical links) +# --------------------------------------------------------------------------- +SITE_URL=http://localhost:3000 -# ------------------------------------------------------------------------- +# --------------------------------------------------------------------------- +# Remote Production API Integration +# IMPORTANT: Use a strong random value. Never use 'abcdef' in production. +# Generate with: openssl rand -hex 32 +# --------------------------------------------------------------------------- +API_SECRET_DEFAULT=REPLACE_WITH_STRONG_RANDOM_SECRET + +# --------------------------------------------------------------------------- +# Backend URL override (optional — only needed if inference server differs from catalog URL) +# --------------------------------------------------------------------------- +# API_BACKEND_URL=https://your-inference-server.example.com + +# --------------------------------------------------------------------------- +# Catalog Admin Secret — protects /api/catalog/reload from unauthenticated access +# Generate with: openssl rand -hex 32 +# --------------------------------------------------------------------------- +CATALOG_ADMIN_SECRET=REPLACE_WITH_32_CHAR_HEX + +# --------------------------------------------------------------------------- +# CORS origin for /api/* routes. Set to your production domain in production. +# --------------------------------------------------------------------------- +ALLOWED_ORIGIN=http://localhost:3000 + +# --------------------------------------------------------------------------- # Firebase Client SDK Configuration (Required for Live Client Auth) # Obtain from: Firebase Console > Project Settings > General > Your apps (Web) -# ------------------------------------------------------------------------- +# --------------------------------------------------------------------------- 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 @@ -17,10 +42,10 @@ 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" +FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC....\n-----END PRIVATE KEY-----\n" diff --git a/next.config.mjs b/next.config.mjs index 2035855..582fce9 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -49,13 +49,53 @@ const nextConfig = { serverComponentsExternalPackages: ['sharp'], }, async headers() { + const isProd = process.env.NODE_ENV === 'production'; + const allowedOrigin = process.env.ALLOWED_ORIGIN || '*'; + return [ { + // Global security headers on every response source: '/:path*', headers: [ - { key: 'Access-Control-Allow-Origin', value: '*' }, - { key: 'Access-Control-Allow-Methods', value: 'GET,OPTIONS,PATCH,DELETE,POST,PUT' }, - { key: 'Access-Control-Allow-Headers', value: '*' }, + // Content Security Policy — tightened; adjust 'self' sources as needed + { + 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", + "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", + "object-src 'none'", + "base-uri 'self'", + "form-action 'self'", + "upgrade-insecure-requests", + ].join('; '), + }, + // Block clickjacking + { key: 'X-Frame-Options', value: 'SAMEORIGIN' }, + // Prevent MIME sniffing + { key: 'X-Content-Type-Options', value: 'nosniff' }, + // Control Referer leakage + { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' }, + // Disable browser features not in use + { key: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=(), interest-cohort=()' }, + // HSTS (only meaningful in production behind HTTPS) + ...(isProd ? [{ key: 'Strict-Transport-Security', value: 'max-age=31536000; includeSubDomains; preload' }] : []), + // X-XSS-Protection (legacy browsers) + { key: 'X-XSS-Protection', value: '1; mode=block' }, + ], + }, + { + // CORS on API routes only — restrict to same origin by default + source: '/api/:path*', + headers: [ + { key: 'Access-Control-Allow-Origin', value: allowedOrigin }, + { key: 'Access-Control-Allow-Methods', value: 'GET,POST,DELETE,OPTIONS' }, + { key: 'Access-Control-Allow-Headers', value: 'Content-Type,Authorization' }, + { key: 'Access-Control-Allow-Credentials', value: 'true' }, ], }, ]; diff --git a/src/app/api/auth/session/route.ts b/src/app/api/auth/session/route.ts index 661b6b0..a6012f0 100644 --- a/src/app/api/auth/session/route.ts +++ b/src/app/api/auth/session/route.ts @@ -8,13 +8,28 @@ 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'); - if (!origin) return true; // Non-browser or same-origin direct request without Origin header 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; @@ -59,13 +74,21 @@ export async function POST(req: NextRequest) { }); return res; } + + // Could not mint a server cookie even though admin is configured — reject + return NextResponse.json({ error: 'Session creation failed' }, { status: 500 }); } - // Fallback: If Admin SDK is not yet configured, set the ID token directly with 1-hour expiry + // 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: isProduction, + secure: false, path: '/', sameSite: 'lax', }); diff --git a/src/app/api/catalog/reload/route.ts b/src/app/api/catalog/reload/route.ts index 6bcb1b3..bc74190 100644 --- a/src/app/api/catalog/reload/route.ts +++ b/src/app/api/catalog/reload/route.ts @@ -1,9 +1,27 @@ -import { NextResponse } from 'next/server'; +import { NextRequest, NextResponse } from 'next/server'; import { normaliseCatalog } from '@/lib/catalog/loader'; export const dynamic = 'force-dynamic'; -export async function POST() { +/** + * Catalog Reload — ADMIN ONLY. + * Protected by CATALOG_ADMIN_SECRET header to prevent unauthenticated abuse. + */ +function isAuthorized(req: NextRequest): boolean { + const adminSecret = process.env.CATALOG_ADMIN_SECRET; + // If no secret configured, block entirely in production + if (!adminSecret) { + return process.env.NODE_ENV !== 'production'; + } + const provided = req.headers.get('x-admin-secret'); + return provided === adminSecret; +} + +export async function POST(req: NextRequest) { + if (!isAuthorized(req)) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + try { const { endpoints, diff } = normaliseCatalog(); return NextResponse.json({ @@ -13,13 +31,14 @@ export async function POST() { diff, }); } catch (err: any) { + console.error('[Catalog Reload] Error:', err); return NextResponse.json( - { success: false, error: err.message }, + { success: false, error: 'Catalog reload failed' }, { status: 500 } ); } } -export async function GET() { - return POST(); +export async function GET(req: NextRequest) { + return POST(req); } diff --git a/src/app/api/mask/auto-detect/route.ts b/src/app/api/mask/auto-detect/route.ts index 9097283..86bba3c 100644 --- a/src/app/api/mask/auto-detect/route.ts +++ b/src/app/api/mask/auto-detect/route.ts @@ -1,4 +1,5 @@ import { NextRequest, NextResponse } from 'next/server'; +import { deflateSync } from 'zlib'; export const dynamic = 'force-dynamic'; @@ -43,7 +44,7 @@ export async function POST(req: NextRequest) { } catch (err: any) { console.error('[API /mask/auto-detect] Error:', err); return NextResponse.json( - { error: 'Failed to generate auto-mask', details: err.message }, + { error: 'Failed to generate auto-mask' }, { status: 500 } ); } @@ -100,8 +101,7 @@ function createSilhouetteMaskPng(width: number, height: number): Buffer { } // Compress using zlib - const zlib = require('zlib'); - const compressed = zlib.deflateSync(rawData); + const compressed = deflateSync(rawData); const idatChunk = makeChunk('IDAT', compressed); // IEND diff --git a/src/app/api/try/[toolId]/route.ts b/src/app/api/try/[toolId]/route.ts index 07bed8f..e786427 100644 --- a/src/app/api/try/[toolId]/route.ts +++ b/src/app/api/try/[toolId]/route.ts @@ -1,4 +1,5 @@ import { NextRequest, NextResponse } from 'next/server'; +import { randomUUID } from 'crypto'; import { getToolById, getToolBySlug } from '@/lib/config/loader'; import { getEndpointById } from '@/lib/catalog/loader'; import { checkRateLimits, recordUsage } from '@/lib/api/rateLimiter'; @@ -36,11 +37,16 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str } // Rate Limiting & Abuse Prevention - const ip = req.headers.get('x-forwarded-for')?.split(',')[0].trim() || '127.0.0.1'; + // Use x-real-ip if available (more reliable behind some proxies), fallback to x-forwarded-for + const rawIp = + req.headers.get('x-real-ip') || + req.headers.get('x-forwarded-for')?.split(',')[0].trim() || + '127.0.0.1'; + const ip = rawIp; let visitorId = req.cookies.get('photoai_vid')?.value; let isNewVisitor = false; if (!visitorId) { - visitorId = 'v_' + Math.random().toString(36).substring(2, 15); + visitorId = 'v_' + randomUUID().replace(/-/g, ''); isNewVisitor = true; } @@ -238,7 +244,7 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str error: { code: 'PROCESSING_ERROR', messageKey: 'processingError', - message: err.message || 'Internal processing error', + message: 'Processing failed. Please try again.', retryable: true, }, }, diff --git a/src/app/api/user-quota/route.ts b/src/app/api/user-quota/route.ts index f301c7a..2050e7a 100644 --- a/src/app/api/user-quota/route.ts +++ b/src/app/api/user-quota/route.ts @@ -1,15 +1,20 @@ import { NextRequest, NextResponse } from 'next/server'; +import { randomUUID } from 'crypto'; import { checkRateLimits } from '@/lib/api/rateLimiter'; export const dynamic = 'force-dynamic'; export const revalidate = 0; export async function GET(req: NextRequest) { - const ip = req.headers.get('x-forwarded-for')?.split(',')[0].trim() || '127.0.0.1'; + const ip = + req.headers.get('x-real-ip') || + req.headers.get('x-forwarded-for')?.split(',')[0].trim() || + '127.0.0.1'; + let visitorId = req.cookies.get('photoai_vid')?.value; let isNewVisitor = false; if (!visitorId) { - visitorId = 'v_' + Math.random().toString(36).substring(2, 15); + visitorId = 'v_' + randomUUID().replace(/-/g, ''); isNewVisitor = true; } @@ -31,6 +36,7 @@ export async function GET(req: NextRequest) { maxAge: 60 * 60 * 24 * 30, httpOnly: true, sameSite: 'lax', + secure: process.env.NODE_ENV === 'production', }); } diff --git a/src/lib/api/mockEngine.ts b/src/lib/api/mockEngine.ts index f13e886..9791330 100644 --- a/src/lib/api/mockEngine.ts +++ b/src/lib/api/mockEngine.ts @@ -2,6 +2,7 @@ * Simulated neural processor for local dev, offline fallback, and PRD contract testing (API-11). * Transforms or filters incoming image buffer safely without external native dependencies. */ +import { deflateSync } from 'zlib'; export async function generateMockNeuralResult( imageBuffer: Buffer, toolId: string, @@ -29,7 +30,6 @@ export async function generateMockNeuralResult( } function createSyntheticArtPng(width: number, height: number, seedText: string): Buffer { - const zlib = require('zlib'); const signature = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); const ihdr = Buffer.alloc(13); @@ -55,7 +55,7 @@ function createSyntheticArtPng(width: number, height: number, seedText: string): } } - const compressed = zlib.deflateSync(rawData); + const compressed = deflateSync(rawData); const idatChunk = makePngChunk('IDAT', compressed); const iendChunk = makePngChunk('IEND', Buffer.alloc(0)); diff --git a/src/lib/api/rateLimiter.ts b/src/lib/api/rateLimiter.ts index 89e1497..6883ec2 100644 --- a/src/lib/api/rateLimiter.ts +++ b/src/lib/api/rateLimiter.ts @@ -18,8 +18,10 @@ export function checkRateLimits( ip: string, limits = { perVisitorPerDay: 5, perIpPerHour: 25, dailyBudgetCalls: 5000 } ): { allowed: boolean; reason?: 'visitor_daily' | 'ip_hourly' | 'budget_exhausted'; remainingToday: number } { - // Relax rate limits for local development, but respect explicit limits in test suites - const isLocal = process.env.NODE_ENV !== 'test' && (ip === '127.0.0.1' || ip === '::1' || ip === 'localhost' || !ip || process.env.NODE_ENV !== 'production'); + // Relax rate limits only for loopback addresses in development; never in production or test + const isLoopback = ip === '127.0.0.1' || ip === '::1' || ip === 'localhost'; + const isDev = process.env.NODE_ENV === 'development'; + const isLocal = isDev && isLoopback; const effectiveLimits = isLocal ? { perVisitorPerDay: 10000, perIpPerHour: 10000, dailyBudgetCalls: 50000 } : limits; diff --git a/src/lib/api/requestBuilder.ts b/src/lib/api/requestBuilder.ts index 03b2821..cdc416f 100644 --- a/src/lib/api/requestBuilder.ts +++ b/src/lib/api/requestBuilder.ts @@ -202,10 +202,13 @@ export async function executeBackendTryIt( // Inject Secret Key (PRD §7.11: Secrets never reach browser) const secretParam = endpoint.params.find((p) => p.isSecret || p.name === 'secretKey'); - const secretVal = process.env.API_SECRET_DEFAULT || 'abcdef'; - if (secretParam) { + const secretVal = process.env.API_SECRET_DEFAULT; + if (!secretVal) { + console.warn(`[Backend API] API_SECRET_DEFAULT not configured — skipping secret injection for endpoint ${endpoint.id}`); + } + if (secretVal && secretParam) { formData.append(secretParam.name, secretVal); - } else { + } else if (secretVal) { formData.append('secretKey', secretVal); }