peppa/apps/web/app/api/client-vitals/route.ts
peppa-bot d8a37833f3
All checks were successful
peppa/build build: success за 16с
peppa/bundle bundle: success за 0с
peppa/lint lint: success за 1с
peppa/typecheck typecheck: success за 21с
PEP-217: Web Vitals пользователей, проверка веса JS в CI, словари не в браузерном бандле
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 17:03:07 +05:00

39 lines
1.6 KiB
TypeScript

// PEP-217: Web Vitals from the browser (WebVitals) → observe.db. No login (the login page counts
// too): a size cap and a per-IP limit like /api/client-errors. Nothing but a route without ids,
// the metric, the value, the screen kind and the mode is stored — no user, no keys, no address.
import { recordVital } from "@peppa/core";
const MAX_BYTES = 4 * 1024;
const PER_IP_PER_MIN = 30;
const MAX_ITEMS = 8;
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;
}
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: { route?: unknown; device?: unknown; mode?: unknown; metrics?: unknown };
try {
b = JSON.parse(raw) as typeof b;
} catch {
return new Response(null, { status: 400 });
}
if (!Array.isArray(b.metrics)) return new Response(null, { status: 400 });
let stored = 0;
for (const m of b.metrics.slice(0, MAX_ITEMS) as Array<{ metric?: unknown; value?: unknown }>) {
if (m && recordVital({ route: b.route, metric: m.metric, value: m.value, device: b.device, mode: b.mode })) stored++;
}
return new Response(null, { status: stored ? 204 : 400 });
}