fix(audit-tier-2): error-surface hygiene — toastError + CodedError sweep

Two mechanical sweeps closing the audit's HIGH §16 + MED §11 findings:

* 38 client components / 56 toast.error sites converted to
  toastError(err) so the new admin error inspector becomes usable from
  user-reported issues — every failed inline-edit, save, send, archive,
  upload, etc. now carries the request-id + error-code (Copy ID action).
* 26 service files / 62 bare-Error throws converted to CodedError or
  the existing AppError subclasses.  Adds new error codes:
  DOCUMENSO_UPSTREAM_ERROR (502), DOCUMENSO_AUTH_FAILURE (502),
  DOCUMENSO_TIMEOUT (504), OCR_UPSTREAM_ERROR (502),
  IMAP_UPSTREAM_ERROR (502), UMAMI_UPSTREAM_ERROR (502),
  UMAMI_NOT_CONFIGURED (409), and INSERT_RETURNING_EMPTY (500) for
  post-insert returning-empty guards.
* Five vitest assertions updated to match the new user-facing wording
  (client-merge "already been merged", expense/interest "couldn't find
  that …", documenso "signing service didn't respond").

Test status: 1168/1168 vitest, tsc clean.

Refs: docs/audit-comprehensive-2026-05-05.md HIGH §16 (auditor-H Issue 1)
+ MED §11 (auditor-G Issue 1).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Matt Ciaccio
2026-05-05 20:18:05 +02:00
parent 6a609ecf94
commit fc7595faf8
69 changed files with 426 additions and 166 deletions

View File

@@ -207,6 +207,55 @@ export const ERROR_CODES = {
status: 403,
userMessage: 'This request was rejected by the security check.',
},
// ─── Upstream integrations ──────────────────────────────────────────
DOCUMENSO_UPSTREAM_ERROR: {
status: 502,
userMessage:
"The signing service didn't respond as expected. Please retry, and if it keeps happening, ping an admin.",
hint: 'Documenso returned a non-2xx; check Documenso health + auth.',
},
DOCUMENSO_AUTH_FAILURE: {
status: 502,
userMessage:
'The signing service rejected our request. An admin will need to refresh the API key.',
hint: 'Documenso 401/403 — API key likely revoked or rotated.',
},
DOCUMENSO_TIMEOUT: {
status: 504,
userMessage: 'The signing service is taking too long to respond. Please try again in a moment.',
},
OCR_UPSTREAM_ERROR: {
status: 502,
userMessage:
"The receipt scanner didn't respond as expected. Please retry, or fill the fields manually.",
},
IMAP_UPSTREAM_ERROR: {
status: 502,
userMessage:
"We couldn't fetch your inbox just now. Please retry, and check your IMAP credentials if it persists.",
},
UMAMI_UPSTREAM_ERROR: {
status: 502,
userMessage: "Analytics data isn't available right now. Please try again shortly.",
},
UMAMI_NOT_CONFIGURED: {
status: 409,
userMessage:
'Analytics has not been configured for this port. Ask an admin to set up the integration.',
},
// ─── Internal post-insert guards ────────────────────────────────────
// Surfaced as a generic "something went wrong" toast because the cause
// is always a programmer / DB-state issue (returning row absent after a
// successful insert, etc.) — the rep can't action it but support can,
// via the request-id lookup. Use only with `internalMessage`.
INSERT_RETURNING_EMPTY: {
status: 500,
userMessage:
'Something went wrong on our end. Please try again, and quote the error ID below if it keeps happening.',
hint: 'A db.insert(...).returning() came back empty — DB constraint or transaction-rollback bug.',
},
} as const satisfies Record<string, ErrorCodeEntry>;
export type ErrorCode = keyof typeof ERROR_CODES;

View File

@@ -15,6 +15,7 @@ import { and, eq, gte, sql } from 'drizzle-orm';
import { db } from '@/lib/db';
import { aiUsageLedger } from '@/lib/db/schema/ai-usage';
import { systemSettings } from '@/lib/db/schema/system';
import { ValidationError } from '@/lib/errors';
import { logger } from '@/lib/logger';
export type BudgetPeriod = 'day' | 'week' | 'month';
@@ -70,10 +71,10 @@ export async function setAiBudget(
period: input.period ?? existing.period,
};
if (next.softCapTokens < 0 || next.hardCapTokens < 0) {
throw new Error('Token caps must be non-negative');
throw new ValidationError('Token caps must be non-negative');
}
if (next.softCapTokens > next.hardCapTokens) {
throw new Error('softCapTokens cannot exceed hardCapTokens');
throw new ValidationError('softCapTokens cannot exceed hardCapTokens');
}
await db
.delete(systemSettings)

View File

