Expose recent-errors for Paperclip via api_key (BIT-684)

Add Fastify GET /v1/paperclip/recent-errors returning CRM-compatible JSON (data
envelope, project_slug per row, status open for open/investigating incidents).

Admin UI proxies the public path /api/error-monitoring/recent-errors to the API
base; middleware bypasses the session redirect for that path only.

Auth matches CRM env names: ERROR_RESOLVE_API_KEY or ERROR_REPORTING_API_KEY for
?api_key=, DEBUG_VIEW_ERRORS_KEY for ?view_errors=.

Paperclip-Agent: David Santos (urlKey david-santos; id 0b1fcf92-5fe3-4ac0-9f29-df4ab72f5376)
Paperclip-Issue: BIT-684
Paperclip-Run: cf7cb964-6953-4476-af09-3feb5d10da17
Made-with: Cursor
This commit is contained in:
David Santos committed 2026-04-01 14:18:00 +00:00
1 parent c899cef6e1
commit 6811dba303
6 files changed
+203

No files matched your search

@@ -0,0 +1,38 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
/**
* Proxies to Fastify (ERROR_REPORTING_ADMIN_API_BASE) so the public hostname
* serves the same path as the CRM (`/api/error-monitoring/recent-errors`).
* Auth is enforced by the API service (api_key / view_errors).
*/
export async function GET(request: NextRequest) {
const rawBase = process.env.ERROR_REPORTING_ADMIN_API_BASE?.trim();
if (!rawBase) {
return NextResponse.json(
{
success: false,
message: "ERROR_REPORTING_ADMIN_API_BASE is not configured.",
},
{ status: 503 },
);
}
const base = rawBase.replace(/\/$/, "");
const src = new URL(request.url);
const target = `${base}/v1/paperclip/recent-errors${src.search}`;
const upstream = await fetch(target, {
method: "GET",
headers: { Accept: "application/json" },
cache: "no-store",
});
const body = await upstream.text();
const ct = upstream.headers.get("Content-Type") ?? "application/json; charset=utf-8";
return new NextResponse(body, {
status: upstream.status,
headers: { "Content-Type": ct },
});
}
+5
View File
@@ -22,6 +22,11 @@ function _allowWithoutSession(): boolean {
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
/** Paperclip error loop + CRM contract: JSON GET with api_key; must not 307 to /login. */
if (pathname === "/api/error-monitoring/recent-errors") {
return NextResponse.next();
}
if (_allowWithoutSession()) {
return NextResponse.next();
}
+4
View File
@@ -15,6 +15,10 @@ JWT_SECRET=change_me_in_production_64_bytes_minimum
# Cookie signing — generate with: openssl rand -base64 32
COOKIE_SECRET=change_me_in_production_32_bytes_minimum
# Recent-errors for Paperclip (optional — if unset, GET /v1/paperclip/recent-errors returns 503)
# ERROR_RESOLVE_API_KEY=same_as_CRM_or_shared_hub_secret
# DEBUG_VIEW_ERRORS_KEY=read_only_alternate_query_param_view_errors
# Rate limits (optional — defaults shown)
# RATE_INGEST_MAX=1000
# RATE_INGEST_WINDOW_MS=60000
+2
View File
@@ -17,6 +17,7 @@ import { INGEST_MAX_BODY_BYTES, ADMIN_MAX_BODY_BYTES } from './plugins/rate-limi
import adminAuthRoutes from './routes/admin/auth.js';
import adminStatsRoutes from './routes/admin/stats.js';
import adminIncidentsRoutes from './routes/admin/incidents.js';
import recentErrorsPublicRoutes from './routes/public/recentErrors.js';
const IS_PROD = process.env.NODE_ENV === 'production';
@@ -63,6 +64,7 @@ await app.register(auditPlugin);
await app.register(rateLimitPlugin);
// Routes
await app.register(recentErrorsPublicRoutes);
await app.register(adminAuthRoutes);
await app.register(adminStatsRoutes);
await app.register(adminIncidentsRoutes);
+149
View File
@@ -0,0 +1,149 @@
/**
* Paperclip / CRM-compatible read-only listing for open incidents.
* GET /v1/paperclip/recent-errors?limit=&api_key=|view_errors=
*
* Auth: query param must match ERROR_RESOLVE_API_KEY or ERROR_REPORTING_API_KEY (api_key),
* or DEBUG_VIEW_ERRORS_KEY (view_errors). At least one server secret must be configured.
*/
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import { safeEqual } from '../../plugins/auth.js';
function resolveApiSecrets(): { apiKey: string; viewKey: string } {
const apiKey =
(process.env.ERROR_RESOLVE_API_KEY ?? process.env.ERROR_REPORTING_API_KEY ?? '').trim();
const viewKey = (process.env.DEBUG_VIEW_ERRORS_KEY ?? '').trim();
return { apiKey, viewKey };
}
function authorizeQuery(request: FastifyRequest, reply: FastifyReply): boolean {
const { apiKey, viewKey } = resolveApiSecrets();
if (!apiKey && !viewKey) {
reply.code(503).send({
success: false,
message: 'Recent-errors API is not configured (set ERROR_RESOLVE_API_KEY and/or DEBUG_VIEW_ERRORS_KEY).',
});
return false;
}
const q = request.query as { api_key?: string; view_errors?: string };
const providedApi = typeof q.api_key === 'string' ? q.api_key : '';
const providedView = typeof q.view_errors === 'string' ? q.view_errors : '';
if (apiKey && providedApi && safeEqual(providedApi, apiKey)) {
return true;
}
if (viewKey && providedView && safeEqual(providedView, viewKey)) {
return true;
}
reply.code(401).send({
success: false,
message: 'Unauthorized',
});
return false;
}
function parseJsonObject(raw: string | null): Record<string, unknown> | null {
if (raw == null || raw === '') {
return null;
}
try {
const v = JSON.parse(raw) as unknown;
if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
return v as Record<string, unknown>;
}
return null;
} catch {
return null;
}
}
function extractFileLine(ctx: Record<string, unknown> | null): { file_path: string; line_number: string } {
if (!ctx) {
return { file_path: '', line_number: '' };
}
const file_path = String(ctx.file_path ?? ctx.filename ?? ctx.path ?? ctx.file ?? '').trim();
const line_number = String(ctx.line_number ?? ctx.lineno ?? ctx.line ?? '').trim();
return { file_path, line_number };
}
export default async function recentErrorsPublicRoutes(app: FastifyInstance): Promise<void> {
const db = app.db;
app.get('/v1/paperclip/recent-errors', async (request, reply) => {
if (!authorizeQuery(request, reply)) {
return;
}
const q = request.query as { limit?: string };
let limit = 999999;
if (q.limit != null && q.limit !== '') {
const n = parseInt(String(q.limit), 10);
if (!Number.isFinite(n) || n < 1) {
return reply.code(400).send({ success: false, message: 'Invalid limit' });
}
limit = Math.min(n, 999999);
}
const sql = `
WITH ranked AS (
SELECT o.id,
o.incident_id,
o.message,
o.stack_trace AS stack_trace,
o.context_json AS context_json,
o.environment,
o.occurred_at AS occurred_at,
ROW_NUMBER() OVER (PARTITION BY o.incident_id ORDER BY o.occurred_at DESC) AS rn
FROM er_incident_occurrences o
INNER JOIN er_incidents i ON i.id = o.incident_id
WHERE i.current_state IN ('open', 'investigating')
)
SELECT CAST(i.id AS CHAR) AS incident_id,
CAST(r.id AS CHAR) AS occurrence_id,
p.slug AS project_slug,
i.severity AS incident_severity,
r.message,
r.stack_trace,
r.context_json,
r.environment,
r.occurred_at
FROM ranked r
INNER JOIN er_incidents i ON i.id = r.incident_id
INNER JOIN er_projects p ON p.id = i.project_id
WHERE r.rn = 1
ORDER BY r.occurred_at DESC
LIMIT ?
`;
const [rows] = await db.execute<RowDataPacket[]>(sql, [limit]);
const data = (rows as Record<string, unknown>[]).map((row) => {
const ctx = parseJsonObject(row.context_json != null ? String(row.context_json) : null);
const { file_path, line_number } = extractFileLine(ctx);
const incSev = String(row.incident_severity ?? 'medium').toLowerCase();
const sev = ['critical', 'high', 'medium', 'low'].includes(incSev) ? incSev : 'medium';
return {
status: 'open',
message: String(row.message ?? ''),
error_message: String(row.message ?? ''),
stack_trace: row.stack_trace != null ? String(row.stack_trace) : '',
file_path,
line_number,
severity: sev,
unique_id: String(row.occurrence_id ?? row.incident_id ?? ''),
project_slug: String(row.project_slug ?? '').toLowerCase(),
environment: String(row.environment ?? 'production'),
};
});
return reply.send({
success: true,
message: 'ok',
data,
});
});
}
+5
View File
@@ -31,6 +31,11 @@ MAX_BACKOFF_EXPONENT=8
# --- admin-ui (Next.js server-side API calls) — target the Fastify `api/` service (default PORT 3200) ---
ERROR_REPORTING_ADMIN_API_BASE=http://127.0.0.1:3200
# --- Paperclip error loop / CRM-compatible GET /api/error-monitoring/recent-errors (Fastify validates query) ---
# Same names as CRM: copy one secret into PAPERCLIP_ERROR_API_KEY or DEBUG_VIEW_ERRORS_KEY on the runner.
# ERROR_RESOLVE_API_KEY=CHANGE_ME
# DEBUG_VIEW_ERRORS_KEY=
# ERROR_REPORTING_UI_DEMO=1
# --- Demo / staging only: token must match seed SQL for project-alpha HTTP fixture ---