feat(api): CRM parity mutations and recent-errors filters (BIT-726)
Add POST /api/error-monitoring/resolve, bulk-resolve, and purge-resolved with resolve key or admin JWT (errors:triage / errors:delete). Extend GET recent-errors with status, severity, project_slug, q, offset, and stable ordering. Document contracts in api/docs/ERROR_MONITORING_PUBLIC_API.md; add vitest for public auth helpers. Proxy new routes and widen admin-ui middleware for /api/error-monitoring/*. Paperclip-Issue: BIT-726 Paperclip-Run: 3fbf92be-736e-4b11-8e90-cf993d8cd5ca Paperclip-Agent: Pedro Alves (id d706f4e6-5d05-4cec-b6e8-f8fb1f203aae) Made-with: Cursor
This commit is contained in:
1 parent
e0af92eda1
commit
8b0044be82
10 files changed
+919
-49
No files matched your search
@@ -0,0 +1,47 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST(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 target = `${base}/api/error-monitoring/bulk-resolve`;
|
||||
const body = await request.text();
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
Accept: "application/json",
|
||||
"Content-Type": request.headers.get("Content-Type") ?? "application/json",
|
||||
};
|
||||
const cookie = request.headers.get("cookie");
|
||||
if (cookie) {
|
||||
headers.Cookie = cookie;
|
||||
}
|
||||
const resolveHdr = request.headers.get("x-error-resolve-key");
|
||||
if (resolveHdr) {
|
||||
headers["X-Error-Resolve-Key"] = resolveHdr;
|
||||
}
|
||||
|
||||
const upstream = await fetch(target, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: body || undefined,
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
const text = await upstream.text();
|
||||
const ct = upstream.headers.get("Content-Type") ?? "application/json; charset=utf-8";
|
||||
return new NextResponse(text, {
|
||||
status: upstream.status,
|
||||
headers: { "Content-Type": ct },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST(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 target = `${base}/api/error-monitoring/purge-resolved`;
|
||||
const body = await request.text();
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
Accept: "application/json",
|
||||
"Content-Type": request.headers.get("Content-Type") ?? "application/json",
|
||||
};
|
||||
const cookie = request.headers.get("cookie");
|
||||
if (cookie) {
|
||||
headers.Cookie = cookie;
|
||||
}
|
||||
const resolveHdr = request.headers.get("x-error-resolve-key");
|
||||
if (resolveHdr) {
|
||||
headers["X-Error-Resolve-Key"] = resolveHdr;
|
||||
}
|
||||
|
||||
const upstream = await fetch(target, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: body || undefined,
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
const text = await upstream.text();
|
||||
const ct = upstream.headers.get("Content-Type") ?? "application/json; charset=utf-8";
|
||||
return new NextResponse(text, {
|
||||
status: upstream.status,
|
||||
headers: { "Content-Type": ct },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST(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 target = `${base}/api/error-monitoring/resolve`;
|
||||
const body = await request.text();
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
Accept: "application/json",
|
||||
"Content-Type": request.headers.get("Content-Type") ?? "application/json",
|
||||
};
|
||||
const cookie = request.headers.get("cookie");
|
||||
if (cookie) {
|
||||
headers.Cookie = cookie;
|
||||
}
|
||||
const resolveHdr = request.headers.get("x-error-resolve-key");
|
||||
if (resolveHdr) {
|
||||
headers["X-Error-Resolve-Key"] = resolveHdr;
|
||||
}
|
||||
|
||||
const upstream = await fetch(target, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: body || undefined,
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
const text = await upstream.text();
|
||||
const ct = upstream.headers.get("Content-Type") ?? "application/json; charset=utf-8";
|
||||
return new NextResponse(text, {
|
||||
status: upstream.status,
|
||||
headers: { "Content-Type": ct },
|
||||
});
|
||||
}
|
||||
@@ -22,8 +22,8 @@ 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.startsWith("/api/error-monitoring/recent-errors")) {
|
||||
/** Paperclip + CRM contract: JSON with api_key on Fastify; proxy routes must not 307 to /login. */
|
||||
if (pathname.startsWith("/api/error-monitoring/")) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
# Public error-monitoring API (hub)
|
||||
|
||||
CRM-shaped JSON endpoints served by the Fastify API (`@errors-bitreport/api`). Same paths as the CRM `ErrorMonitoring` module where noted.
|
||||
|
||||
## Authentication
|
||||
|
||||
### Read (`GET …/recent-errors`)
|
||||
|
||||
- Query: `api_key` must match `ERROR_RESOLVE_API_KEY` or `ERROR_REPORTING_API_KEY`, **or**
|
||||
- Query: `view_errors` must match `DEBUG_VIEW_ERRORS_KEY`.
|
||||
- If neither server secret is set → **503**.
|
||||
|
||||
### Mutations (`POST …/resolve`, `bulk-resolve`, `purge-resolved`)
|
||||
|
||||
- Header `X-Error-Resolve-Key` or JSON body field `api_key` must match `ERROR_RESOLVE_API_KEY` or `ERROR_REPORTING_API_KEY` when that secret is set, **or**
|
||||
- Admin session: HTTP-only cookie `__Host-access` (JWT) with:
|
||||
- `errors:triage` for resolve and bulk-resolve
|
||||
- `errors:delete` for purge-resolved
|
||||
- If no resolve key is configured → only session auth is accepted (token-only automation is disabled).
|
||||
|
||||
## `GET /api/error-monitoring/recent-errors`
|
||||
|
||||
Alias: `GET /v1/paperclip/recent-errors`
|
||||
|
||||
| Query | Description |
|
||||
|--------|-------------|
|
||||
| `limit` | Max rows (default large cap; invalid → **400**) |
|
||||
| `offset` | Pagination offset (default `0`) |
|
||||
| `status` | Comma-separated: `open`, `investigating`, `resolved`, `ignored` (default `open,investigating`) |
|
||||
| `severity` | `critical` \| `high` \| `medium` \| `low` \| `info` |
|
||||
| `project_slug` | Project slug (lowercase) |
|
||||
| `q` | Search incident title, occurrence message, or fingerprint (`LIKE`) |
|
||||
| `order` | `occurred_at_desc` (default) or `occurred_at_asc` (tie-break: `occurrence id`) |
|
||||
|
||||
**Response:** `{ "success": true, "message": "ok", "data": [ … ] }`
|
||||
|
||||
Each row includes CRM-compatible fields. For non-resolved incidents, `status` is always `"open"` (including `investigating`) so Paperclip `error_loop` continues to treat rows as open.
|
||||
|
||||
## `POST /api/error-monitoring/resolve`
|
||||
|
||||
**Body (JSON):**
|
||||
|
||||
| Field | Required | Description |
|
||||
|--------|-----------|-------------|
|
||||
| `unique_id` | yes | Latest occurrence id as returned in `recent-errors`, or incident id |
|
||||
| `resolution_notes` | no | Stored in state history note (default message if omitted) |
|
||||
| `assigned_to` | no | Appended to the change note for traceability |
|
||||
| `api_key` | no | Resolve key if not using header / session |
|
||||
|
||||
**Responses:** **200** success envelope; **400** missing id; **401** auth; **404** not found or not resolvable; **503** if read keys not applicable (mutations use resolve key / session only).
|
||||
|
||||
## `POST /api/error-monitoring/bulk-resolve`
|
||||
|
||||
**Body (JSON):**
|
||||
|
||||
| Field | Required | Description |
|
||||
|--------|-----------|-------------|
|
||||
| `unique_ids` | one of | Non-empty array of numeric string ids (max 1000); maps to incidents via occurrence or incident id |
|
||||
| `message_pattern` | one of | String or array of strings (max 20); resolves incidents with any open occurrence whose `message` contains the substring (`LIKE %pattern%`) |
|
||||
| `resolution_notes` | no | Default bulk message if omitted |
|
||||
| `assigned_to` | no | Appended to note |
|
||||
| `api_key` | no | Resolve key |
|
||||
|
||||
If both `unique_ids` and `message_pattern` are sent, **`unique_ids` wins** (CRM behaviour).
|
||||
|
||||
## `POST /api/error-monitoring/purge-resolved`
|
||||
|
||||
**Body (JSON):**
|
||||
|
||||
| Field | Description |
|
||||
|--------|-------------|
|
||||
| `dry_run` | If true, returns `would_delete` count only |
|
||||
| `api_key` | Optional resolve key |
|
||||
|
||||
**Effect:** `DELETE` from `er_incidents` where `current_state = 'resolved'` (cascades occurrences and related rows per schema).
|
||||
|
||||
## Admin UI proxy
|
||||
|
||||
When the Next admin UI is deployed with `ERROR_REPORTING_ADMIN_API_BASE`, the same paths under `/api/error-monitoring/*` are reverse-proxied to Fastify (see `admin-ui/app/api/error-monitoring/*/route.ts`).
|
||||
@@ -18,6 +18,7 @@ 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';
|
||||
import errorMonitoringMutationsRoutes from './routes/public/errorMonitoringMutations.js';
|
||||
|
||||
const IS_PROD = process.env.NODE_ENV === 'production';
|
||||
|
||||
@@ -65,6 +66,7 @@ await app.register(rateLimitPlugin);
|
||||
|
||||
// Routes
|
||||
await app.register(recentErrorsPublicRoutes);
|
||||
await app.register(errorMonitoringMutationsRoutes);
|
||||
await app.register(adminAuthRoutes);
|
||||
await app.register(adminStatsRoutes);
|
||||
await app.register(adminIncidentsRoutes);
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import type { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import {
|
||||
authorizeReadQuery,
|
||||
resolveMutationSecret,
|
||||
authorizeMutation,
|
||||
} from './errorMonitoringAuth.js';
|
||||
|
||||
function mockReply(): FastifyReply & { lastCode: () => number | undefined; lastBody: () => unknown } {
|
||||
let code: number | undefined;
|
||||
let body: unknown;
|
||||
const reply = {
|
||||
code(c: number) {
|
||||
code = c;
|
||||
return reply;
|
||||
},
|
||||
send(b: unknown) {
|
||||
body = b;
|
||||
return reply;
|
||||
},
|
||||
lastCode: () => code,
|
||||
lastBody: () => body,
|
||||
};
|
||||
return reply as FastifyReply & { lastCode: () => number | undefined; lastBody: () => unknown };
|
||||
}
|
||||
|
||||
describe('authorizeReadQuery', () => {
|
||||
const prev = { ...process.env };
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...prev };
|
||||
});
|
||||
|
||||
it('returns 503 when no server secrets configured', () => {
|
||||
delete process.env.ERROR_RESOLVE_API_KEY;
|
||||
delete process.env.ERROR_REPORTING_API_KEY;
|
||||
delete process.env.DEBUG_VIEW_ERRORS_KEY;
|
||||
const request = { query: {} } as FastifyRequest;
|
||||
const reply = mockReply();
|
||||
const ok = authorizeReadQuery(request, reply);
|
||||
expect(ok).toBe(false);
|
||||
expect(reply.lastCode()).toBe(503);
|
||||
});
|
||||
|
||||
it('allows api_key when it matches ERROR_RESOLVE_API_KEY', () => {
|
||||
process.env.ERROR_RESOLVE_API_KEY = 'k1';
|
||||
delete process.env.DEBUG_VIEW_ERRORS_KEY;
|
||||
const request = { query: { api_key: 'k1' } } as unknown as FastifyRequest;
|
||||
const reply = mockReply();
|
||||
expect(authorizeReadQuery(request, reply)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns 401 when key wrong', () => {
|
||||
process.env.ERROR_RESOLVE_API_KEY = 'k1';
|
||||
const request = { query: { api_key: 'nope' } } as unknown as FastifyRequest;
|
||||
const reply = mockReply();
|
||||
expect(authorizeReadQuery(request, reply)).toBe(false);
|
||||
expect(reply.lastCode()).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('authorizeMutation', () => {
|
||||
const prev = { ...process.env };
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...prev };
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('ERROR_RESOLVE_API_KEY', 'resolve-secret');
|
||||
});
|
||||
|
||||
it('allows matching api_key in body', async () => {
|
||||
const request = {
|
||||
query: {},
|
||||
cookies: {},
|
||||
headers: {},
|
||||
body: { api_key: 'resolve-secret' },
|
||||
jwtVerify: vi.fn(),
|
||||
} as unknown as FastifyRequest;
|
||||
const reply = mockReply();
|
||||
const auth = await authorizeMutation(request, reply, { api_key: 'resolve-secret' }, 'errors:triage');
|
||||
expect(auth).toEqual({ via: 'api_key', session: null });
|
||||
});
|
||||
|
||||
it('returns 401 when key wrong and no session', async () => {
|
||||
const request = {
|
||||
query: {},
|
||||
cookies: {},
|
||||
headers: {},
|
||||
body: { api_key: 'bad' },
|
||||
jwtVerify: vi.fn(),
|
||||
} as unknown as FastifyRequest;
|
||||
const reply = mockReply();
|
||||
const auth = await authorizeMutation(request, reply, { api_key: 'bad' }, 'errors:triage');
|
||||
expect(auth).toBeNull();
|
||||
expect(reply.lastCode()).toBe(401);
|
||||
});
|
||||
|
||||
it('resolveMutationSecret reads env', () => {
|
||||
expect(resolveMutationSecret()).toBe('resolve-secret');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* Shared auth for CRM-shaped public error-monitoring routes on the hub.
|
||||
* Read: api_key / view_errors query params.
|
||||
* Mutations: ERROR_RESOLVE_API_KEY (or ERROR_REPORTING_API_KEY) via body or
|
||||
* X-Error-Resolve-Key, or admin session (JWT cookie) with RBAC permission.
|
||||
*/
|
||||
|
||||
import type { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { safeEqual } from '../plugins/auth.js';
|
||||
import { can, type JwtPayload, type Permission } from '../types/auth.js';
|
||||
|
||||
const ACCESS_COOKIE = '__Host-access';
|
||||
|
||||
export function resolveReadSecrets(): { 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 };
|
||||
}
|
||||
|
||||
export function resolveMutationSecret(): string {
|
||||
const k = (process.env.ERROR_RESOLVE_API_KEY ?? process.env.ERROR_REPORTING_API_KEY ?? '').trim();
|
||||
return k;
|
||||
}
|
||||
|
||||
export function authorizeReadQuery(request: FastifyRequest, reply: FastifyReply): boolean {
|
||||
const { apiKey, viewKey } = resolveReadSecrets();
|
||||
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 sentResolveKeyFromRequest(
|
||||
request: FastifyRequest,
|
||||
body: Record<string, unknown>,
|
||||
): string {
|
||||
const fromBody = body.api_key;
|
||||
const header = request.headers['x-error-resolve-key'];
|
||||
const h = Array.isArray(header) ? header[0] : header;
|
||||
const fromHeader = typeof h === 'string' ? h : '';
|
||||
const b = typeof fromBody === 'string' ? fromBody : '';
|
||||
return (b || fromHeader).trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* CRM parity: if a resolve key is configured, caller must send a matching key
|
||||
* OR present a valid admin session with `permission`. If no resolve key is set,
|
||||
* only session + permission is accepted (token-only automation disabled).
|
||||
*/
|
||||
export type MutationAuth =
|
||||
| { via: 'api_key'; session: null }
|
||||
| { via: 'session'; session: { email: string; userId: string } };
|
||||
|
||||
export async function authorizeMutation(
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
body: Record<string, unknown>,
|
||||
permission: Permission,
|
||||
): Promise<MutationAuth | null> {
|
||||
const resolveKey = resolveMutationSecret();
|
||||
const sent = sentResolveKeyFromRequest(request, body);
|
||||
|
||||
if (resolveKey && sent && safeEqual(sent, resolveKey)) {
|
||||
return { via: 'api_key', session: null };
|
||||
}
|
||||
|
||||
const session = await trySessionWithPermission(request, permission);
|
||||
if (session) {
|
||||
return { via: 'session', session };
|
||||
}
|
||||
|
||||
if (!resolveKey) {
|
||||
reply.code(401).send({
|
||||
success: false,
|
||||
message: 'Unauthorized (session or ERROR_RESOLVE_API_KEY required)',
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
reply.code(401).send({
|
||||
success: false,
|
||||
message: 'Unauthorized',
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
async function trySessionWithPermission(
|
||||
request: FastifyRequest,
|
||||
permission: Permission,
|
||||
): Promise<{ email: string; userId: string } | null> {
|
||||
const token = request.cookies[ACCESS_COOKIE];
|
||||
if (!token) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const payload = await request.jwtVerify<JwtPayload>({ onlyCookie: false });
|
||||
if (!can(payload.role, permission)) {
|
||||
return null;
|
||||
}
|
||||
return { email: payload.email, userId: payload.sub };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function changedByRef(auth: MutationAuth): { type: 'api_key' | 'user'; ref: string } {
|
||||
if (auth.via === 'api_key') {
|
||||
return { type: 'api_key', ref: 'resolve_api' };
|
||||
}
|
||||
const email = auth.session.email || 'unknown';
|
||||
const ref = email.length > 128 ? email.slice(0, 125) + '...' : email;
|
||||
return { type: 'user', ref };
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
/**
|
||||
* CRM-shaped operational mutations for the hub (same paths as CRM module).
|
||||
* POST /api/error-monitoring/resolve
|
||||
* POST /api/error-monitoring/bulk-resolve
|
||||
* POST /api/error-monitoring/purge-resolved
|
||||
*/
|
||||
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import type { ResultSetHeader, RowDataPacket } from 'mysql2';
|
||||
import {
|
||||
authorizeMutation,
|
||||
changedByRef,
|
||||
type MutationAuth,
|
||||
} from '../../lib/errorMonitoringAuth.js';
|
||||
|
||||
function parseJsonBody(raw: unknown): Record<string, unknown> {
|
||||
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
|
||||
return {};
|
||||
}
|
||||
return raw as Record<string, unknown>;
|
||||
}
|
||||
|
||||
async function lookupIncidentForUniqueId(
|
||||
db: FastifyInstance['db'],
|
||||
uniqueId: string,
|
||||
): Promise<{ incidentId: string; projectId: string; currentState: string } | null> {
|
||||
const [oRows] = await db.execute<RowDataPacket[]>(
|
||||
`SELECT CAST(i.id AS CHAR) AS incident_id,
|
||||
CAST(i.project_id AS CHAR) AS project_id,
|
||||
i.current_state AS current_state
|
||||
FROM er_incident_occurrences o
|
||||
INNER JOIN er_incidents i ON i.id = o.incident_id
|
||||
WHERE o.id = ?
|
||||
LIMIT 1`,
|
||||
[uniqueId],
|
||||
);
|
||||
const o = oRows[0] as Record<string, unknown> | undefined;
|
||||
if (o) {
|
||||
return {
|
||||
incidentId: String(o.incident_id),
|
||||
projectId: String(o.project_id),
|
||||
currentState: String(o.current_state),
|
||||
};
|
||||
}
|
||||
|
||||
const [iRows] = await db.execute<RowDataPacket[]>(
|
||||
`SELECT CAST(id AS CHAR) AS incident_id,
|
||||
CAST(project_id AS CHAR) AS project_id,
|
||||
current_state AS current_state
|
||||
FROM er_incidents
|
||||
WHERE id = ?
|
||||
LIMIT 1`,
|
||||
[uniqueId],
|
||||
);
|
||||
const ir = iRows[0] as Record<string, unknown> | undefined;
|
||||
if (!ir) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
incidentId: String(ir.incident_id),
|
||||
projectId: String(ir.project_id),
|
||||
currentState: String(ir.current_state),
|
||||
};
|
||||
}
|
||||
|
||||
async function markIncidentResolved(
|
||||
db: FastifyInstance['db'],
|
||||
row: { incidentId: string; projectId: string; currentState: string },
|
||||
changeNote: string,
|
||||
auth: MutationAuth,
|
||||
): Promise<boolean> {
|
||||
if (!['open', 'investigating'].includes(row.currentState)) {
|
||||
return false;
|
||||
}
|
||||
const { type, ref } = changedByRef(auth);
|
||||
const conn = await db.getConnection();
|
||||
try {
|
||||
await conn.beginTransaction();
|
||||
const [upd] = await conn.execute<ResultSetHeader>(
|
||||
`UPDATE er_incidents
|
||||
SET current_state = 'resolved', updated_at = CURRENT_TIMESTAMP(6)
|
||||
WHERE id = ? AND current_state IN ('open','investigating')`,
|
||||
[row.incidentId],
|
||||
);
|
||||
if (upd.affectedRows === 0) {
|
||||
await conn.rollback();
|
||||
return false;
|
||||
}
|
||||
await conn.execute(
|
||||
`INSERT INTO er_incident_state_history
|
||||
(incident_id, project_id, from_state, to_state, changed_by_type, changed_by_ref, change_note)
|
||||
VALUES (?, ?, ?, 'resolved', ?, ?, ?)`,
|
||||
[row.incidentId, row.projectId, row.currentState, type, ref, changeNote || null],
|
||||
);
|
||||
await conn.commit();
|
||||
return true;
|
||||
} catch (e) {
|
||||
await conn.rollback();
|
||||
throw e;
|
||||
} finally {
|
||||
conn.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function handleResolve(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
const db = request.server.db;
|
||||
const body = parseJsonBody(request.body);
|
||||
const auth = await authorizeMutation(request, reply, body, 'errors:triage');
|
||||
if (!auth) {
|
||||
return;
|
||||
}
|
||||
|
||||
const uniqueId = typeof body.unique_id === 'string' ? body.unique_id.trim() : '';
|
||||
if (!uniqueId || !/^\d+$/.test(uniqueId)) {
|
||||
return void reply.code(400).send({ success: false, message: 'Unique ID é obrigatório' });
|
||||
}
|
||||
|
||||
let resolutionNotes =
|
||||
typeof body.resolution_notes === 'string' ? body.resolution_notes.trim() : '';
|
||||
if (resolutionNotes === '') {
|
||||
resolutionNotes = 'Marked as resolved via API';
|
||||
}
|
||||
const assignedTo = typeof body.assigned_to === 'string' ? body.assigned_to.trim() : '';
|
||||
const changeNote =
|
||||
assignedTo !== '' ? `${resolutionNotes} (assigned_to: ${assignedTo})` : resolutionNotes;
|
||||
|
||||
const row = await lookupIncidentForUniqueId(db, uniqueId);
|
||||
if (!row) {
|
||||
return void reply.code(404).send({ success: false, message: 'Erro não encontrado' });
|
||||
}
|
||||
|
||||
const ok = await markIncidentResolved(db, row, changeNote, auth);
|
||||
if (!ok) {
|
||||
return void reply.code(404).send({
|
||||
success: false,
|
||||
message: 'Incidente já resolvido ou estado inválido.',
|
||||
});
|
||||
}
|
||||
|
||||
return void reply.send({
|
||||
success: true,
|
||||
message: 'Erro marcado como resolvido',
|
||||
data: { unique_id: uniqueId, resolution_notes: resolutionNotes },
|
||||
});
|
||||
}
|
||||
|
||||
async function handleBulkResolve(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
const db = request.server.db;
|
||||
const body = parseJsonBody(request.body);
|
||||
const auth = await authorizeMutation(request, reply, body, 'errors:triage');
|
||||
if (!auth) {
|
||||
return;
|
||||
}
|
||||
|
||||
let resolutionNotes =
|
||||
typeof body.resolution_notes === 'string' ? body.resolution_notes.trim() : '';
|
||||
if (resolutionNotes === '') {
|
||||
resolutionNotes = 'Bulk resolved via API';
|
||||
}
|
||||
const assignedTo = typeof body.assigned_to === 'string' ? body.assigned_to.trim() : '';
|
||||
const changeNoteBase =
|
||||
assignedTo !== '' ? `${resolutionNotes} (assigned_to: ${assignedTo})` : resolutionNotes;
|
||||
|
||||
const { type, ref } = changedByRef(auth);
|
||||
|
||||
const rawIds = body.unique_ids;
|
||||
if (Array.isArray(rawIds) && rawIds.length > 0) {
|
||||
const uniqueIds = rawIds
|
||||
.filter((x): x is string => typeof x === 'string')
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => /^\d+$/.test(s));
|
||||
const capped = uniqueIds.slice(0, 1000);
|
||||
if (capped.length === 0) {
|
||||
return void reply.code(400).send({
|
||||
success: false,
|
||||
message: 'unique_ids must be non-empty array of numeric strings',
|
||||
});
|
||||
}
|
||||
|
||||
const seen = new Set<string>();
|
||||
const targets: { incidentId: string; projectId: string; currentState: string }[] = [];
|
||||
for (const uid of capped) {
|
||||
const row = await lookupIncidentForUniqueId(db, uid);
|
||||
if (row && ['open', 'investigating'].includes(row.currentState) && !seen.has(row.incidentId)) {
|
||||
seen.add(row.incidentId);
|
||||
targets.push(row);
|
||||
}
|
||||
}
|
||||
|
||||
let resolved = 0;
|
||||
const conn = await db.getConnection();
|
||||
try {
|
||||
await conn.beginTransaction();
|
||||
for (const row of targets) {
|
||||
const [upd] = await conn.execute<ResultSetHeader>(
|
||||
`UPDATE er_incidents
|
||||
SET current_state = 'resolved', updated_at = CURRENT_TIMESTAMP(6)
|
||||
WHERE id = ? AND current_state IN ('open','investigating')`,
|
||||
[row.incidentId],
|
||||
);
|
||||
if (upd.affectedRows === 0) {
|
||||
continue;
|
||||
}
|
||||
await conn.execute(
|
||||
`INSERT INTO er_incident_state_history
|
||||
(incident_id, project_id, from_state, to_state, changed_by_type, changed_by_ref, change_note)
|
||||
VALUES (?, ?, ?, 'resolved', ?, ?, ?)`,
|
||||
[row.incidentId, row.projectId, row.currentState, type, ref, changeNoteBase || null],
|
||||
);
|
||||
resolved += upd.affectedRows;
|
||||
}
|
||||
await conn.commit();
|
||||
} catch (e) {
|
||||
await conn.rollback();
|
||||
throw e;
|
||||
} finally {
|
||||
conn.release();
|
||||
}
|
||||
|
||||
return void reply.send({
|
||||
success: true,
|
||||
message: 'Bulk resolve by unique_ids completed',
|
||||
data: { resolved, by: 'unique_ids' as const },
|
||||
});
|
||||
}
|
||||
|
||||
const patternInput = body.message_pattern;
|
||||
if (patternInput === null || patternInput === '') {
|
||||
return void reply.code(400).send({
|
||||
success: false,
|
||||
message: 'message_pattern or unique_ids is required',
|
||||
});
|
||||
}
|
||||
const patternsIn = Array.isArray(patternInput) ? patternInput : [patternInput];
|
||||
const likePatterns: string[] = [];
|
||||
for (const p of patternsIn) {
|
||||
const s = typeof p === 'string' ? p.trim() : '';
|
||||
if (s !== '') {
|
||||
likePatterns.push(`%${s}%`);
|
||||
}
|
||||
}
|
||||
const patterns = likePatterns.slice(0, 20);
|
||||
if (patterns.length === 0) {
|
||||
return void reply.code(400).send({
|
||||
success: false,
|
||||
message: 'message_pattern must be non-empty string or array of strings',
|
||||
});
|
||||
}
|
||||
|
||||
const conds = patterns.map(() => 'o.message LIKE ?').join(' OR ');
|
||||
const sql = `
|
||||
SELECT DISTINCT CAST(i.id AS CHAR) AS incident_id,
|
||||
CAST(i.project_id AS CHAR) AS project_id,
|
||||
i.current_state AS current_state
|
||||
FROM er_incidents i
|
||||
INNER JOIN er_incident_occurrences o ON o.incident_id = i.id
|
||||
WHERE i.current_state IN ('open','investigating')
|
||||
AND (${conds})
|
||||
`;
|
||||
const [matchRows] = await db.execute<RowDataPacket[]>(sql, patterns);
|
||||
const targets = (matchRows as Record<string, unknown>[]).map((r) => ({
|
||||
incidentId: String(r.incident_id),
|
||||
projectId: String(r.project_id),
|
||||
currentState: String(r.current_state),
|
||||
}));
|
||||
|
||||
let resolved = 0;
|
||||
const conn = await db.getConnection();
|
||||
try {
|
||||
await conn.beginTransaction();
|
||||
for (const row of targets) {
|
||||
const [upd] = await conn.execute<ResultSetHeader>(
|
||||
`UPDATE er_incidents
|
||||
SET current_state = 'resolved', updated_at = CURRENT_TIMESTAMP(6)
|
||||
WHERE id = ? AND current_state IN ('open','investigating')`,
|
||||
[row.incidentId],
|
||||
);
|
||||
if (upd.affectedRows === 0) {
|
||||
continue;
|
||||
}
|
||||
await conn.execute(
|
||||
`INSERT INTO er_incident_state_history
|
||||
(incident_id, project_id, from_state, to_state, changed_by_type, changed_by_ref, change_note)
|
||||
VALUES (?, ?, ?, 'resolved', ?, ?, ?)`,
|
||||
[row.incidentId, row.projectId, row.currentState, type, ref, changeNoteBase || null],
|
||||
);
|
||||
resolved += upd.affectedRows;
|
||||
}
|
||||
await conn.commit();
|
||||
} catch (e) {
|
||||
await conn.rollback();
|
||||
throw e;
|
||||
} finally {
|
||||
conn.release();
|
||||
}
|
||||
|
||||
return void reply.send({
|
||||
success: true,
|
||||
message: 'Bulk resolve by message pattern completed',
|
||||
data: { resolved, by: 'message_pattern' as const, patterns: likePatterns },
|
||||
});
|
||||
}
|
||||
|
||||
async function handlePurgeResolved(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
const db = request.server.db;
|
||||
const body = parseJsonBody(request.body);
|
||||
const auth = await authorizeMutation(request, reply, body, 'errors:delete');
|
||||
if (!auth) {
|
||||
return;
|
||||
}
|
||||
|
||||
const dryRun = Boolean(body.dry_run);
|
||||
|
||||
const [countRows] = await db.execute<RowDataPacket[]>(
|
||||
`SELECT COUNT(*) AS c FROM er_incidents WHERE current_state = 'resolved'`,
|
||||
);
|
||||
const count = Number((countRows[0] as { c?: number }).c ?? 0);
|
||||
|
||||
if (dryRun) {
|
||||
return void reply.send({
|
||||
success: true,
|
||||
message: 'Dry run',
|
||||
data: { dry_run: true, would_delete: count },
|
||||
});
|
||||
}
|
||||
|
||||
if (count === 0) {
|
||||
return void reply.send({
|
||||
success: true,
|
||||
message: 'Nenhum incidente resolvido para apagar.',
|
||||
data: { deleted: 0 },
|
||||
});
|
||||
}
|
||||
|
||||
const [del] = await db.execute<ResultSetHeader>(
|
||||
`DELETE FROM er_incidents WHERE current_state = 'resolved'`,
|
||||
);
|
||||
|
||||
return void reply.send({
|
||||
success: true,
|
||||
message: `Apagados ${del.affectedRows} incidentes resolvidos`,
|
||||
data: { deleted: del.affectedRows },
|
||||
});
|
||||
}
|
||||
|
||||
export default async function errorMonitoringMutationsRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.post('/api/error-monitoring/resolve', handleResolve);
|
||||
app.post('/api/error-monitoring/bulk-resolve', handleBulkResolve);
|
||||
app.post('/api/error-monitoring/purge-resolved', handlePurgeResolved);
|
||||
}
|
||||
@@ -1,8 +1,15 @@
|
||||
/**
|
||||
* Paperclip / CRM-compatible read-only listing for open incidents.
|
||||
* Paths (same handler, Paperclip default query is the CRM-shaped one):
|
||||
* GET /api/error-monitoring/recent-errors?limit=&api_key=|view_errors=
|
||||
* GET /v1/paperclip/recent-errors?limit=&api_key=|view_errors=
|
||||
* Paperclip / CRM-compatible listing for incidents (open by default; filters optional).
|
||||
* Paths (same handler):
|
||||
* GET /api/error-monitoring/recent-errors?limit=&offset=&api_key=|view_errors=
|
||||
* GET /v1/paperclip/recent-errors?...
|
||||
*
|
||||
* Optional query filters (hub extension, backward compatible when omitted):
|
||||
* status — comma-separated: open,investigating,resolved,ignored (default: open,investigating)
|
||||
* severity — critical|high|medium|low|info
|
||||
* project_slug — project slug (lowercase)
|
||||
* q — search title, message, fingerprint (LIKE)
|
||||
* order — occurred_at_desc (default) | occurred_at_asc
|
||||
*
|
||||
* 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.
|
||||
@@ -10,42 +17,10 @@
|
||||
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import type { RowDataPacket } from 'mysql2';
|
||||
import { safeEqual } from '../../plugins/auth.js';
|
||||
import { authorizeReadQuery } from '../../lib/errorMonitoringAuth.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;
|
||||
}
|
||||
const INCIDENT_STATES = ['open', 'investigating', 'resolved', 'ignored'] as const;
|
||||
const SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'] as const;
|
||||
|
||||
function parseJsonObject(raw: string | null): Record<string, unknown> | null {
|
||||
if (raw == null || raw === '') {
|
||||
@@ -71,14 +46,40 @@ function extractFileLine(ctx: Record<string, unknown> | null): { file_path: stri
|
||||
return { file_path, line_number };
|
||||
}
|
||||
|
||||
function parseStatusList(raw: string | undefined): string[] | null {
|
||||
if (raw == null || raw.trim() === '') {
|
||||
return ['open', 'investigating'];
|
||||
}
|
||||
const parts = raw
|
||||
.split(',')
|
||||
.map((s) => s.trim().toLowerCase())
|
||||
.filter(Boolean);
|
||||
const allowed = new Set(INCIDENT_STATES as readonly string[]);
|
||||
for (const p of parts) {
|
||||
if (!allowed.has(p)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return parts.length > 0 ? parts : ['open', 'investigating'];
|
||||
}
|
||||
|
||||
async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
const db = request.server.db;
|
||||
|
||||
if (!authorizeQuery(request, reply)) {
|
||||
if (!authorizeReadQuery(request, reply)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const q = request.query as { limit?: string };
|
||||
const q = request.query as {
|
||||
limit?: string;
|
||||
offset?: string;
|
||||
status?: string;
|
||||
severity?: string;
|
||||
project_slug?: string;
|
||||
q?: string;
|
||||
order?: string;
|
||||
};
|
||||
|
||||
let limit = 999999;
|
||||
if (q.limit != null && q.limit !== '') {
|
||||
const n = parseInt(String(q.limit), 10);
|
||||
@@ -88,6 +89,59 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
|
||||
limit = Math.min(n, 999999);
|
||||
}
|
||||
|
||||
let offset = 0;
|
||||
if (q.offset != null && q.offset !== '') {
|
||||
const o = parseInt(String(q.offset), 10);
|
||||
if (!Number.isFinite(o) || o < 0) {
|
||||
return void reply.code(400).send({ success: false, message: 'Invalid offset' });
|
||||
}
|
||||
offset = Math.min(o, 10_000_000);
|
||||
}
|
||||
|
||||
const states = parseStatusList(q.status);
|
||||
if (!states) {
|
||||
return void reply.code(400).send({
|
||||
success: false,
|
||||
message: `Invalid status (use comma-separated: ${INCIDENT_STATES.join(',')})`,
|
||||
});
|
||||
}
|
||||
|
||||
if (q.severity != null && q.severity !== '') {
|
||||
const sev = q.severity.trim().toLowerCase();
|
||||
if (!(SEVERITIES as readonly string[]).includes(sev)) {
|
||||
return void reply.code(400).send({
|
||||
success: false,
|
||||
message: `Invalid severity (allowed: ${SEVERITIES.join(',')})`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const orderRaw = (q.order ?? 'occurred_at_desc').trim().toLowerCase();
|
||||
const orderSql =
|
||||
orderRaw === 'occurred_at_asc' ? 'r.occurred_at ASC, r.id ASC' : 'r.occurred_at DESC, r.id DESC';
|
||||
|
||||
const statePlaceholders = states.map(() => '?').join(', ');
|
||||
const conditions: string[] = [`i.current_state IN (${statePlaceholders})`];
|
||||
const params: Array<string | number> = [...states];
|
||||
|
||||
if (q.severity != null && q.severity !== '') {
|
||||
conditions.push('i.severity = ?');
|
||||
params.push(q.severity.trim().toLowerCase());
|
||||
}
|
||||
|
||||
if (q.project_slug != null && q.project_slug.trim() !== '') {
|
||||
conditions.push('p.slug = ?');
|
||||
params.push(q.project_slug.trim().toLowerCase());
|
||||
}
|
||||
|
||||
if (q.q != null && q.q.trim() !== '') {
|
||||
const term = `%${q.q.trim()}%`;
|
||||
conditions.push('(i.title LIKE ? OR o.message LIKE ? OR i.fingerprint LIKE ?)');
|
||||
params.push(term, term, term);
|
||||
}
|
||||
|
||||
const whereClause = conditions.join(' AND ');
|
||||
|
||||
const sql = `
|
||||
WITH ranked AS (
|
||||
SELECT o.id,
|
||||
@@ -97,15 +151,17 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
|
||||
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
|
||||
ROW_NUMBER() OVER (PARTITION BY o.incident_id ORDER BY o.occurred_at DESC, o.id 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')
|
||||
INNER JOIN er_projects p ON p.id = i.project_id
|
||||
WHERE ${whereClause}
|
||||
)
|
||||
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,
|
||||
i.current_state AS incident_state,
|
||||
r.message,
|
||||
r.stack_trace,
|
||||
r.context_json,
|
||||
@@ -115,20 +171,23 @@ async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply):
|
||||
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 ?
|
||||
ORDER BY ${orderSql}
|
||||
LIMIT ? OFFSET ?
|
||||
`;
|
||||
|
||||
const [rows] = await db.execute<RowDataPacket[]>(sql, [limit]);
|
||||
params.push(limit, offset);
|
||||
|
||||
const [rows] = await db.execute<RowDataPacket[]>(sql, params);
|
||||
|
||||
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';
|
||||
const st = String(row.incident_state ?? 'open').toLowerCase();
|
||||
|
||||
return {
|
||||
status: 'open',
|
||||
status: st === 'resolved' ? 'resolved' : st === 'ignored' ? 'ignored' : 'open',
|
||||
message: String(row.message ?? ''),
|
||||
error_message: String(row.message ?? ''),
|
||||
stack_trace: row.stack_trace != null ? String(row.stack_trace) : '',
|
||||
|
||||
Reference in new issue
Block a user