@@ -22,6 +22,8 @@
import { PDFDocument } from 'pdf-lib';
import { ValidationError } from '@/lib/errors';
// ─── shared types ────────────────────────────────────────────────────────────
export type ParserEngine = 'acroform' | 'ocr' | 'ai';
@@ -445,7 +447,7 @@ export async function parseBerthPdf(
opts: ParseBerthPdfOptions = {},
): Promise<ParseResult> {
if (!isPdfMagic(buffer)) {
throw new Error('PDF magic-byte check failed: file does not begin with %PDF-');
throw new ValidationError('PDF magic-byte check failed: file does not begin with %PDF-');
}
const acro = await tryAcroForm(buffer);
if (acro && Object.keys(acro.fields).length > 0) return acro;

View File

@@ -15,7 +15,7 @@ import { and, asc, desc, eq, isNull } from 'drizzle-orm';
import { db } from '@/lib/db';
import { brochures, brochureVersions, ports } from '@/lib/db/schema';
import type { Brochure, BrochureVersion } from '@/lib/db/schema';
import { ForbiddenError, NotFoundError, ValidationError } from '@/lib/errors';
import { CodedError, ForbiddenError, NotFoundError, ValidationError } from '@/lib/errors';
import { getStorageBackend } from '@/lib/storage';
import { buildStoragePath } from '@/lib/minio';
import { logger } from '@/lib/logger';
@@ -140,7 +140,10 @@ export async function createBrochure(input: CreateBrochureInput): Promise<Brochu
createdBy: input.createdBy,
})
.returning();
if (!row) throw new Error('Failed to create brochure');
if (!row)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to create brochure',
});
return row;
});
}
@@ -177,7 +180,10 @@ export async function updateBrochure(
.set(updates)
.where(eq(brochures.id, brochureId))
.returning();
if (!row) throw new Error('Failed to update brochure');
if (!row)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to update brochure',
});
return row;
});
}
@@ -276,7 +282,10 @@ export async function registerBrochureVersion(
uploadedBy: input.uploadedBy,
})
.returning();
if (!row) throw new Error('Failed to record brochure version');
if (!row)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to record brochure version',
});
return row;
}

View File

