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
+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.
* 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',
});
+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';
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);
}
+3 -3
View File
@@ -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
+9 -3
View File
@@ -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,
},
},
+8 -2
View File
@@ -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',
});
}
+2 -2
View File
@@ -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));
+4 -2
View File
@@ -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;
+6 -3
View File
@@ -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);
}