feat(admin): add production error center and refresh CMS dependencies
This commit is contained in:
1 parent
c6b919c01d
commit
816e3875c2
47 files changed
+1545
-547
No files matched your search
@@ -0,0 +1,79 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ append: vi.fn(), limit: vi.fn() }));
|
||||
vi.mock("@/lib/rate-limit", () => ({
|
||||
clientIp: async () => "test",
|
||||
rateLimit: mocks.limit,
|
||||
}));
|
||||
vi.mock("@/lib/error-monitor", async () => {
|
||||
const actual = await vi.importActual<typeof import("@/lib/error-monitor")>(
|
||||
"@/lib/error-monitor",
|
||||
);
|
||||
return {
|
||||
...actual,
|
||||
ErrorStore: class {
|
||||
append = mocks.append;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { POST } from "./route";
|
||||
|
||||
afterEach(() => vi.resetAllMocks());
|
||||
const req = (body: string, origin = "https://cms.test") =>
|
||||
new Request("https://cms.test/api/diagnostics/errors", {
|
||||
method: "POST",
|
||||
headers: { origin, "Content-Type": "application/json" },
|
||||
body,
|
||||
});
|
||||
it("rejects cross-origin reports before touching storage", async () => {
|
||||
expect((await POST(req("{}", "https://other.test"))).status).toBe(403);
|
||||
expect(mocks.append).not.toHaveBeenCalled();
|
||||
});
|
||||
it("limits reports before reading their body", async () => {
|
||||
mocks.limit.mockResolvedValue({ ok: false });
|
||||
expect((await POST(req("{}"))).status).toBe(429);
|
||||
expect(mocks.append).not.toHaveBeenCalled();
|
||||
});
|
||||
it("rejects oversized reports without trusting content-length", async () => {
|
||||
mocks.limit.mockResolvedValue({ ok: true });
|
||||
expect((await POST(req("a".repeat(17000)))).status).toBe(413);
|
||||
expect(mocks.append).not.toHaveBeenCalled();
|
||||
});
|
||||
it("stores only sanitized diagnostic fields and identifies browser claims", async () => {
|
||||
mocks.limit.mockResolvedValue({ ok: true });
|
||||
mocks.append.mockResolvedValue(undefined);
|
||||
const r = await POST(
|
||||
req(
|
||||
JSON.stringify({
|
||||
event: "browser.exception",
|
||||
message: "token=secret",
|
||||
path: "/news?token=hidden",
|
||||
body: "never store",
|
||||
release: "old-client",
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(r.status).toBe(202);
|
||||
const saved = mocks.append.mock.calls[0][0];
|
||||
expect(saved.source).toBe("browser");
|
||||
expect(saved.context.clientRelease).toBe("old-client");
|
||||
expect(JSON.stringify(saved)).not.toMatch(/hidden|never store|token=secret/);
|
||||
});
|
||||
it("reports storage failure rather than claiming receipt", async () => {
|
||||
mocks.limit.mockResolvedValue({ ok: true });
|
||||
mocks.append.mockRejectedValue(new Error("disk"));
|
||||
expect(
|
||||
(
|
||||
await POST(
|
||||
req(
|
||||
JSON.stringify({
|
||||
event: "browser.exception",
|
||||
message: "failure",
|
||||
path: "/",
|
||||
}),
|
||||
),
|
||||
)
|
||||
).status,
|
||||
).toBe(503);
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { createErrorRecord, ErrorStore } from "@/lib/error-monitor";
|
||||
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
||||
|
||||
const schema = z.object({
|
||||
event: z.enum([
|
||||
"browser.exception",
|
||||
"browser.boundary",
|
||||
"browser.unhandled_rejection",
|
||||
]),
|
||||
clientReference: z.string().uuid().optional(),
|
||||
message: z.string().max(1000),
|
||||
stack: z.string().max(6000).optional(),
|
||||
path: z.string().startsWith("/").max(1000),
|
||||
digest: z.string().max(200).optional(),
|
||||
release: z.string().max(100).optional(),
|
||||
});
|
||||
export async function POST(request: Request) {
|
||||
if (
|
||||
request.headers.get("origin") !==
|
||||
new URL(
|
||||
process.env.APP_URL || process.env.NEXT_PUBLIC_APP_URL || request.url,
|
||||
).origin ||
|
||||
!request.headers.get("content-type")?.startsWith("application/json")
|
||||
)
|
||||
return new Response(null, { status: 403 });
|
||||
const limit = await rateLimit(`cms-error:${await clientIp()}`, 20, 60000);
|
||||
if (!limit.ok) return new Response(null, { status: 429 });
|
||||
const reader = request.body?.getReader();
|
||||
if (!reader) return new Response(null, { status: 400 });
|
||||
const chunks: Uint8Array[] = [];
|
||||
let length = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
length += value.byteLength;
|
||||
if (length > 16000) {
|
||||
await reader.cancel();
|
||||
return new Response(null, { status: 413 });
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
const parsed = schema.safeParse(
|
||||
JSON.parse(Buffer.concat(chunks).toString("utf8")),
|
||||
);
|
||||
if (!parsed.success) return new Response(null, { status: 400 });
|
||||
const data = parsed.data;
|
||||
const error = new Error(data.message);
|
||||
error.stack = data.stack ?? "";
|
||||
const record = createErrorRecord("browser", data.event, error, {
|
||||
clientReference: data.clientReference ?? null,
|
||||
path: data.path.split("?")[0],
|
||||
digest: data.digest ?? null,
|
||||
clientRelease: data.release ?? "unknown",
|
||||
});
|
||||
await new ErrorStore().append(record);
|
||||
return NextResponse.json(
|
||||
{ id: record.id },
|
||||
{ status: 202, headers: { "Cache-Control": "no-store" } },
|
||||
);
|
||||
} catch {
|
||||
return new Response(null, { status: 503 });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user