@@ -33,6 +33,7 @@ import {
import { interests } from '@/lib/db/schema/interests';
import { berthReservations } from '@/lib/db/schema/reservations';
import { auditLogs } from '@/lib/db/schema/system';
import { ConflictError, NotFoundError, ValidationError } from '@/lib/errors';
// ─── Public API ─────────────────────────────────────────────────────────────
@@ -81,7 +82,7 @@ export interface MergeResult {
*/
export async function mergeClients(opts: MergeOptions): Promise<MergeResult> {
if (opts.winnerId === opts.loserId) {
throw new Error('Cannot merge a client into itself');
throw new ValidationError('Cannot merge a client into itself');
}
return await db.transaction(async (tx) => {
@@ -99,16 +100,16 @@ export async function mergeClients(opts: MergeOptions): Promise<MergeResult> {
.where(eq(clients.id, opts.loserId))
.for('update');
if (!winnerRow) throw new Error(`Winner client ${opts.winnerId} not found`);
if (!loserRow) throw new Error(`Loser client ${opts.loserId} not found`);
if (!winnerRow) throw new NotFoundError('client');
if (!loserRow) throw new NotFoundError('client');
if (winnerRow.portId !== loserRow.portId) {
throw new Error('Cannot merge clients across different ports');
throw new ValidationError('Cannot merge clients across different ports');
}
if (loserRow.mergedIntoClientId) {
throw new Error(`Loser ${opts.loserId} already merged into ${loserRow.mergedIntoClientId}`);
throw new ConflictError('That client has already been merged into another record.');
}
if (winnerRow.archivedAt) {
throw new Error('Cannot merge into an archived client');
throw new ConflictError('Cannot merge into an archived client');
}
// ── Snapshot the loser's full state before any mutation. Used by

View File

@@ -9,7 +9,7 @@ import { userProfiles } from '@/lib/db/schema/users';
import { env } from '@/lib/env';
import { sendEmail } from '@/lib/email';
import { crmInviteEmail } from '@/lib/email/templates/crm-invite';
import { ConflictError, NotFoundError, ValidationError } from '@/lib/errors';
import { CodedError, ConflictError, NotFoundError, ValidationError } from '@/lib/errors';
import { hashToken, mintToken } from '@/lib/portal/passwords';
const INVITE_TTL_HOURS = 72;
@@ -61,7 +61,10 @@ export async function createCrmInvite(args: {
})
.returning({ id: crmUserInvites.id });
if (!row) throw new Error('Failed to create CRM invite');
if (!row)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to create CRM invite',
});
const link = `${env.APP_URL}/set-password?token=${raw}`;
const { subject, html, text } = crmInviteEmail({

View File

@@ -1,6 +1,7 @@
import { db } from '@/lib/db';
import { currencyRates } from '@/lib/db/schema/system';
import { eq, and } from 'drizzle-orm';
import { CodedError } from '@/lib/errors';
import { logger } from '@/lib/logger';
import { fetchWithTimeout } from '@/lib/fetch-with-timeout';
@@ -25,7 +26,10 @@ export async function convert(
export async function refreshRates(): Promise<void> {
try {
const res = await fetchWithTimeout('https://api.frankfurter.dev/v1/latest?base=USD');
if (!res.ok) throw new Error(`Frankfurter API error: ${res.status}`);
if (!res.ok)
throw new CodedError('INTERNAL', {
internalMessage: `Frankfurter API error: ${res.status}`,
});
const data = await res.json();
const rates = data.rates as Record<string, number>;

View File

@@ -3,7 +3,7 @@ import { and, eq, count } from 'drizzle-orm';
import { db } from '@/lib/db';
import { customFieldDefinitions, customFieldValues } from '@/lib/db/schema/system';
import { createAuditLog, type AuditMeta } from '@/lib/audit';
import { NotFoundError, ValidationError, ConflictError } from '@/lib/errors';
import { CodedError, NotFoundError, ValidationError, ConflictError } from '@/lib/errors';
import type { CreateFieldInput, UpdateFieldInput } from '@/lib/validators/custom-fields';
import type { CustomFieldDefinition } from '@/lib/db/schema/system';
@@ -89,7 +89,10 @@ export async function createDefinition(
.returning();
const created = rows[0];
if (!created) throw new Error('Insert failed - no row returned');
if (!created)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Custom field definition insert returned no row',
});
void createAuditLog({
userId,
@@ -141,7 +144,10 @@ export async function updateDefinition(
.returning();
const updated = updateRows[0];
if (!updated) throw new Error('Update failed - no row returned');
if (!updated)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Custom field definition update returned no row',
});
void createAuditLog({
userId,

View File

@@ -1,7 +1,8 @@
import { env } from '@/lib/env';
import { CodedError } from '@/lib/errors';
import { logger } from '@/lib/logger';
import { getPortDocumensoConfig, type DocumensoApiVersion } from '@/lib/services/port-config';
import { fetchWithTimeout } from '@/lib/fetch-with-timeout';
import { fetchWithTimeout, FetchTimeoutError } from '@/lib/fetch-with-timeout';
interface DocumensoCreds {
baseUrl: string;
@@ -27,19 +28,36 @@ async function documensoFetch(
portId?: string,
): Promise<unknown> {
const { baseUrl, apiKey } = await resolveCreds(portId);
const res = await fetchWithTimeout(`${baseUrl}${path}`, {
...options,
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
...options?.headers,
},
});
let res: Response;
try {
res = await fetchWithTimeout(`${baseUrl}${path}`, {
...options,
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
...options?.headers,
},
});
} catch (err) {
if (err instanceof FetchTimeoutError) {
throw new CodedError('DOCUMENSO_TIMEOUT', {
internalMessage: `${path} timed out after ${err.timeoutMs}ms`,
});
}
throw err;
}
if (!res.ok) {
const err = await res.text();
logger.error({ path, status: res.status, err, portId }, 'Documenso API error');
throw new Error(`Documenso API error: ${res.status}`);
if (res.status === 401 || res.status === 403) {
throw new CodedError('DOCUMENSO_AUTH_FAILURE', {
internalMessage: `${path}${res.status}`,
});
}
throw new CodedError('DOCUMENSO_UPSTREAM_ERROR', {
internalMessage: `${path}${res.status}: ${err}`,
});
}
return res.json();
@@ -242,14 +260,32 @@ export async function sendReminder(
export async function downloadSignedPdf(docId: string, portId?: string): Promise<Buffer> {
const { baseUrl, apiKey } = await resolveCreds(portId);
const res = await fetchWithTimeout(`${baseUrl}/api/v1/documents/${docId}/download`, {
headers: { Authorization: `Bearer ${apiKey}` },
});
const path = `/api/v1/documents/${docId}/download`;
let res: Response;
try {
res = await fetchWithTimeout(`${baseUrl}${path}`, {
headers: { Authorization: `Bearer ${apiKey}` },
});
} catch (err) {
if (err instanceof FetchTimeoutError) {
throw new CodedError('DOCUMENSO_TIMEOUT', {
internalMessage: `${path} timed out after ${err.timeoutMs}ms`,
});
}
throw err;
}
if (!res.ok) {
const err = await res.text();
logger.error({ docId, status: res.status, err, portId }, 'Documenso download error');
throw new Error(`Documenso download error: ${res.status}`);
if (res.status === 401 || res.status === 403) {
throw new CodedError('DOCUMENSO_AUTH_FAILURE', {
internalMessage: `${path}${res.status}`,
});
}
throw new CodedError('DOCUMENSO_UPSTREAM_ERROR', {
internalMessage: `${path}${res.status}: ${err}`,
});
}
const arrayBuffer = await res.arrayBuffer();
@@ -367,7 +403,14 @@ export async function placeFields(
if (!res.ok) {
const err = await res.text();
logger.error({ docId, status: res.status, err, portId }, 'Documenso v2 placeFields error');
throw new Error(`Documenso v2 placeFields error: ${res.status}`);
if (res.status === 401 || res.status === 403) {
throw new CodedError('DOCUMENSO_AUTH_FAILURE', {
internalMessage: `v2 placeFields ${docId}${res.status}`,
});
}
throw new CodedError('DOCUMENSO_UPSTREAM_ERROR', {
internalMessage: `v2 placeFields ${docId}${res.status}: ${err}`,
});
}
return;
}
@@ -414,7 +457,14 @@ export async function placeFields(
{ docId, status: lastError.status, err: lastError.body, portId },
'Documenso v1 placeField error',
);
throw new Error(`Documenso v1 placeField error: ${lastError.status}`);
if (lastError.status === 401 || lastError.status === 403) {
throw new CodedError('DOCUMENSO_AUTH_FAILURE', {
internalMessage: `v1 placeField ${docId}${lastError.status}`,
});
}
throw new CodedError('DOCUMENSO_UPSTREAM_ERROR', {
internalMessage: `v1 placeField ${docId}${lastError.status}: ${lastError.body}`,
});
}
}
}
@@ -482,6 +532,13 @@ export async function voidDocument(docId: string, portId?: string): Promise<void
if (!res.ok) {
const err = await res.text();
logger.error({ docId, status: res.status, err, portId }, 'Documenso voidDocument error');
throw new Error(`Documenso voidDocument error: ${res.status}`);
if (res.status === 401 || res.status === 403) {
throw new CodedError('DOCUMENSO_AUTH_FAILURE', {
internalMessage: `voidDocument ${docId}${res.status}`,
});
}
throw new CodedError('DOCUMENSO_UPSTREAM_ERROR', {
internalMessage: `voidDocument ${docId}${res.status}: ${err}`,
});
}
}

View File

@@ -18,7 +18,7 @@ import { userProfiles, userPortRoles } from '@/lib/db/schema/users';
import { buildListQuery } from '@/lib/db/query-builder';
import { createAuditLog, type AuditMeta } from '@/lib/audit';
import { diffEntity } from '@/lib/entity-diff';
import { NotFoundError, ValidationError, ConflictError } from '@/lib/errors';
import { CodedError, NotFoundError, ValidationError, ConflictError } from '@/lib/errors';
import { emitToRoom } from '@/lib/socket/server';
import { buildStoragePath } from '@/lib/minio';
import { getStorageBackend } from '@/lib/storage';
@@ -1412,7 +1412,10 @@ export async function createFromWizard(
})
.returning();
if (!doc) throw new Error('Failed to insert document');
if (!doc)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to insert document',
});
if (data.watchers.length > 0) {
await assertWatchersInPort(portId, data.watchers);
@@ -1498,7 +1501,10 @@ export async function createFromUpload(
createdBy: meta.userId,
})
.returning();
if (!doc) throw new Error('Failed to insert document');
if (!doc)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to insert document',
});
await db.insert(documentSigners).values(
data.signers.map((s) => ({

View File

@@ -4,7 +4,7 @@ import { db } from '@/lib/db';
import { emailAccounts } from '@/lib/db/schema/email';
import { encrypt, decrypt } from '@/lib/utils/encryption';
import { createAuditLog, type AuditMeta } from '@/lib/audit';
import { NotFoundError, ForbiddenError } from '@/lib/errors';
import { CodedError, NotFoundError, ForbiddenError } from '@/lib/errors';
import type { ConnectAccountInput, ToggleAccountInput } from '@/lib/validators/email';
// ─── Types ────────────────────────────────────────────────────────────────────
@@ -62,7 +62,10 @@ export async function connectAccount(
.returning();
const account = inserted[0];
if (!account) throw new Error('Failed to insert email account');
if (!account)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to insert email account',
});
void createAuditLog({
userId: audit.userId,
@@ -104,7 +107,10 @@ export async function toggleAccount(
.returning();
const updated = updatedRows[0];
if (!updated) throw new Error('Failed to update email account');
if (!updated)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to update email account',
});
return stripCredentials(updated);
}

View File

@@ -6,7 +6,7 @@ import { emailAccounts, emailMessages, emailThreads } from '@/lib/db/schema/emai
import { documents, documentEvents, files } from '@/lib/db/schema/documents';
import { createAuditLog, type AuditMeta } from '@/lib/audit';
import { env } from '@/lib/env';
import { NotFoundError, ForbiddenError } from '@/lib/errors';
import { CodedError, NotFoundError, ForbiddenError } from '@/lib/errors';
import { logger } from '@/lib/logger';
import { getDecryptedCredentials } from '@/lib/services/email-accounts.service';
import { getPortEmailConfig } from '@/lib/services/port-config';
@@ -195,7 +195,10 @@ export async function sendEmail(
})
.returning();
const newThread = newThreadRows[0];
if (!newThread) throw new Error('Failed to create email thread');
if (!newThread)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to create email thread',
});
threadId = newThread.id;
}
@@ -222,7 +225,10 @@ export async function sendEmail(
.returning();
const message = messageRows[0];
if (!message) throw new Error('Failed to persist outbound email message');
if (!message)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to persist outbound email message',
});
// Update thread metadata
await db

View File

@@ -3,7 +3,7 @@ import { and, desc, eq, ilike, or, sql } from 'drizzle-orm';
import { db } from '@/lib/db';
import { emailAccounts, emailMessages, emailThreads } from '@/lib/db/schema/email';
import { clientContacts, clients } from '@/lib/db/schema/clients';
import { NotFoundError } from '@/lib/errors';
import { CodedError, NotFoundError } from '@/lib/errors';
import { getDecryptedCredentials } from '@/lib/services/email-accounts.service';
import { logger } from '@/lib/logger';
import type { ListThreadsInput } from '@/lib/validators/email';
@@ -160,7 +160,10 @@ export async function ingestMessage(portId: string, parsedEmail: ParsedEmail) {
})
.returning();
const newThread = newThreadRows[0];
if (!newThread) throw new Error('Failed to create email thread');
if (!newThread)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to create email thread (per-client path)',
});
threadId = newThread.id;
}
}
@@ -197,7 +200,10 @@ export async function ingestMessage(portId: string, parsedEmail: ParsedEmail) {
})
.returning();
const newThread = newThreadRows[0];
if (!newThread) throw new Error('Failed to create email thread');
if (!newThread)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to create email thread (orphan ingest path)',
});
threadId = newThread.id;
}
@@ -219,7 +225,10 @@ export async function ingestMessage(portId: string, parsedEmail: ParsedEmail) {
.returning();
const message = messageRows[0];
if (!message) throw new Error('Failed to insert email message');
if (!message)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to insert email message',
});
// Update thread's lastMessageAt and messageCount
await db

