feat(admin-ui): add POST /api/error-monitoring/php-error bridge (BIT-1541)

Translates CRM-shaped ErrorMonitoringReporter payloads (project_slug,
gitea_repo at top level) to ingest-api /v1/ingest/events format.  Both
routing fields are promoted into the event context so they are persisted
in context_json and surfaced by GET /api/error-monitoring/recent-errors,
unblocking ERRSIG routing validation for CasamentoWeb.

Auth: X-Error-Monitoring-Key is forwarded as Bearer to the ingest-api;
the key must be registered in er_ingest_keys for the target project.

Paperclip-Issue: BIT-1541
Co-Authored-By: Paperclip <[email protected]>
This commit is contained in:
David SantosandPaperclip committed 2026-04-08 00:48:43 +00:00
1 parent a51b3e987a
commit f8c401a990
1 file changed
+165
@@ -0,0 +1,165 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
/**
* CRM-shaped PHP error ingest bridge.
*
* Receives the legacy `X-Error-Monitoring-Key` + flat JSON payload sent by
* ErrorMonitoringReporter (CasamentoWeb, CRM, etc.) and translates it to the
* ingest-api `/v1/ingest/events` schema, ensuring `gitea_repo` and
* `project_slug` are promoted into the event `context` so they are persisted
* in `context_json` and returned by `GET /api/error-monitoring/recent-errors`.
*
* Auth: the `X-Error-Monitoring-Key` value is forwarded as `Authorization:
* Bearer` to the ingest-api — the key must exist in `er_ingest_keys`.
*/
interface CrmPhpPayload {
message?: unknown;
severity?: unknown;
level?: unknown;
stack_trace?: unknown;
stacktrace?: unknown;
file_path?: unknown;
line_number?: unknown;
error_type?: unknown;
environment?: unknown;
url?: unknown;
http_method?: unknown;
ip_address?: unknown;
user_agent?: unknown;
context_data?: unknown;
// routing metadata (hub-mirrored fields)
project_slug?: unknown;
project_name?: unknown;
gitea_repo?: unknown;
}
function safeStr(v: unknown): string {
return typeof v === "string" ? v : "";
}
export async function POST(request: NextRequest) {
const ingestApiUrl = (process.env.INGEST_API_URL ?? "http://127.0.0.1:3041").replace(/\/$/, "");
// Extract auth key — forwarded as Bearer to ingest-api.
const monitoringKey =
request.headers.get("x-error-monitoring-key")?.trim() ??
request.headers.get("x-api-key")?.trim() ??
"";
if (!monitoringKey) {
return NextResponse.json(
{ success: false, message: "Missing X-Error-Monitoring-Key header." },
{ status: 401 },
);
}
let body: CrmPhpPayload;
try {
body = (await request.json()) as CrmPhpPayload;
} catch {
return NextResponse.json(
{ success: false, message: "Invalid JSON body." },
{ status: 400 },
);
}
const message = safeStr(body.message);
if (!message) {
return NextResponse.json(
{ success: false, message: "Missing required field: message." },
{ status: 400 },
);
}
// Normalise severity → ingest level.
const level = safeStr(body.severity || body.level) || "error";
// Stack trace (CRM uses snake_case `stack_trace`).
const stackTrace = safeStr(body.stack_trace || body.stacktrace);
// Build context: start with context_data, then promote top-level routing
// fields so they land in context_json and are readable by recent-errors.
const contextData: Record<string, unknown> =
body.context_data !== null &&
typeof body.context_data === "object" &&
!Array.isArray(body.context_data)
? { ...(body.context_data as Record<string, unknown>) }
: {};
// Routing metadata — always overwrite so reporter values win.
const gitea_repo = safeStr(body.gitea_repo);
const project_slug = safeStr(body.project_slug);
const project_name = safeStr(body.project_name);
if (gitea_repo) contextData.gitea_repo = gitea_repo;
if (project_slug) contextData.project_slug = project_slug;
if (project_name) contextData.project_name = project_name;
// Preserve other top-level diagnostic fields.
const file_path = safeStr(body.file_path);
const line_number = safeStr(body.line_number);
const error_type = safeStr(body.error_type);
if (file_path) contextData.file_path = file_path;
if (line_number) contextData.line_number = line_number;
if (error_type) contextData.error_type = error_type;
const httpUrl = safeStr(body.url);
if (httpUrl) contextData.url = httpUrl;
const httpMethod = safeStr(body.http_method);
if (httpMethod) contextData.http_method = httpMethod;
const ipAddress = safeStr(body.ip_address);
if (ipAddress) contextData.ip_address = ipAddress;
const userAgent = safeStr(body.user_agent);
if (userAgent) contextData.user_agent = userAgent;
const event = {
schema_version: 1,
occurred_at: new Date().toISOString(),
level,
message,
...(stackTrace ? { stack_trace: stackTrace } : {}),
...(Object.keys(contextData).length > 0 ? { context: contextData } : {}),
};
const ingestTarget = `${ingestApiUrl}/v1/ingest/events`;
const ingestBody = JSON.stringify({ events: [event] });
let upstream: Response;
try {
upstream = await fetch(ingestTarget, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${monitoringKey}`,
},
body: ingestBody,
cache: "no-store",
});
} catch (err) {
const msg = err instanceof Error ? err.message : "ingest_unreachable";
return NextResponse.json(
{ success: false, message: `Ingest API unreachable: ${msg}` },
{ status: 502 },
);
}
if (upstream.status === 401) {
return NextResponse.json(
{ success: false, message: "Ingest key not recognised." },
{ status: 401 },
);
}
if (!upstream.ok) {
const errText = await upstream.text().catch(() => "");
return NextResponse.json(
{ success: false, message: `Ingest failed (${upstream.status}): ${errText}` },
{ status: upstream.status >= 500 ? 502 : upstream.status },
);
}
return NextResponse.json({ success: true, message: "ok" });
}