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:
1 parent
c899cef6e1
commit
6811dba303
6 files changed
+203
No files matched your search
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user