View File

@@ -8,6 +8,7 @@ import { and, between, eq, ne, sql } from 'drizzle-orm';
import { db } from '@/lib/db';
import { expenses } from '@/lib/db/schema/financial';
import { NotFoundError, ValidationError } from '@/lib/errors';
const DEDUP_WINDOW_DAYS = 3;
@@ -93,7 +94,7 @@ export async function mergeDuplicate(
portId: string,
): Promise<void> {
if (sourceId === targetId) {
throw new Error('Cannot merge an expense into itself');
throw new ValidationError('Cannot merge an expense into itself');
}
await db.transaction(async (tx) => {
@@ -106,7 +107,7 @@ export async function mergeDuplicate(
.from(expenses)
.where(and(eq(expenses.id, targetId), eq(expenses.portId, portId)));
if (!source || !target) {
throw new Error('Source or target expense not found in this port');
throw new NotFoundError('expense');
}
const mergedReceipts = Array.from(

View File

@@ -160,7 +160,10 @@ export async function createExpense(portId: string, data: CreateExpenseInput, me
})
.returning();
if (!expense) throw new Error('Insert failed');
if (!expense)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Expense insert returned no row',
});
void createAuditLog({
userId: meta.userId,

View File

@@ -3,7 +3,7 @@ import { and, desc, eq } from 'drizzle-orm';
import { db } from '@/lib/db';
import { formTemplates } from '@/lib/db/schema/documents';
import { createAuditLog } from '@/lib/audit';
import { NotFoundError } from '@/lib/errors';
import { CodedError, NotFoundError } from '@/lib/errors';
import type {
CreateFormTemplateInput,
UpdateFormTemplateInput,
@@ -50,7 +50,10 @@ export async function createFormTemplate(
})
.returning();
if (!tpl) throw new Error('Insert failed');
if (!tpl)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Form template insert returned no row',
});
void createAuditLog({
userId: meta.userId,

View File

@@ -18,7 +18,7 @@ import { db } from '@/lib/db';
import { gdprExports, type GdprExport } from '@/lib/db/schema/gdpr';
import { clients, clientContacts } from '@/lib/db/schema/clients';
import { ports } from '@/lib/db/schema/ports';
import { NotFoundError, ValidationError } from '@/lib/errors';
import { CodedError, NotFoundError, ValidationError } from '@/lib/errors';
import { logger } from '@/lib/logger';
import { getStorageBackend, presignDownloadUrl } from '@/lib/storage';
import { getQueue } from '@/lib/queue';
@@ -82,7 +82,10 @@ export async function requestGdprExport(input: RequestExportInput): Promise<Requ
status: 'pending',
})
.returning();
if (!row) throw new Error('Failed to create export row');
if (!row)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'GDPR export row insert returned no row',
});
void createAuditLog({
userId: input.requestedBy,
@@ -153,9 +156,9 @@ export async function processGdprExportJob(input: ProcessJobInput): Promise<void
const buffer = await done;
if (buffer.length > MAX_BUNDLE_BYTES) {
throw new Error(
`GDPR bundle exceeded ${MAX_BUNDLE_BYTES} bytes (got ${buffer.length}); refusing to upload`,
);
throw new CodedError('INTERNAL', {
internalMessage: `GDPR bundle exceeded ${MAX_BUNDLE_BYTES} bytes (got ${buffer.length}); refusing to upload`,
});
}
const port = await db.query.ports.findFirst({ where: eq(ports.id, input.portId) });

View File

@@ -7,6 +7,7 @@ import { reminders } from '@/lib/db/schema/operations';
import { emailThreads } from '@/lib/db/schema/email';
import { logger } from '@/lib/logger';
import { PIPELINE_STAGES } from '@/lib/constants';
import { NotFoundError } from '@/lib/errors';
// ─── Types ────────────────────────────────────────────────────────────────────
@@ -108,7 +109,7 @@ export async function calculateInterestScore(
});
if (!interest) {
throw new Error(`Interest not found: ${interestId}`);
throw new NotFoundError('interest');
}
// Try cache (port-scoped key)

View File

@@ -12,7 +12,7 @@ import { buildListQuery } from '@/lib/db/query-builder';
import { createAuditLog, type AuditMeta } from '@/lib/audit';
import { diffEntity } from '@/lib/entity-diff';
import { withTransaction } from '@/lib/db/utils';
import { NotFoundError, ConflictError, ValidationError } from '@/lib/errors';
import { CodedError, NotFoundError, ConflictError, ValidationError } from '@/lib/errors';
import { getCountryName } from '@/lib/i18n/countries';
import { getSubdivisionName } from '@/lib/i18n/subdivisions';
import { emitToRoom } from '@/lib/socket/server';
@@ -337,7 +337,10 @@ export async function createInvoice(portId: string, data: CreateInvoiceInput, me
})
.returning();
if (!newInvoice) throw new Error('Insert failed');
if (!newInvoice)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Invoice insert returned no row',
});
// Insert line items
if (lineItemsData.length > 0) {
@@ -618,7 +621,10 @@ export async function generateInvoicePdf(id: string, portId: string, meta: Audit
})
.returning();
if (!fileRecord) throw new Error('File record insert failed');
if (!fileRecord)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Invoice PDF file record insert returned no row',
});
await db
.update(invoices)

