fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
+110
View File
@@ -0,0 +1,110 @@
/**
* The database-error wrapper, and the classification it exists to unlock.
*
* The idiom `throw new Error(\`Database error: ${error.message}\`)` kept the
* prose and dropped `code`. `isTransientFailure()` checks that SQLSTATE FIRST,
* and 57014 (statement timeout) is already in its transient set, so stripping
* it turned a retryable timeout into UNKNOWN_ERROR: "Något gick fel. Försök
* igen." Agents cannot dispatch on that, so they retried: on production over
* 60 days, 462 wasted repeat calls, with 53.1% of all real-agent error calls
* sitting inside a repeat streak.
*
* The headline test is the last one: it asserts the OLD shape still resolves
* to UNKNOWN_ERROR and the new one resolves to TRANSIENT_ERROR, so it fails if
* the wrapper ever stops preserving the code.
*/
import { describe, it, expect } from 'vitest'
import { dbError, errorCauseTag } from '../db-error'
import { getStructuredError } from '../get-structured-error'
/** What supabase-js hands back when Postgres cancels on statement_timeout. */
const TIMEOUT_ERROR = {
message: 'canceling statement due to statement timeout',
code: '57014',
details: null,
hint: null,
}
describe('dbError', () => {
it('preserves the SQLSTATE, which is the whole point', () => {
const wrapped = dbError(TIMEOUT_ERROR)
expect(wrapped.code).toBe('57014')
})
it('preserves details and hint for the server log', () => {
const wrapped = dbError({
message: 'duplicate key value violates unique constraint',
code: '23505',
details: 'Key (company_id, account_number) already exists.',
hint: 'Use upsert.',
})
expect(wrapped.details).toContain('already exists')
expect(wrapped.hint).toBe('Use upsert.')
})
it('never renders the literal "undefined"', () => {
// A driver-level failure (aborted fetch, gateway timeout) can arrive with
// no message at all. "Database error: undefined" is the string that made
// these unsearchable in production.
for (const shape of [{}, { message: undefined }, { message: '' }, { message: ' ' }, null]) {
expect(dbError(shape).message).not.toContain('undefined')
}
})
it('prefixes with the historical context by default', () => {
expect(dbError({ message: 'boom' }).message).toBe('Database error: boom')
})
it('keeps the driver message verbatim when context is null', () => {
// fetchAllRows passes null: callers such as query_journal's
// sanitizeDbError already match on the exact text, and this change is
// meant to add the code, not reword anything.
expect(dbError({ message: 'boom' }, null).message).toBe('boom')
})
it('accepts a custom context', () => {
expect(dbError({ message: 'boom' }, 'Database error resolving voucher "A-7"').message).toBe(
'Database error resolving voucher "A-7": boom',
)
})
})
describe('errorCauseTag', () => {
it('returns the SQLSTATE, which carries no tenant data', () => {
expect(errorCauseTag(dbError(TIMEOUT_ERROR))).toBe('57014')
})
it('falls back to the error name when there is no code', () => {
expect(errorCauseTag(new TypeError('nope'))).toBe('TypeError')
})
it('returns null rather than inventing a tag', () => {
expect(errorCauseTag(new Error('plain'))).toBeNull()
expect(errorCauseTag(null)).toBeNull()
})
})
describe('classification: the regression this prevents', () => {
it('classifies a wrapped statement timeout as retryable', () => {
expect(getStructuredError(dbError(TIMEOUT_ERROR)).code).toBe('TRANSIENT_ERROR')
})
it('would classify the OLD bare-Error shape as UNKNOWN_ERROR', () => {
// The bug, pinned. `new Error(error.message)` is what fetchAllRows threw,
// and PostgREST does not always put the word "timeout" in the message it
// returns, so message-pattern matching cannot be relied on. Only the code
// is durable, which is why the wrapper must carry it.
const stripped = new Error('some driver text that names no timeout')
expect(getStructuredError(stripped).code).toBe('UNKNOWN_ERROR')
// Same failure, code intact: now dispatchable.
const preserved = dbError({ message: 'some driver text that names no timeout', code: '57014' })
expect(getStructuredError(preserved).code).toBe('TRANSIENT_ERROR')
})
it('does not mistake a SQLSTATE for one of our own stable codes', () => {
// extractCode() only accepts /^[A-Z_]+$/. Every SQLSTATE contains digits,
// so attaching one cannot hijack the application error registry.
expect(getStructuredError(dbError({ message: 'x', code: '23505' })).code).not.toBe('23505')
})
})
@@ -0,0 +1,66 @@
import { describe, it, expect } from 'vitest'
import { getBankConnectionErrorMessage } from '../get-error-message'
// The PSD2 callback mapper (issue #1716): raw provider tokens used to reach
// the user verbatim ("server_error", "invalid_state"), which left them with
// nothing to act on and support with nothing to answer.
describe('getBankConnectionErrorMessage', () => {
it('maps a user cancel (access_denied) without echoing the provider text', () => {
const msg = getBankConnectionErrorMessage('access_denied', 'User cancelled')
expect(msg).toContain('Anslutningen avbröts hos banken')
expect(msg).not.toContain('User cancelled')
})
it('treats "Cancelled by user" descriptions as a cancel regardless of code', () => {
const msg = getBankConnectionErrorMessage('server_error', 'Cancelled by user')
expect(msg).toContain('Anslutningen avbröts hos banken')
})
it('maps a bare server_error to the bank-side failure explanation', () => {
const msg = getBankConnectionErrorMessage('server_error')
expect(msg).toContain('fel på bankens sida')
// The Handelsbanken corporate case: point at mandates without naming a bank
// (the settings page adds the bank-specific steps from bank_error_code).
expect(msg).toContain('fullmakt')
})
it('surfaces the provider description in parentheses on unknown codes', () => {
const msg = getBankConnectionErrorMessage('aspsp_error', 'PSU lacks corporate mandate')
expect(msg).toContain('Banken avvisade anslutningen')
expect(msg).toContain('(PSU lacks corporate mandate)')
})
it('does not duplicate the code when the description equals the code', () => {
const msg = getBankConnectionErrorMessage('server_error', 'server_error')
expect(msg).toContain('fel på bankens sida')
expect(msg).not.toContain('(server_error)')
})
it('maps session-expiry descriptions to the expired-session message', () => {
const msg = getBankConnectionErrorMessage('server_error', 'Session expired at ASPSP')
expect(msg).toContain('inloggningssession')
expect(msg).toContain('(Session expired at ASPSP)')
})
it('maps the internal invalid_state token to a retry explanation', () => {
const msg = getBankConnectionErrorMessage('invalid_state')
expect(msg).toContain('Starta bankkopplingen på nytt')
expect(msg).not.toContain('invalid_state')
})
it('maps missing_parameters and invalid_code_format to Swedish', () => {
expect(getBankConnectionErrorMessage('missing_parameters')).toContain('ofullständigt svar')
expect(getBankConnectionErrorMessage('invalid_code_format')).toContain('ogiltigt svar')
})
it('maps temporarily_unavailable to the try-later message', () => {
const msg = getBankConnectionErrorMessage('temporarily_unavailable')
expect(msg).toContain('tillfälligt otillgänglig')
})
it('falls back to a Swedish rejection message for unknown codes without description', () => {
const msg = getBankConnectionErrorMessage('weird_code')
expect(msg).toContain('Banken avvisade anslutningen')
expect(msg).not.toContain('weird_code')
})
})
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,139 @@
import { describe, it, expect } from 'vitest'
import { getStructuredError } from '../get-structured-error'
describe('getStructuredError', () => {
it('extracts code from structured bookkeeping error', () => {
const result = getStructuredError({
error: {
code: 'JOURNAL_ENTRY_NOT_BALANCED',
message: 'Debits do not match credits',
details: { totalDebit: 100, totalCredit: 90 },
},
})
expect(result.code).toBe('JOURNAL_ENTRY_NOT_BALANCED')
expect(result.message_sv).toContain('balanserar inte')
expect(result.message_en).toContain('Debits')
expect(result.remediation?.description).toContain('Recalculate')
})
it('extracts code from typed error class with code property', () => {
class FakeBookkeepingError extends Error {
readonly code = 'ACCOUNTS_NOT_IN_CHART'
readonly accountNumbers = ['1930', '2641']
constructor() {
super('Accounts not in chart')
}
}
const result = getStructuredError(new FakeBookkeepingError())
expect(result.code).toBe('ACCOUNTS_NOT_IN_CHART')
expect(result.remediation?.resource).toBe('Accounted://chart-of-accounts')
})
it('infers PERIOD_NOT_LOCKED from message text', () => {
const result = getStructuredError(new Error('Period must be locked before closing'))
expect(result.code).toBe('PERIOD_NOT_LOCKED')
expect(result.remediation?.tool).toBe('gnubok_lock_period')
})
it('maps an over-long reason to VALIDATION_ERROR with a specific Swedish message', () => {
const result = getStructuredError(new Error('reason must be 500 characters or fewer'))
expect(result.code).toBe('VALIDATION_ERROR')
expect(result.message_sv).toBe('Motiveringen får vara högst 500 tecken.')
})
it('infers PERIOD_HAS_UNBOOKED_TRANSACTIONS from Swedish lock-error message', () => {
const result = getStructuredError(
new Error('Kan inte låsa period: 3 affärstransaktion(er) saknar bokföring.')
)
expect(result.code).toBe('PERIOD_HAS_UNBOOKED_TRANSACTIONS')
expect(result.remediation?.tool).toBe('gnubok_list_uncategorized_transactions')
})
it('produces INSUFFICIENT_SCOPE remediation with attempted scope', () => {
const result = getStructuredError(
new Error('Insufficient scope: this API key does not have the "bookkeeping:write" scope'),
{ attemptedScope: 'bookkeeping:write' }
)
expect(result.code).toBe('INSUFFICIENT_SCOPE')
expect(result.remediation?.description).toContain('"bookkeeping:write"')
expect(result.remediation?.resource).toBe('Accounted://capabilities')
})
it('infers TRANSACTION_ALREADY_CATEGORIZED', () => {
const result = getStructuredError(new Error('Transaction already has a journal entry'))
expect(result.code).toBe('TRANSACTION_ALREADY_CATEGORIZED')
expect(result.remediation?.tool).toBe('gnubok_uncategorize_transaction')
})
it('falls back to UNKNOWN_ERROR when no code or pattern matches', () => {
const result = getStructuredError(new Error('Something weird happened'))
expect(result.code).toBe('UNKNOWN_ERROR')
expect(result.remediation).toBeUndefined()
})
it('handles plain string errors', () => {
const result = getStructuredError('Period must be locked before closing')
expect(result.code).toBe('PERIOD_NOT_LOCKED')
expect(result.message_en).toBe('Period must be locked before closing')
})
it('handles null/undefined gracefully', () => {
const result = getStructuredError(null)
expect(result.code).toBe('UNKNOWN_ERROR')
expect(result.message_en).toBe('Unknown error')
expect(result.message_sv).toBeTruthy()
})
it('always returns Swedish message even with no match', () => {
const result = getStructuredError(new Error('Random gibberish XYZ'))
expect(result.message_sv).toBeTruthy()
expect(result.message_sv.length).toBeGreaterThan(0)
})
})
describe('retryable contract (always present, transient inference)', () => {
it('is explicitly false for a plain unclassified error', () => {
const result = getStructuredError(new Error('nope'))
expect(result.code).toBe('UNKNOWN_ERROR')
expect(result.retryable).toBe(false)
})
it('classifies a wrapped deadlock message as TRANSIENT_ERROR, retryable', () => {
// Tools wrap DB errors as plain strings, losing the SQLSTATE: the
// message pattern must survive that wrapping.
const result = getStructuredError(new Error('Database error: deadlock detected'))
expect(result.code).toBe('TRANSIENT_ERROR')
expect(result.retryable).toBe(true)
})
it('classifies a Postgres serialization-failure SQLSTATE as transient', () => {
const err = Object.assign(new Error('could not complete'), { code: '40001' })
const result = getStructuredError(err)
expect(result.code).toBe('TRANSIENT_ERROR')
expect(result.retryable).toBe(true)
})
it('classifies upstream 429/503 statuses as transient', () => {
expect(getStructuredError(Object.assign(new Error('slow down'), { status: 429 })).retryable).toBe(true)
expect(getStructuredError(Object.assign(new Error('bad gateway'), { statusCode: 502 })).retryable).toBe(true)
})
it('classifies fetch/socket failures as transient', () => {
expect(getStructuredError(new Error('fetch failed')).code).toBe('TRANSIENT_ERROR')
expect(getStructuredError(new Error('socket hang up')).retryable).toBe(true)
expect(getStructuredError(new Error('connect ECONNRESET 1.2.3.4:443')).retryable).toBe(true)
})
it('keeps a specific inferred code but still computes retryable from the failure', () => {
// NOT_FOUND is permanent even though nothing in the registry says so explicitly.
const result = getStructuredError(new Error('Transaction not found'))
expect(result.code).toBe('NOT_FOUND')
expect(result.retryable).toBe(false)
})
it('lets an explicit registry retryable:true win over inference', () => {
const tagged = Object.assign(new Error('over the cap'), { code: 'RATE_LIMITED' })
const result = getStructuredError(tagged)
expect(result.retryable).toBe(true)
})
})
@@ -0,0 +1,60 @@
import { describe, expect, it } from 'vitest'
import { getErrorMessage } from '../get-error-message'
import { getErrorEntry } from '../structured-errors'
import { ReconciliationSignoffError, type SignoffErrorCode } from '@/lib/reconciliation/signoff'
/**
* The sign-off refusals are composed in Swedish at the throw site (a date, an
* amount). Before these codes were registered, getErrorMessage() fell through
* to its generic fallback and the dialog showed "Något gick fel. Försök igen."
* for a refused sign-off.
*/
const CODES: SignoffErrorCode[] = [
'INVALID_DATE',
'DATE_IN_FUTURE',
'NOT_FETCHED_THROUGH',
'OUTSIDE_UNKNOWN',
'NOT_RECONCILED',
'NOTE_REQUIRED',
'ALREADY_SIGNED_OFF',
'SIGNOFF_NOT_FOUND',
'ALREADY_REOPENED',
'SIGNOFF_RACE',
'EXTERNAL_BALANCE_NOT_ALLOWED',
]
describe('reconciliation sign-off codes in the error registry', () => {
it('registers every code with a Swedish and an English message', () => {
for (const code of CODES) {
const entry = getErrorEntry(code)
expect(entry, code).toBeDefined()
expect(entry?.message_sv, code).toMatch(/\S/)
expect(entry?.message_en, code).toMatch(/\S/)
expect(entry?.thrown_message_sv, code).toBe(true)
}
})
it('passes the thrown Swedish text through verbatim, runtime detail included', () => {
const err = new ReconciliationSignoffError(
'Skattekontot är hämtat t.o.m. 2026-08-20. Hämta igen innan du stämmer av ett senare datum.',
'NOT_FETCHED_THROUGH',
)
expect(getErrorMessage(err)).toBe(
'Skattekontot är hämtat t.o.m. 2026-08-20. Hämta igen innan du stämmer av ett senare datum.',
)
const refused = new ReconciliationSignoffError(
'Kontot har en oförklarad differens. Koppla eller bokför raderna först, eller signera med en notering.',
'NOT_RECONCILED',
{ unexplained_difference: 53717 },
)
expect(getErrorMessage(refused)).toBe(
'Kontot har en oförklarad differens. Koppla eller bokför raderna först, eller signera med en notering.',
)
expect(getErrorMessage(refused)).not.toMatch(/Något gick fel/)
})
it('gives English users the registry text', () => {
const err = new ReconciliationSignoffError('Kontot har en oförklarad differens.', 'NOT_RECONCILED')
expect(getErrorMessage(err, { locale: 'en' })).toBe(getErrorEntry('NOT_RECONCILED')?.message_en)
})
})
@@ -0,0 +1,254 @@
import { describe, it, expect } from 'vitest'
import { ZodError, z } from 'zod'
import {
errorResponse,
errorResponseFromCode,
type ErrorEnvelope,
} from '../get-structured-error'
import { getErrorEntry, listErrorCodes } from '../structured-errors'
import {
AccountsNotInChartError,
EntryDateOutsideFiscalPeriodError,
JournalEntryNotBalancedError,
} from '@/lib/bookkeeping/errors'
const noopLogger = {
error: () => {},
}
async function readEnvelope(res: Response): Promise<ErrorEnvelope> {
return (await res.json()) as ErrorEnvelope
}
describe('structured-errors registry', () => {
it('has entries for the canonical generic codes', () => {
for (const code of [
'INTERNAL_ERROR',
'VALIDATION_ERROR',
'UNAUTHORIZED',
'FORBIDDEN',
'NOT_FOUND',
'CONFLICT',
'RATE_LIMITED',
'COMPANY_CONTEXT_MISSING',
]) {
const entry = getErrorEntry(code)
expect(entry, `missing entry for ${code}`).toBeDefined()
expect(entry?.message_sv).toBeTruthy()
expect(entry?.message_en).toBeTruthy()
}
})
it('has 422 entries for the Björn Lundén connect verdicts (valid key, missing activation; unknown key)', () => {
for (const code of ['BL_INTEGRATION_NOT_ACTIVATED', 'BL_COMPANY_KEY_NOT_FOUND']) {
const entry = getErrorEntry(code)
expect(entry, `missing entry for ${code}`).toBeDefined()
// 422, never 401: the caller's own session is fine and a 401 can trip
// client-side auth interceptors into logging the user out.
expect(entry?.httpStatus).toBe(422)
expect(entry?.message_sv).toBeTruthy()
expect(entry?.message_en).toBeTruthy()
}
})
it('has an entry for every code the link-transaction service can emit', () => {
for (const code of [
'LINK_TX_JE_NOT_FOUND',
'LINK_TX_JE_NOT_POSTED',
'LINK_TX_TX_ALREADY_LINKED',
'LINK_TX_INVOICE_NOT_FOUND',
'LINK_TX_INVOICE_NOT_OPEN',
'LINK_TX_INVOICE_CREDIT_NOTE',
'LINK_TX_INVOICE_RACE',
'LINK_TX_INVOICE_CURRENCY_MISMATCH',
'LINK_TX_DB_ERROR',
]) {
const entry = getErrorEntry(code)
expect(entry, `missing entry for ${code}`).toBeDefined()
expect(entry?.message_sv).toBeTruthy()
expect(entry?.message_en).toBeTruthy()
}
})
it('registers PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED as a 503 configuration gap (#1996)', () => {
const entry = getErrorEntry('PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED')
expect(entry).toBeDefined()
expect(entry?.httpStatus).toBe(503)
expect(entry?.message_sv).toContain('PERSONNUMMER_ENCRYPTION_KEY')
expect(entry?.message_sv).toMatch(/Kontakta supporten/)
expect(entry?.message_en).toContain('PERSONNUMMER_ENCRYPTION_KEY')
expect(entry?.remediation?.description).toContain('PERSONNUMMER_ENCRYPTION_KEY')
// Retrying without the variable fails identically: never mark it transient.
expect(entry?.retryable).toBeFalsy()
})
it('registers PROVIDER_RESOURCE_FORBIDDEN as a 403 that never tells the user to reconnect', () => {
// The provider refused one register on a grant that keeps working, so
// "Återanslut" is the one thing this message must not say: reconnecting
// re-mints the same grant and meets the same 403. This entry is also the
// single source of that copy (get-error-message.ts reads it for the toast,
// lib/docs/content/errors.ts publishes it), so it has to exist.
const entry = getErrorEntry('PROVIDER_RESOURCE_FORBIDDEN')
expect(entry).toBeDefined()
expect(entry?.httpStatus).toBe(403)
// Says reconnecting does not help; never the "Återanslut för att
// fortsätta" imperative PROVIDER_AUTH_EXPIRED carries.
expect(entry?.message_sv).toMatch(/återansluta hjälper inte/i)
expect(entry?.message_sv).not.toMatch(/återanslut för att fortsätta/i)
expect(entry?.message_sv).toMatch(/behörighet/i)
expect(entry?.message_en).toBeTruthy()
// Retrying the same call hits the same permission gap: not transient.
expect(entry?.retryable).toBeFalsy()
})
it('listErrorCodes returns at least the bookkeeping + generic + provider codes', () => {
const codes = listErrorCodes()
expect(codes.length).toBeGreaterThan(20)
expect(codes).toContain('JOURNAL_ENTRY_NOT_BALANCED')
expect(codes).toContain('PROVIDER_AUTH_EXPIRED')
expect(codes).toContain('BOKIO_COMPANY_NOT_FOUND')
expect(codes).toContain('CANNOT_EDIT_NON_DRAFT')
expect(codes).toContain('MANDATORY_DIMENSION_MISSING')
// Node network system codes registered as retryable transients (#337).
expect(codes).toContain('ECONNREFUSED')
expect(getErrorEntry('ECONNREFUSED')?.retryable).toBe(true)
})
})
describe('errorResponse', () => {
it('maps a plain Error carrying a registry code to that code, status and requestId', async () => {
// The shape lib/salary/personnummer.ts throws when the key is unset in
// production: an Error with a `code` own-property, no class hierarchy.
const err = Object.assign(new Error('PERSONNUMMER_ENCRYPTION_KEY is required in production'), {
code: 'PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED',
})
const res = errorResponse(err, noopLogger, { requestId: 'req_1996' })
expect(res.status).toBe(503)
expect(res.headers.get('X-Request-Id')).toBe('req_1996')
const body = await readEnvelope(res)
expect(body.error.code).toBe('PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED')
expect(body.error.message).toMatch(/PERSONNUMMER_ENCRYPTION_KEY/)
expect(body.error.requestId).toBe('req_1996')
// The raw English Error.message must not replace the registry message.
expect(body.error.message).not.toBe(err.message)
})
it('maps BookkeepingError to its code + structured details + Swedish message', async () => {
const err = new JournalEntryNotBalancedError(100, 90)
const res = errorResponse(err, noopLogger, { requestId: 'req_1' })
expect(res.status).toBe(400)
expect(res.headers.get('X-Request-Id')).toBe('req_1')
const body = await readEnvelope(res)
expect(body.error.code).toBe('JOURNAL_ENTRY_NOT_BALANCED')
expect(body.error.message).toMatch(/balanserar inte/i)
expect(body.error.requestId).toBe('req_1')
expect(body.error.details).toMatchObject({ totalDebit: 100, totalCredit: 90 })
})
it('preserves AccountsNotInChartError details', async () => {
const err = new AccountsNotInChartError(['1930', '2641'])
const res = errorResponse(err, noopLogger, { requestId: 'req_2' })
const body = await readEnvelope(res)
expect(body.error.code).toBe('ACCOUNTS_NOT_IN_CHART')
expect(body.error.details).toMatchObject({ account_numbers: ['1930', '2641'] })
})
it('maps ZodError to VALIDATION_ERROR with field issues', async () => {
let zodErr: ZodError
try {
z.object({ name: z.string().min(1) }).parse({ name: '' })
throw new Error('should have thrown')
} catch (e) {
zodErr = e as ZodError
}
const res = errorResponse(zodErr, noopLogger, { requestId: 'req_3' })
expect(res.status).toBe(400)
const body = await readEnvelope(res)
expect(body.error.code).toBe('VALIDATION_ERROR')
expect(body.error.details).toMatchObject({
issues: expect.arrayContaining([
expect.objectContaining({ field: 'name' }),
]),
})
})
it('maps Postgres unique violation to VALIDATION_ERROR with pgCode', async () => {
const pgErr = Object.assign(new Error('duplicate key'), { code: '23505' })
const res = errorResponse(pgErr, noopLogger, { requestId: 'req_4' })
expect(res.status).toBe(400)
const body = await readEnvelope(res)
expect(body.error.code).toBe('VALIDATION_ERROR')
expect(body.error.details).toMatchObject({ pgCode: '23505' })
})
it('maps the ignored-transaction journal constraint to a typed conflict', async () => {
const pgErr = Object.assign(
new Error(
'new row for relation "transactions" violates check constraint "transactions_is_ignored_no_journal_entry"',
),
{ code: '23514' },
)
const res = errorResponse(pgErr, noopLogger, { requestId: 'req_ignored_tx' })
expect(res.status).toBe(409)
const body = await readEnvelope(res)
expect(body.error.code).toBe('TX_CATEGORIZE_IGNORED_CONFLICT')
expect(body.error.message).not.toContain('check constraint')
expect(body.error.details).toMatchObject({ pgCode: '23514' })
})
it('does not apply unrelated message heuristics to Postgres errors', async () => {
const pgErr = Object.assign(new Error('Invoice not found'), { code: 'P0001' })
const res = errorResponse(pgErr, noopLogger, { requestId: 'req_pg_unrelated' })
expect(res.status).toBe(500)
const body = await readEnvelope(res)
expect(body.error.code).toBe('INTERNAL_ERROR')
})
it('maps Postgres no-data-found to NOT_FOUND with pgCode', async () => {
const pgErr = Object.assign(new Error('invoice not found'), { code: 'P0002' })
const res = errorResponse(pgErr, noopLogger, { requestId: 'req_pg_not_found' })
expect(res.status).toBe(404)
const body = await readEnvelope(res)
expect(body.error.code).toBe('NOT_FOUND')
expect(body.error.details).toMatchObject({ pgCode: 'P0002' })
})
it('falls back to INTERNAL_ERROR for unknown shapes', async () => {
const res = errorResponse(new Error('boom'), noopLogger, { requestId: 'req_5' })
expect(res.status).toBe(500)
const body = await readEnvelope(res)
expect(body.error.code).toBe('INTERNAL_ERROR')
expect(body.error.requestId).toBe('req_5')
})
it('passes through entries with remediation hints', async () => {
const res = errorResponseFromCode('PROVIDER_AUTH_EXPIRED', noopLogger, { requestId: 'req_6' })
const body = await readEnvelope(res)
expect(body.error.code).toBe('PROVIDER_AUTH_EXPIRED')
expect(res.status).toBe(401)
})
it('errorResponseFromCode emits requestId in header', () => {
const res = errorResponseFromCode('NOT_FOUND', noopLogger, { requestId: 'req_7' })
expect(res.headers.get('X-Request-Id')).toBe('req_7')
})
it('preserves EntryDateOutsideFiscalPeriodError fields', async () => {
const err = new EntryDateOutsideFiscalPeriodError(
'2026-01-01',
'FY2025',
'2025-01-01',
'2025-12-31',
)
const body = await readEnvelope(errorResponse(err, noopLogger, { requestId: 'req_8' }))
expect(body.error.code).toBe('ENTRY_DATE_OUTSIDE_FISCAL_PERIOD')
expect(body.error.details).toMatchObject({
entryDate: '2026-01-01',
periodName: 'FY2025',
periodStart: '2025-01-01',
periodEnd: '2025-12-31',
})
})
})
+97
View File
@@ -0,0 +1,97 @@
/**
* Wrap a Supabase/PostgREST error without throwing away its identity.
*
* ## The bug this exists to prevent
*
* The idiom across the MCP tools was:
*
* if (error) throw new Error(`Database error: ${error.message}`)
*
* which keeps the prose and discards `code`. That matters because `code` is
* the SQLSTATE, and `isTransientFailure()` in lib/errors/get-structured-error.ts
* checks it FIRST: `57014` (statement timeout), `40001`, `40P01`, `53300` and
* friends are already in its TRANSIENT_SQLSTATES set. Strip the code and a
* retryable timeout arrives as an anonymous Error, misses every transient
* check, and resolves to UNKNOWN_ERROR: "Något gick fel. Försök igen."
*
* Measured on production over 60 days (bot actors excluded): 1 024 real-agent
* tool failures, 645 of them UNKNOWN_ERROR across 60 actors and 57 companies,
* 537 carrying that exact generic string. `gnubok_query_journal` alone failed
* 164 times at a p50 of 8 110 ms while every other failing tool sat between 1
* and 315 ms: a timeout signature that should have been TRANSIENT_ERROR all
* along. Agents cannot dispatch on "something went wrong", so they retried:
* 82 streaks of three or more identical failures, 462 wasted repeat calls,
* 53.1% of all real-agent error calls sitting inside a streak.
*
* ## Why attaching `code` is safe
*
* `extractCode()` only treats a code as an application error code when it
* matches /^[A-Z_]+$/. Every SQLSTATE contains digits (`57014`, `42P01`,
* `23505`), and so does every PostgREST code (`PGRST200`), so none of them can
* be mistaken for one of our own stable codes. The only behaviour this unlocks
* is the transient check that was always meant to run.
*/
/** The shape of a PostgrestError, narrowed to what we read. */
interface DatabaseErrorLike {
message?: string | null
code?: string | null
details?: string | null
hint?: string | null
}
/**
* An Error carrying the driver's SQLSTATE and diagnostics.
*
* `details` and `hint` are preserved for the server log, not for the agent:
* `getStructuredError` never reads them, so they cannot leak into a tool
* result. They are what makes a production failure debuggable after the fact.
*/
export interface DatabaseError extends Error {
code?: string
details?: string
hint?: string
}
/**
* @param error the `error` half of a supabase-js `{ data, error }` result
* @param context prefix for the message; defaults to the historical
* "Database error" so existing message-pattern matching in
* `inferCode()` keeps working unchanged. Pass `null` to keep
* the driver's message verbatim, for call sites whose exact
* text callers already depend on.
*/
export function dbError(error: unknown, context: string | null = 'Database error'): DatabaseError {
const source = (error ?? {}) as DatabaseErrorLike
const raw = typeof source.message === 'string' && source.message.trim() ? source.message.trim() : null
// Never render the literal "undefined". A driver-level failure (an aborted
// fetch, a gateway timeout) can arrive with no `message` at all, and
// "Database error: undefined" is the string that made these unsearchable in
// the first place.
const prefix = context ?? ''
const message = raw
? (prefix ? `${prefix}: ${raw}` : raw)
: `${prefix || 'Database error'}: no message from the database driver`
const wrapped = new Error(message) as DatabaseError
if (typeof source.code === 'string' && source.code) wrapped.code = source.code
if (typeof source.details === 'string' && source.details) wrapped.details = source.details
if (typeof source.hint === 'string' && source.hint) wrapped.hint = source.hint
return wrapped
}
/**
* A PII-safe identifier for what failed, for telemetry.
*
* A SQLSTATE is five characters of protocol vocabulary and carries no tenant
* data. A raw driver message can quote row values in a constraint violation,
* so it belongs in the server log, never in `event_log`.
*/
export function errorCauseTag(error: unknown): string | null {
if (error === null || error === undefined) return null
const source = error as DatabaseErrorLike & { name?: unknown }
if (typeof source.code === 'string' && source.code) return source.code
if (error instanceof Error && error.name && error.name !== 'Error') return error.name
return null
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff