peppa/apps/web/app/api/client-errors/route.ts
Асель 6e54fc69a6 PEP-91: Peppa reports its own errors to Bugsink — backend to PEP-api, browser to PEP-web
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:39:46 +05:00

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