View File

@@ -6,7 +6,7 @@ import { interestNotes, interests } from '@/lib/db/schema/interests';
import { yachtNotes, yachts } from '@/lib/db/schema/yachts';
import { companyNotes, companies } from '@/lib/db/schema/companies';
import { userProfiles } from '@/lib/db/schema/users';
import { NotFoundError, ValidationError } from '@/lib/errors';
import { CodedError, NotFoundError, ValidationError } from '@/lib/errors';
import type { CreateNoteInput, UpdateNoteInput } from '@/lib/validators/notes';
const EDIT_WINDOW_MS = 15 * 60 * 1000; // 15 minutes
@@ -141,7 +141,10 @@ export async function create(
.insert(yachtNotes)
.values({ yachtId: entityId, authorId, content: data.content })
.returning();
if (!note) throw new Error('Insert failed');
if (!note)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Yacht note insert returned no row',
});
const profile = await db
.select({ displayName: userProfiles.displayName })
.from(userProfiles)
@@ -154,7 +157,10 @@ export async function create(
.insert(companyNotes)
.values({ companyId: entityId, authorId, content: data.content })
.returning();
if (!note) throw new Error('Insert failed');
if (!note)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Company note insert returned no row',
});
const profile = await db
.select({ displayName: userProfiles.displayName })
.from(userProfiles)
@@ -168,7 +174,10 @@ export async function create(
.values({ clientId: entityId, authorId, content: data.content })
.returning();
if (!note) throw new Error('Insert failed');
if (!note)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Client note insert returned no row',
});
const profile = await db
.select({ displayName: userProfiles.displayName })
@@ -204,7 +213,10 @@ export async function create(
.values({ interestId: entityId, authorId, content: data.content })
.returning();
if (!note) throw new Error('Insert failed');
if (!note)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Interest note insert returned no row',
});
const profile = await db
.select({ displayName: userProfiles.displayName })
@@ -235,7 +247,9 @@ export async function create(
return { ...note, authorName };
}
throw new Error(`Unsupported entityType: ${entityType as string}`);
throw new CodedError('INTERNAL', {
internalMessage: `Unsupported entityType: ${entityType as string}`,
});
}
export async function update(

View File

@@ -6,6 +6,7 @@
import OpenAI from 'openai';
import { CodedError } from '@/lib/errors';
import { logger } from '@/lib/logger';
import { fetchWithTimeout } from '@/lib/fetch-with-timeout';
@@ -140,7 +141,9 @@ async function runClaude({ imageBuffer, mimeType, apiKey, model }: RunArgs): Pro
});
if (!res.ok) {
const detail = await res.text().catch(() => '');
throw new Error(`Claude API ${res.status}: ${detail.slice(0, 200)}`);
throw new CodedError('OCR_UPSTREAM_ERROR', {
internalMessage: `Claude API ${res.status}: ${detail.slice(0, 200)}`,
});
}
const body = (await res.json()) as {
id?: string;

View File

@@ -8,7 +8,13 @@ import { systemSettings } from '@/lib/db/schema/system';
import { env } from '@/lib/env';
import { sendEmail } from '@/lib/email';
import { activationEmail, resetEmail } from '@/lib/email/templates/portal-auth';
import { ConflictError, NotFoundError, UnauthorizedError, ValidationError } from '@/lib/errors';
import {
CodedError,
ConflictError,
NotFoundError,
UnauthorizedError,
ValidationError,
} from '@/lib/errors';
import { logger } from '@/lib/logger';
import { createPortalToken } from '@/lib/portal/auth';
import { hashPassword, hashToken, mintToken, verifyPassword } from '@/lib/portal/passwords';
@@ -71,7 +77,9 @@ export async function createPortalUser(args: {
.returning({ id: portalUsers.id });
if (!user) {
throw new Error('Failed to create portal user');
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to create portal user',
});
}
await issueActivationToken(user.id, normalizedEmail, args.portId);

View File

@@ -12,7 +12,7 @@ import { emitToRoom } from '@/lib/socket/server';
import { getQueue } from '@/lib/queue';
import { env } from '@/lib/env';
import { logger } from '@/lib/logger';
import { NotFoundError } from '@/lib/errors';
import { CodedError, ConflictError, NotFoundError } from '@/lib/errors';
import {
fetchPipelineData,
@@ -82,7 +82,9 @@ export async function requestReport(portId: string, userId: string, data: Reques
.returning();
if (!report) {
throw new Error('Failed to create report record');
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to create report record',
});
}
await getQueue('reports').add('generate-report', { reportJobId: report.id });
@@ -149,7 +151,7 @@ export async function getDownloadUrl(reportId: string, portId: string) {
}
if (report.status !== 'ready' || !report.fileId) {
throw new Error('Report is not ready for download');
throw new ConflictError('Report is not ready for download');
}
const file = await db.query.files.findFirst({
@@ -173,7 +175,7 @@ export async function generateReport(reportJobId: string): Promise<void> {
});
if (!report) {
throw new Error(`Report job not found: ${reportJobId}`);
throw new NotFoundError('report job');
}
const { portId, reportType, name, parameters, requestedBy } = report;
@@ -189,7 +191,9 @@ export async function generateReport(reportJobId: string): Promise<void> {
const typeKey = reportType as ReportType;
const config = REPORT_TYPE_MAP[typeKey];
if (!config) {
throw new Error(`Unknown report type: ${reportType}`);
throw new CodedError('VALIDATION_ERROR', {
internalMessage: `Unknown report type: ${reportType}`,
});
}
const params = (parameters ?? {}) as Record<string, unknown>;
@@ -242,7 +246,9 @@ export async function generateReport(reportJobId: string): Promise<void> {
.returning();
if (!fileRecord) {
throw new Error('Failed to insert file record');
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to insert file record for generated report',
});
}
// 11. Update generatedReports: status='ready', fileId, completedAt

View File

@@ -3,7 +3,7 @@ import { and, eq } from 'drizzle-orm';
import { db } from '@/lib/db';
import { residentialClients, residentialInterests } from '@/lib/db/schema/residential';
import { createAuditLog, type AuditMeta } from '@/lib/audit';
import { NotFoundError } from '@/lib/errors';
import { CodedError, NotFoundError } from '@/lib/errors';
import { emitToRoom } from '@/lib/socket/server';
import { buildListQuery } from '@/lib/db/query-builder';
import { diffEntity } from '@/lib/entity-diff';
@@ -78,7 +78,10 @@ export async function createResidentialClient(
.insert(residentialClients)
.values({ portId, ...data })
.returning();
if (!row) throw new Error('Failed to create residential client');
if (!row)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to create residential client',
});
void createAuditLog({
userId: meta.userId,
@@ -249,7 +252,10 @@ export async function createResidentialInterest(
.insert(residentialInterests)
.values({ portId, ...data })
.returning();
if (!row) throw new Error('Failed to create residential interest');
if (!row)
throw new CodedError('INSERT_RETURNING_EMPTY', {
internalMessage: 'Failed to create residential interest',
});
void createAuditLog({
userId: meta.userId,

View File

@@ -20,6 +20,7 @@
import nodemailer, { type Transporter } from 'nodemailer';
import { env } from '@/lib/env';
import { ConflictError } from '@/lib/errors';
import { decrypt, encrypt } from '@/lib/utils/encryption';
import { getSetting, upsertSetting } from '@/lib/services/settings.service';
import type { AuditMeta } from '@/lib/audit';
@@ -323,7 +324,7 @@ export async function createSalesTransporter(portId: string): Promise<{
}> {
const cfg = await getSalesEmailConfig(portId);
if (!cfg.smtpHost) {
throw new Error(
throw new ConflictError(
'Sales SMTP not configured for this port. Configure in /admin/email before sending.',
);
}

View File

@@ -6,6 +6,7 @@ import { getQueue, QUEUE_CONFIGS, type QueueName } from '@/lib/queue';
import { createAuditLog } from '@/lib/audit';
import { env } from '@/lib/env';
import { sql, desc, eq } from 'drizzle-orm';
import { NotFoundError } from '@/lib/errors';
import { logger } from '@/lib/logger';
// ─── Types ────────────────────────────────────────────────────────────────────
@@ -269,7 +270,7 @@ export async function getQueueJobs(
export async function retryJob(queueName: QueueName, jobId: string, userId: string): Promise<void> {
const queue = getQueue(queueName);
const job = await queue.getJob(jobId);
if (!job) throw new Error(`Job ${jobId} not found in queue ${queueName}`);
if (!job) throw new NotFoundError('queue job');
await job.retry();
@@ -294,7 +295,7 @@ export async function deleteJob(
): Promise<void> {
const queue = getQueue(queueName);
const job = await queue.getJob(jobId);
if (!job) throw new Error(`Job ${jobId} not found in queue ${queueName}`);
if (!job) throw new NotFoundError('queue job');
await job.remove();

View File

@@ -21,6 +21,7 @@ import { and, eq, inArray } from 'drizzle-orm';
import { db } from '@/lib/db';
import { systemSettings } from '@/lib/db/schema/system';
import { rangeToBounds, type DateRange } from '@/lib/analytics/range';
import { CodedError } from '@/lib/errors';
import { fetchWithTimeout } from '@/lib/fetch-with-timeout';
// ─── Settings access ────────────────────────────────────────────────────────
@@ -87,10 +88,15 @@ async function loginAndCache(apiUrl: string, username: string, password: string)
body: JSON.stringify({ username, password }),
});
if (!res.ok) {
throw new Error(`Umami login failed: ${res.status} ${res.statusText}`);
throw new CodedError('UMAMI_UPSTREAM_ERROR', {
internalMessage: `Umami login failed: ${res.status} ${res.statusText}`,
});
}
const body = (await res.json()) as { token?: string };
if (!body.token) throw new Error('Umami login response missing token');
if (!body.token)
throw new CodedError('UMAMI_UPSTREAM_ERROR', {
internalMessage: 'Umami login response missing token',
});
jwtCache.set(`${apiUrl}::${username}`, {
token: body.token,
expiresAt: Date.now() + JWT_TTL_MS,
@@ -101,7 +107,9 @@ async function loginAndCache(apiUrl: string, username: string, password: string)
async function resolveBearer(config: UmamiPortConfig): Promise<string> {
if (config.apiToken) return config.apiToken;
if (!config.username || !config.password) {
throw new Error('Umami is misconfigured: no API token and no username/password.');
throw new CodedError('UMAMI_NOT_CONFIGURED', {
internalMessage: 'Umami is misconfigured: no API token and no username/password.',
});
}
const cacheKey = `${config.apiUrl}::${config.username}`;
const cached = jwtCache.get(cacheKey);
@@ -136,13 +144,17 @@ async function umamiFetch<T>(
if (res.status === 401 || res.status === 403) {
// Bearer rejected - drop cached JWT so next call re-logs in.
if (config.username) jwtCache.delete(`${config.apiUrl}::${config.username}`);
throw new Error(`Umami unauthorized: ${res.status}`);
throw new CodedError('UMAMI_UPSTREAM_ERROR', {
internalMessage: `Umami unauthorized: ${res.status}`,
});
}
if (!res.ok) {
const text = await res.text().catch(() => '');
throw new Error(
`Umami ${path} failed: ${res.status} ${res.statusText}${text ? ` - ${text}` : ''}`,
);
throw new CodedError('UMAMI_UPSTREAM_ERROR', {
internalMessage: `Umami ${path} failed: ${res.status} ${res.statusText}${
text ? ` - ${text}` : ''
}`,
});
}
return (await res.json()) as T;
}
@@ -248,7 +260,9 @@ export async function getActiveVisitors(portId: string): Promise<UmamiActiveVisi
export async function testConnection(portId: string): Promise<{ ok: true; visitors: number }> {
const config = await loadUmamiConfig(portId);
if (!config) {
throw new Error('Umami is not configured for this port.');
throw new CodedError('UMAMI_NOT_CONFIGURED', {
internalMessage: 'Umami is not configured for this port.',
});
}
const result = await umamiFetch<UmamiActiveVisitors>(
config,