feat(errors): platform-wide request ids + error codes + admin inspector
End-to-end error-handling overhaul. A user hitting any failure now sees
a plain-text message + stable error code + reference id. A super admin
can paste the id into /admin/errors/<id> for the full request shape,
sanitized body, error stack, and a heuristic likely-cause hint.
REQUEST CONTEXT (AsyncLocalStorage)
- src/lib/request-context.ts mints a per-request frame carrying
requestId + portId + userId + method + path + start timestamp.
- withAuth wraps every authenticated handler in runWithRequestContext
and accepts an upstream X-Request-Id header (validated shape) or
generates a fresh UUID. The id ALWAYS leaves on the X-Request-Id
response header, including early-return 401/403/4xx paths.
- Pino logger reads from the same context via mixin — every log
line emitted during the request automatically carries the ids
with no per-call threading.
ERROR CODE REGISTRY
- src/lib/error-codes.ts defines stable DOMAIN_REASON codes with
HTTP status + plain-text user-facing message (no jargon, written
for the rep on the phone with a customer).
- New CodedError class wraps a registered code + optional
internalMessage (admin-only — never sent to client).
- Existing AppError subclasses got plain-text default rewrites so
legacy throw sites improve immediately without migration.
- High-impact services migrated to specific codes:
expenses (RECEIPT_REQUIRED, INVOICE_LINKED), interest-berths
(CROSS_PORT_LINK_REJECTED), berth-pdf (PDF_MAGIC_BYTE / PDF_EMPTY /
PDF_TOO_LARGE / VERSION_ALREADY_CURRENT), recommender
(INTEREST_PORT_MISMATCH).
ERROR ENVELOPE
- errorResponse always sets X-Request-Id header + requestId field.
- 5xx responses include a "Quote error ID …" friendly line.
- 4xx kept clean (validation, permission, not-found don't pollute
the inspector — they're already in audit log).
PERSISTENCE (error_events table, migration 0040)
- One row per 5xx, keyed on requestId, with method/path/status/error
name+message/stack head (4KB cap)/sanitized body excerpt (1KB cap;
password/token/secret/etc keys redacted)/duration/IP/UA/metadata.
- captureErrorEvent extracts Postgres SQLSTATE/severity/cause.code
so the classifier can recognize FK / unique / NOT NULL / schema-
drift violations.
- Failure to persist is logged-not-thrown.
LIKELY-CULPRIT CLASSIFIER (src/lib/error-classifier.ts)
- 4-pass heuristic (first match wins):
1. Postgres SQLSTATE → human reason (23503 FK, 23505 unique,
42703 schema drift, 53300 connection limit, …)
2. Error class name (AbortError, TimeoutError, FetchError,
ZodError)
3. Stack-path patterns (/lib/storage/, /lib/email/, documenso,
openai|claude, /queue/workers/)
4. Free-text message keywords (econnrefused, rate limit, timeout,
unauthorized|invalid api key)
- Returns { label, hint, subsystem } for the inspector badge.
CLIENT SIDE
- apiFetch throws structured ApiError with message + code + requestId
+ details + retryAfter.
- toastError() helper renders the standard 3-line toast:
plain message / Error code: X / Reference ID: Y [Copy ID].
ADMIN INSPECTOR
- /<port>/admin/errors lists captured 5xx with status badge + path +
likely-culprit badge + truncated message + reference id. Filter by
status code; auto-refresh via TanStack Query.
- /<port>/admin/errors/<requestId> deep-dive: request shape, full
error name+message+stack, sanitized body excerpt, raw metadata,
registered-code lookup (so admin can compare to what user saw),
likely-culprit hint with subsystem tag.
- /<port>/admin/errors/codes is the in-app code reference page —
every registered code grouped by domain prefix, searchable, with
HTTP status + user message inline. Linked from inspector header
so admins can flip to it while triaging.
- Permission: admin.view_audit_log. Super admins see all ports;
regular admins port-scoped.
- system-monitoring dashboard now surfaces error_events alongside
permission_denied audit + queue failed jobs (RecentError gains
source: 'request' variant).
DOCS
- docs/error-handling.md walks through coded errors, plain-text
message guidelines, client toasting, admin inspector usage,
persistence rules, classifier internals, pruning, and the
legacy → CodedError migration path.
MIGRATION SAFETY
- Audit confirmed all 41 migrations (0000-0040) apply cleanly in
journal order against an empty DB. 0040 references ports(id)
which exists from 0000. 0035/0038 don't deadlock under sequential
psql -f. Removed redundant idx_ds_sent_by from 0038 (created in
0037).
Tests: 1168/1168 vitest passing. tsc clean.
- security-error-responses tests updated for plain-text messages
+ new optional response keys (code/requestId/message).
- berth-pdf-versions tests assert stable error codes via
toMatchObject({ code }) rather than message regex.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -101,7 +101,9 @@ describe('uploadBerthPdf', () => {
|
||||
fileName: 'spoof.pdf',
|
||||
uploadedBy: 'test-user',
|
||||
}),
|
||||
).rejects.toThrow(/magic-byte/);
|
||||
// Plain-text user message replaced "magic-byte" wording; assert the
|
||||
// stable error code instead so this test survives copy edits.
|
||||
).rejects.toMatchObject({ code: 'BERTHS_PDF_MAGIC_BYTE' });
|
||||
});
|
||||
|
||||
it('increments versionNumber on the second upload', async () => {
|
||||
@@ -296,9 +298,11 @@ describe('rollbackToVersion', () => {
|
||||
fileName: 'v1.pdf',
|
||||
uploadedBy: 'test',
|
||||
});
|
||||
await expect(rollbackToVersion(berth.id, v1.versionId, port.id)).rejects.toThrow(
|
||||
/already current/,
|
||||
);
|
||||
// Plain-text user message replaced "already current" wording; assert
|
||||
// the stable error code instead.
|
||||
await expect(rollbackToVersion(berth.id, v1.versionId, port.id)).rejects.toMatchObject({
|
||||
code: 'BERTHS_VERSION_ALREADY_CURRENT',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -321,11 +325,11 @@ describe('cross-port tenant guard', () => {
|
||||
// Port B caller passing port A's berth id must hit NotFoundError on
|
||||
// every entrypoint — including read-only listing, which previously
|
||||
// returned 15-min presigned download URLs to the foreign port's PDFs.
|
||||
await expect(listBerthPdfVersions(berthA.id, portB.id)).rejects.toThrow(/Berth/);
|
||||
await expect(rollbackToVersion(berthA.id, v1.versionId, portB.id)).rejects.toThrow(/Berth/);
|
||||
await expect(listBerthPdfVersions(berthA.id, portB.id)).rejects.toThrow(/berth/i);
|
||||
await expect(rollbackToVersion(berthA.id, v1.versionId, portB.id)).rejects.toThrow(/berth/i);
|
||||
await expect(
|
||||
applyParseResults(berthA.id, v1.versionId, { lengthFt: 99 }, portB.id),
|
||||
).rejects.toThrow(/Berth/);
|
||||
).rejects.toThrow(/berth/i);
|
||||
await expect(
|
||||
uploadBerthPdf({
|
||||
berthId: berthA.id,
|
||||
@@ -334,13 +338,13 @@ describe('cross-port tenant guard', () => {
|
||||
fileName: 'B-cross.pdf',
|
||||
uploadedBy: 'test',
|
||||
}),
|
||||
).rejects.toThrow(/Berth/);
|
||||
).rejects.toThrow(/berth/i);
|
||||
await expect(
|
||||
reconcilePdfWithBerth(
|
||||
berthA.id,
|
||||
{ engine: 'ocr', fields: {}, meanConfidence: 1, warnings: [] },
|
||||
portB.id,
|
||||
),
|
||||
).rejects.toThrow(/Berth/);
|
||||
).rejects.toThrow(/berth/i);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* Rule from SECURITY-GUIDELINES.md:
|
||||
* "Error responses must NEVER contain stack traces, SQL queries, or internal paths"
|
||||
*/
|
||||
import { beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// ── Mock next/server before importing the module under test ──────────────────
|
||||
// NextResponse is a Next.js runtime class unavailable in a plain Node environment.
|
||||
@@ -68,12 +68,13 @@ describe('Error response security — AppError subclasses', () => {
|
||||
expect(JSON.stringify(body)).not.toContain('node_modules');
|
||||
});
|
||||
|
||||
it('NotFoundError returns 404 with generic message, not entity internals', async () => {
|
||||
it('NotFoundError returns 404 with plain-text message, not entity internals', async () => {
|
||||
const error = new NotFoundError('Client');
|
||||
const response = errorResponse(error);
|
||||
expect(response.status).toBe(404);
|
||||
const body = await response.json();
|
||||
expect(body.error).toBe('Client not found');
|
||||
// Message is now plain-text user-facing (no jargon, lowercased entity).
|
||||
expect(body.error).toBe("We couldn't find that client. It may have been removed.");
|
||||
expect(body.code).toBe('NOT_FOUND');
|
||||
expect(JSON.stringify(body)).not.toContain('stack');
|
||||
});
|
||||
@@ -111,9 +112,7 @@ describe('Error response security — AppError subclasses', () => {
|
||||
|
||||
describe('Error response security — unknown / native errors', () => {
|
||||
it('native Error with SQL content returns generic 500', async () => {
|
||||
const error = new Error(
|
||||
"SELECT * FROM users WHERE id = 1; DROP TABLE users;--",
|
||||
);
|
||||
const error = new Error('SELECT * FROM users WHERE id = 1; DROP TABLE users;--');
|
||||
const response = errorResponse(error);
|
||||
expect(response.status).toBe(500);
|
||||
const body = await response.json();
|
||||
@@ -135,9 +134,7 @@ describe('Error response security — unknown / native errors', () => {
|
||||
});
|
||||
|
||||
it('native Error with node_modules path returns generic 500 without path', async () => {
|
||||
const error = new Error(
|
||||
'ENOENT: no such file at /app/node_modules/pg/lib/connection.js',
|
||||
);
|
||||
const error = new Error('ENOENT: no such file at /app/node_modules/pg/lib/connection.js');
|
||||
const response = errorResponse(error);
|
||||
expect(response.status).toBe(500);
|
||||
const body = await response.json();
|
||||
@@ -233,10 +230,17 @@ describe('Error response security — response shape invariants', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('500 response body has exactly the error key and nothing else', async () => {
|
||||
it('500 response body carries error + code (and requestId when in-flight)', async () => {
|
||||
const response = errorResponse(new Error('db connection refused'));
|
||||
const body = await response.json();
|
||||
expect(Object.keys(body)).toEqual(['error']);
|
||||
// Allowed keys for a 500 response. `code` is always present; `requestId`
|
||||
// and `message` only appear when an active request context is in scope.
|
||||
const allowed = new Set(['error', 'code', 'requestId', 'message']);
|
||||
for (const key of Object.keys(body)) {
|
||||
expect(allowed.has(key)).toBe(true);
|
||||
}
|
||||
expect(body.error).toBe('Internal server error');
|
||||
expect(body.code).toBe('INTERNAL');
|
||||
expect(body).not.toHaveProperty('stack');
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user