security: comprehensive hardening pass — CSP, CORS lockdown, CSRF strict-origin, error leak redaction, crypto visitor IDs, rate limiter fix, catalog admin guard, ESM imports, production cookie flags

This commit is contained in:
2026-11-13 11:34:32 +05:30
parent d53c1e071a
commit 56d72d69e6
10 changed files with 157 additions and 33 deletions
+32 -7
View File
@@ -2,13 +2,38 @@
# CRE Innovations - Web Studio Environment Configuration # 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) # Firebase Client SDK Configuration (Required for Live Client Auth)
# Obtain from: Firebase Console > Project Settings > General > Your apps (Web) # Obtain from: Firebase Console > Project Settings > General > Your apps (Web)
# ------------------------------------------------------------------------- # ---------------------------------------------------------------------------
NEXT_PUBLIC_FIREBASE_API_KEY=your_api_key_here NEXT_PUBLIC_FIREBASE_API_KEY=your_api_key_here
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your_project_id.firebaseapp.com NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your_project_id.firebaseapp.com
NEXT_PUBLIC_FIREBASE_PROJECT_ID=your_project_id 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_APP_ID=1:your_app_id:web:your_web_id
NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID=G-XXXXXXXXXX NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID=G-XXXXXXXXXX
# ------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Firebase Admin SDK Configuration (Required for Server Session Minting) # Firebase Admin SDK Configuration (Required for Server Session Minting)
# Obtain from: Firebase Console > Project Settings > Service accounts > Generate new private key # Obtain from: Firebase Console > Project Settings > Service accounts > Generate new private key
# ------------------------------------------------------------------------- # ---------------------------------------------------------------------------
FIREBASE_PROJECT_ID=your_project_id FIREBASE_PROJECT_ID=your_project_id
FIREBASE_CLIENT_EMAIL=firebase-adminsdk-xxxxx@your_project_id.iam.gserviceaccount.com 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"
+43 -3
View File
@@ -49,13 +49,53 @@ const nextConfig = {
serverComponentsExternalPackages: ['sharp'], serverComponentsExternalPackages: ['sharp'],
}, },
async headers() { async headers() {
const isProd = process.env.NODE_ENV === 'production';
const allowedOrigin = process.env.ALLOWED_ORIGIN || '*';
return [ return [
{ {
// Global security headers on every response
source: '/:path*', source: '/:path*',
headers: [ headers: [
{ key: 'Access-Control-Allow-Origin', value: '*' }, // Content Security Policy — tightened; adjust 'self' sources as needed
{ key: 'Access-Control-Allow-Methods', value: 'GET,OPTIONS,PATCH,DELETE,POST,PUT' }, {
{ key: 'Access-Control-Allow-Headers', value: '*' }, 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' },
], ],
}, },
]; ];
+26 -3
View File
@@ -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. * 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 { function isValidOrigin(req: NextRequest): boolean {
const origin = req.headers.get('origin'); 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'); const host = req.headers.get('host');
if (!host) return false; 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 { try {
const originUrl = new URL(origin); const originUrl = new URL(origin);
return originUrl.host === host; return originUrl.host === host;
@@ -59,13 +74,21 @@ export async function POST(req: NextRequest) {
}); });
return res; 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, { res.cookies.set(SESSION_COOKIE_NAME, idToken, {
maxAge: 3600, maxAge: 3600,
httpOnly: true, httpOnly: true,
secure: isProduction, secure: false,
path: '/', path: '/',
sameSite: 'lax', sameSite: 'lax',
}); });
+24 -5
View File
@@ -1,9 +1,27 @@
import { NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { normaliseCatalog } from '@/lib/catalog/loader'; import { normaliseCatalog } from '@/lib/catalog/loader';
export const dynamic = 'force-dynamic'; 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 { try {
const { endpoints, diff } = normaliseCatalog(); const { endpoints, diff } = normaliseCatalog();
return NextResponse.json({ return NextResponse.json({
@@ -13,13 +31,14 @@ export async function POST() {
diff, diff,
}); });
} catch (err: any) { } catch (err: any) {
console.error('[Catalog Reload] Error:', err);
return NextResponse.json( return NextResponse.json(
{ success: false, error: err.message }, { success: false, error: 'Catalog reload failed' },
{ status: 500 } { status: 500 }
); );
} }
} }
export async function GET() { export async function GET(req: NextRequest) {
return POST(); return POST(req);
} }
+3 -3
View File
@@ -1,4 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { deflateSync } from 'zlib';
export const dynamic = 'force-dynamic'; export const dynamic = 'force-dynamic';
@@ -43,7 +44,7 @@ export async function POST(req: NextRequest) {
} catch (err: any) { } catch (err: any) {
console.error('[API /mask/auto-detect] Error:', err); console.error('[API /mask/auto-detect] Error:', err);
return NextResponse.json( return NextResponse.json(
{ error: 'Failed to generate auto-mask', details: err.message }, { error: 'Failed to generate auto-mask' },
{ status: 500 } { status: 500 }
); );
} }
@@ -100,8 +101,7 @@ function createSilhouetteMaskPng(width: number, height: number): Buffer {
} }
// Compress using zlib // Compress using zlib
const zlib = require('zlib'); const compressed = deflateSync(rawData);
const compressed = zlib.deflateSync(rawData);
const idatChunk = makeChunk('IDAT', compressed); const idatChunk = makeChunk('IDAT', compressed);
// IEND // IEND
+9 -3
View File
@@ -1,4 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { randomUUID } from 'crypto';
import { getToolById, getToolBySlug } from '@/lib/config/loader'; import { getToolById, getToolBySlug } from '@/lib/config/loader';
import { getEndpointById } from '@/lib/catalog/loader'; import { getEndpointById } from '@/lib/catalog/loader';
import { checkRateLimits, recordUsage } from '@/lib/api/rateLimiter'; import { checkRateLimits, recordUsage } from '@/lib/api/rateLimiter';
@@ -36,11 +37,16 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str
} }
// Rate Limiting & Abuse Prevention // 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 visitorId = req.cookies.get('photoai_vid')?.value;
let isNewVisitor = false; let isNewVisitor = false;
if (!visitorId) { if (!visitorId) {
visitorId = 'v_' + Math.random().toString(36).substring(2, 15); visitorId = 'v_' + randomUUID().replace(/-/g, '');
isNewVisitor = true; isNewVisitor = true;
} }
@@ -238,7 +244,7 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str
error: { error: {
code: 'PROCESSING_ERROR', code: 'PROCESSING_ERROR',
messageKey: 'processingError', messageKey: 'processingError',
message: err.message || 'Internal processing error', message: 'Processing failed. Please try again.',
retryable: true, retryable: true,
}, },
}, },
+8 -2
View File
@@ -1,15 +1,20 @@
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { randomUUID } from 'crypto';
import { checkRateLimits } from '@/lib/api/rateLimiter'; import { checkRateLimits } from '@/lib/api/rateLimiter';
export const dynamic = 'force-dynamic'; export const dynamic = 'force-dynamic';
export const revalidate = 0; export const revalidate = 0;
export async function GET(req: NextRequest) { 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 visitorId = req.cookies.get('photoai_vid')?.value;
let isNewVisitor = false; let isNewVisitor = false;
if (!visitorId) { if (!visitorId) {
visitorId = 'v_' + Math.random().toString(36).substring(2, 15); visitorId = 'v_' + randomUUID().replace(/-/g, '');
isNewVisitor = true; isNewVisitor = true;
} }
@@ -31,6 +36,7 @@ export async function GET(req: NextRequest) {
maxAge: 60 * 60 * 24 * 30, maxAge: 60 * 60 * 24 * 30,
httpOnly: true, httpOnly: true,
sameSite: 'lax', sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
}); });
} }
+2 -2
View File
@@ -2,6 +2,7 @@
* Simulated neural processor for local dev, offline fallback, and PRD contract testing (API-11). * 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. * Transforms or filters incoming image buffer safely without external native dependencies.
*/ */
import { deflateSync } from 'zlib';
export async function generateMockNeuralResult( export async function generateMockNeuralResult(
imageBuffer: Buffer, imageBuffer: Buffer,
toolId: string, toolId: string,
@@ -29,7 +30,6 @@ export async function generateMockNeuralResult(
} }
function createSyntheticArtPng(width: number, height: number, seedText: string): Buffer { 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 signature = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
const ihdr = Buffer.alloc(13); 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 idatChunk = makePngChunk('IDAT', compressed);
const iendChunk = makePngChunk('IEND', Buffer.alloc(0)); const iendChunk = makePngChunk('IEND', Buffer.alloc(0));
+4 -2
View File
@@ -18,8 +18,10 @@ export function checkRateLimits(
ip: string, ip: string,
limits = { perVisitorPerDay: 5, perIpPerHour: 25, dailyBudgetCalls: 5000 } limits = { perVisitorPerDay: 5, perIpPerHour: 25, dailyBudgetCalls: 5000 }
): { allowed: boolean; reason?: 'visitor_daily' | 'ip_hourly' | 'budget_exhausted'; remainingToday: number } { ): { allowed: boolean; reason?: 'visitor_daily' | 'ip_hourly' | 'budget_exhausted'; remainingToday: number } {
// Relax rate limits for local development, but respect explicit limits in test suites // Relax rate limits only for loopback addresses in development; never in production or test
const isLocal = process.env.NODE_ENV !== 'test' && (ip === '127.0.0.1' || ip === '::1' || ip === 'localhost' || !ip || process.env.NODE_ENV !== 'production'); 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 const effectiveLimits = isLocal
? { perVisitorPerDay: 10000, perIpPerHour: 10000, dailyBudgetCalls: 50000 } ? { perVisitorPerDay: 10000, perIpPerHour: 10000, dailyBudgetCalls: 50000 }
: limits; : limits;
+6 -3
View File
@@ -202,10 +202,13 @@ export async function executeBackendTryIt(
// Inject Secret Key (PRD §7.11: Secrets never reach browser) // Inject Secret Key (PRD §7.11: Secrets never reach browser)
const secretParam = endpoint.params.find((p) => p.isSecret || p.name === 'secretKey'); const secretParam = endpoint.params.find((p) => p.isSecret || p.name === 'secretKey');
const secretVal = process.env.API_SECRET_DEFAULT || 'abcdef'; const secretVal = process.env.API_SECRET_DEFAULT;
if (secretParam) { 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); formData.append(secretParam.name, secretVal);
} else { } else if (secretVal) {
formData.append('secretKey', secretVal); formData.append('secretKey', secretVal);
} }