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',
});
}