43 lines
1.7 KiB
TypeScript
43 lines
1.7 KiB
TypeScript
// PEP-91: errors from the browser (ErrorReporter) → Bugsink, source `web` of the platform project.
|
|
// No login needed (the login page breaks too): size cap and a per-IP limit instead.
|
|
import { reportPlatformError } from "@peppa/core";
|
|
import { db } from "@/lib/db";
|
|
|
|
const MAX_BYTES = 16 * 1024;
|
|
const PER_IP_PER_MIN = 20;
|
|
const hits = new Map<string, { at: number; n: number }>();
|
|
|
|
function limited(ip: string, now = Date.now()): boolean {
|
|
const h = hits.get(ip);
|
|
if (!h || now - h.at >= 60_000) {
|
|
if (hits.size > 5000) hits.clear();
|
|
hits.set(ip, { at: now, n: 1 });
|
|
return false;
|
|
}
|
|
return ++h.n > PER_IP_PER_MIN;
|
|
}
|
|
|
|
const str = (v: unknown, max: number) => (typeof v === "string" ? v.slice(0, max) : undefined);
|
|
|
|
export async function POST(req: Request) {
|
|
const ip = req.headers.get("cf-connecting-ip") ?? req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "local";
|
|
if (limited(ip)) return new Response(null, { status: 429 });
|
|
const raw = await req.text();
|
|
if (raw.length > MAX_BYTES) return new Response(null, { status: 413 });
|
|
let b: Record<string, unknown>;
|
|
try {
|
|
b = JSON.parse(raw) as Record<string, unknown>;
|
|
} catch {
|
|
return new Response(null, { status: 400 });
|
|
}
|
|
const message = str(b.message, 2000);
|
|
if (!message) return new Response(null, { status: 400 });
|
|
const path = str(b.url, 500);
|
|
const sent = await reportPlatformError(
|
|
db,
|
|
{ name: str(b.type, 100) || "Error", message, stack: str(b.stack, 8000) },
|
|
{ service: "browser", kind: "web", platform: "javascript", where: path?.split("?")[0], request: { url: path, method: "GET", userAgent: req.headers.get("user-agent") ?? undefined } },
|
|
);
|
|
return Response.json({ sent });
|
|
}
|