Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 58x 58x 58x 58x 58x 58x 56x 56x 56x 56x 2x 2x 2x 2x 58x 1x 1x 1x 1x 1x 1x 1x 1x 1x 58x 58x 58x 58x 14x 58x 58x 1x 1x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 56x 56x 56x 56x 56x 56x 58x 1x 1x 1x 1x 1x 55x 58x 1x 1x 1x 1x 1x 54x 54x 58x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 50x 50x 50x 50x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 58x 1x 1x 1x 58x | /**
* Client Error Reporting API
*
* Receives error reports from the client application.
* Implements security hardening:
* - Rate limiting (20 errors/minute per IP)
* - Input validation (Zod schema)
* - Data sanitization (PII redaction)
* - Origin verification
* - Improved fingerprinting
*/
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { logger } from '@/lib/logging';
import { checkRateLimit, getRateLimitInfo, rateLimitPresets } from '@/lib/security/rate-limit';
import { clientErrorSchema } from '@/lib/monitoring/schemas';
import { generateErrorFingerprint } from '@/lib/monitoring/fingerprint';
import { sanitizeErrorData, sanitizeMetadata } from '@/lib/monitoring/sanitize';
/**
* Get allowed origins for error reporting
*/
function getAllowedOrigins(): string[] {
const origins: string[] = [];
if (process.env.NEXT_PUBLIC_APP_URL) {
origins.push(process.env.NEXT_PUBLIC_APP_URL);
}
// Allow localhost in development
if (process.env.NODE_ENV === 'development') {
origins.push('http://localhost:3000', 'http://127.0.0.1:3000');
}
return origins;
}
/**
* Verify request origin
*/
function verifyOrigin(request: NextRequest): { valid: boolean; origin: string | null } {
const origin = request.headers.get('origin');
const referer = request.headers.get('referer');
// No origin header (could be same-origin or server-side)
if (!origin) {
// Check referer as fallback
if (referer) {
try {
const refererOrigin = new URL(referer).origin;
const allowedOrigins = getAllowedOrigins();
return { valid: allowedOrigins.length === 0 || allowedOrigins.includes(refererOrigin), origin: refererOrigin };
} catch {
return { valid: true, origin: null }; // Allow if can't parse
}
}
return { valid: true, origin: null }; // Allow if no origin/referer
}
const allowedOrigins = getAllowedOrigins();
// If no origins configured, allow all (development mode)
if (allowedOrigins.length === 0) {
return { valid: true, origin };
}
return { valid: allowedOrigins.includes(origin), origin };
}
/**
* Get client IP address
*/
function getClientIP(request: NextRequest): string {
return (
request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ||
request.headers.get('x-real-ip') ||
'unknown'
);
}
export async function POST(request: NextRequest) {
const ip = getClientIP(request);
// Phase 5: Origin verification
const { valid: validOrigin, origin } = verifyOrigin(request);
if (!validOrigin) {
logger.warn('Error report rejected: invalid origin', { category: 'SECURITY', origin, ip });
return NextResponse.json(
{ success: false, error: 'Invalid origin' },
{ status: 403 }
);
}
// Phase 1: Rate limiting
const { limit, windowMs } = rateLimitPresets.errorReporting;
const allowed = checkRateLimit(`error:${ip}`, limit, windowMs);
const rateLimitInfo = getRateLimitInfo(`error:${ip}`, limit);
if (!allowed) {
logger.warn('Error rate limit exceeded', { category: 'SECURITY', ip });
return NextResponse.json(
{ success: false, error: 'Rate limit exceeded' },
{
status: 429,
headers: {
'X-RateLimit-Limit': rateLimitInfo.limit.toString(),
'X-RateLimit-Remaining': rateLimitInfo.remaining.toString(),
'X-RateLimit-Reset': rateLimitInfo.resetTime,
...(rateLimitInfo.retryAfter && { 'Retry-After': rateLimitInfo.retryAfter.toString() }),
},
}
);
}
try {
// Phase 2: Input validation
let body: unknown;
try {
const text = await request.text();
if (!text || text.trim() === '') {
return NextResponse.json(
{ success: false, error: 'Empty request body' },
{ status: 400 }
);
}
body = JSON.parse(text);
} catch {
return NextResponse.json(
{ success: false, error: 'Invalid JSON body' },
{ status: 400 }
);
}
const result = clientErrorSchema.safeParse(body);
if (!result.success) {
logger.warn('Invalid error payload', {
category: 'API',
ip,
errors: result.error.flatten(),
});
return NextResponse.json(
{
success: false,
error: 'Invalid error payload',
details: result.error.flatten().fieldErrors,
},
{ status: 400 }
);
}
const validatedData = result.data;
// Phase 4: Data sanitization
const sanitizedMessage = sanitizeErrorData(validatedData.message || 'Unknown client error');
const sanitizedStack = sanitizeErrorData(validatedData.stack || validatedData.componentStack || '');
const sanitizedMetadata = validatedData.metadata
? sanitizeMetadata(validatedData.metadata)
: undefined;
// Phase 3: Improved fingerprinting
const fingerprint = generateErrorFingerprint({
message: validatedData.message,
stack: validatedData.stack,
category: 'CLIENT',
url: validatedData.url,
});
if (process.env.CI !== 'true') {
// Log to database with sanitized data
await prisma.errorLog.create({
data: {
fingerprint,
level: 'error',
category: 'CLIENT',
message: sanitizedMessage,
stack: sanitizedStack,
url: validatedData.url,
userAgent: validatedData.userAgent,
ip,
requestId: validatedData.errorId,
metadata: sanitizedMetadata ? JSON.parse(JSON.stringify(sanitizedMetadata)) : undefined,
},
});
}
// Update statistics
await prisma.errorStatistic.upsert({
where: { fingerprint },
update: {
count: { increment: 1 },
lastSeen: new Date(),
},
create: {
fingerprint,
category: 'CLIENT',
message: sanitizedMessage.substring(0, 500),
count: 1,
firstSeen: new Date(),
lastSeen: new Date(),
},
});
logger.info('Client error reported', {
category: 'API',
fingerprint,
url: validatedData.url,
});
return NextResponse.json(
{ success: true },
{
headers: {
'X-RateLimit-Limit': rateLimitInfo.limit.toString(),
'X-RateLimit-Remaining': rateLimitInfo.remaining.toString(),
},
}
);
} catch (error) {
logger.error('Failed to log client error', error as Error, { category: 'API' });
return NextResponse.json({ success: false }, { status: 500 });
}
}
|