* fix(enable-banking): read BBAN from AccountIdentification.other and store it on the account Enable Banking has no top-level `bban` key on AccountIdentification: a Swedish BBAN (clearing + account number) arrives as `other.identification` with `other.scheme_name = 'BBAN'`, or in `all_account_ids`. The client typed `bban?: string` and read `.bban`, so the value was always undefined: no connected account ever carried its clearing + account number, and domestic counterparty accounts on transactions were dropped. Type the identifiers per the OpenAPI spec, add extractBban() and pickAccountIdentifier(), read counterparty identifiers through the scheme list (IBAN, then BBAN/BGNR/PGNR, then anything), and store `bban` on StoredAccount from the OAuth callback. The external_id dedup scope stays IBAN-then-uid and is untouched. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * feat(invoices): named payee accounts on cash_accounts with a default per currency A company had exactly one set of payment instructions per invoice currency (company_settings.invoice_payment_accounts), picked by currency alone. A second SEK bank account, or a second bankgiro number, had nowhere to live. cash_accounts is already the per-company bank-account entity. Migration 20260903150000 adds the payee fields (bankgiro, plusgiro, clearing + account number, BBAN, BIC, Swish, foreign routing) plus invoice_payee, a small invoice_payee_defaults table (one default account per currency; one account may be the default for several currencies, a SEK account with an IBAN is the usual EUR payee), and a SECURITY DEFINER mirror that rewrites the legacy map and the SEK bank columns from the default accounts. Every existing reader (PDF, email, reminders, v1, MCP) keeps working; the three writers that only touched legacy columns (PUT /api/settings, v1 settings, MCP update_company_settings) now write through to the default account, so what an agent sets is what the PDF prints. Peppol PaymentMeans is built from the resolver instead of the raw legacy column. bg_pg is dropped (never read or written; NULL on every prod and staging row). Backfill lands only on existing cash accounts (primary, IBAN match, or the only enabled account in the currency). Entries with no target stay in the map as the resolver fallback and get an attach action in settings. New: POST /api/cash-accounts (manual bank account on the next free 19xx), PATCH /api/cash-accounts/[id] payee fields (owner/admin), GET/PUT /api/cash-accounts/payee-defaults. Settings page rewritten as an account list with per-currency defaults. Behandlingshistorik and the full archive cover the new table and columns. Verified on staging: migration applied (11 defaults landed), mirror trigger observed rewriting company_settings from a payee edit. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * feat(invoices): choose which bank account an invoice is paid to, frozen at issue Migration 20260903160000 adds invoices.payment_cash_account_id (FK to cash_accounts, SET NULL) and invoices.payment_details, the payee fields frozen when the account is chosen and refreshed at issue. Resolver: resolveInvoicePaymentAccount / companyWithInvoicePaymentAccount / assertInvoicePaymentAccountForRender take an optional override, and hasRequiredInvoicePaymentAccount reads it from the invoice row, so every surface (PDF, Swish QR, email, reminders, payment confirmation, Peppol, recurring, staged MCP send) prints the frozen payee when one exists and the company default per currency otherwise. Invoices that never chose an account behave exactly as before. Issue paths (mark-sent, send, v1 send, v1 mark-sent, Peppol send, recurring, MCP send and mark-sent) refresh the snapshot from the account as it is at issue; a chosen account that is disabled, un-flagged or unusable for the currency blocks with INVOICE_SEND_PAYMENT_ACCOUNT_INVALID. Writers: dashboard POST/PATCH, v1 create/update and MCP create_invoice accept payment_cash_account_id and validate it against the company's payee accounts (INVOICE_PAYEE_ACCOUNT_INVALID). Credit notes inherit the original's payee; copies carry the choice; preview-pdf renders the chosen account. The editor shows "Betalas till" under the currency when the company has two or more usable payee accounts for that currency. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * feat(invoices): book manual payments on the invoice's chosen bank account Manual mark-paid (dashboard, v1, MCP gnubok_mark_invoice_as_paid) and the booking dialog's proposed lines debited 1930 regardless of which bank account the invoice asked to be paid to. They now resolve the chosen payee account's ledger account (resolveInvoiceSettlementAccount) and fall back to 1930 only when no account was chosen or the row is gone. Bank-transaction matching keeps debiting the account the money landed on and does not filter by the chosen account; between equal-confidence candidates it prefers the invoice that asked to be paid to the landing account. Scores are untouched, so nothing new auto-matches. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * chore(invoices): keep the payload-size and phantom-column ceilings after the payee work Shorten the new gnubok_create_invoice argument description (tools/list payload was 29 bytes over the 60 kB budget), inline the cash-account payee UPDATE/INSERT payloads and the settings select strings as literals so the phantom-column scanner can read their columns, and reuse ACCOUNT_NUMBER_RE instead of a hand-rolled copy. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * fix(invoices): harden the payee model after review (admin-only payee columns, separate payee IBAN, company-scoped FK) Review findings from CodeRabbit, Superagent, the Swedish accounting review and three skeptic passes, resolved in one batch: Schema (both migrations are unshipped and edited in place): - cash_accounts.payee_iban: the printed IBAN is its own column. iban stays the bank identity written by every sync and used to re-pair on reconnect, so a sync can no longer rewrite an invoice instruction or resurrect a cleared IBAN. The backfill copies each currency entry verbatim onto the target account (IBAN match first, then primary), so every invoice keeps printing exactly what it printed before; the bank IBAN is never pushed onto invoices that did not carry one. - Payee columns are owner/admin-only at the database (BEFORE trigger, service role exempt): cash_accounts is member-writable for bank sync, and the SECURITY DEFINER mirror would otherwise have let a member rewrite where customers pay. - Revoking an account as payee or disabling it drops its defaults; deleting a default drops that currency from the map and clears the legacy SEK columns (an admin saying "nothing to print" must not keep printing a closed account). The mirror leaves the legacy SEK columns alone when the map has no SEK entry, so legacy-only companies are never wiped by a mirror run for another currency. - Audit and mirror triggers fire on the same column set; anon and authenticated can no longer execute the trigger-only definer functions. - invoices.payment_cash_account_id is a composite same-company FK with SET NULL scoped to the account column. Code: - Only 19xx bank accounts can be payee: PATCH, the defaults PUT (which now also requires enabled, payee-flagged and usable for the currency), resolveInvoicePayeeChoice, and the mark-paid settlement resolver (which also refuses disabled rows and logs every fallback to 1930). - createManualBankAccount excludes every ledger slot any row already holds (findFreeLedgerAccount treats a manual holder as free; this path inserts). - The legacy settings writers (PUT /api/settings, v1, MCP) write through to the account BEFORE updating company_settings and fail the request on error; the account is written before it is adopted as default so the mirror never sees an empty payee. - snapshotInvoicePayee: dry runs no longer persist; a failed snapshot write blocks issue (INVOICE_PAYEE_SNAPSHOT_FAILED). v1 mark-sent/mark-paid projections carry the payee columns; v1 create validates the payee before the dry-run return and echoes it in the preview. - pickAccountIdentifier: supplementary IBAN wins over a primary BBAN, and non-account schemes (card PANs) are never persisted. - Editor shows the payee select for a single usable account with no default; the booking dialog waits for cash accounts before proposing lines; a failed default write no longer hides a created account. - Behandlingshistorik names the account on created/deleted defaults. - Regenerated skills/accounted-api; MCP argument description trimmed under the tools/list payload ceiling. Declined: clearing legacy columns via a forward migration (the mirror now does it on delete); Swedish review's "show the debit account in the mark-paid UI" (the booking dialog already proposes and lets the user edit the debit line); manual ledger collision (UNIQUE exists, and the create path now rejects it with a clear error); Peppol aligning to the PDF value for companies whose legacy column had drifted from the map (the PDF is the customer-facing document; both now agree). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * fix(invoices): read NEW.invoice_payee only on the cash_accounts branch of the mirror trigger trg_mirror_invoice_payee_defaults fires for both tables; plpgsql resolves record fields per expression, so the combined condition failed with "record new has no field invoice_payee" whenever a default row changed, which took down every pg-real case on the payee tables. The revoke/disable check now sits inside its own TG_TABLE_NAME branch. The MCP settings executor test mocks the payee write-through like the settings route test already does. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * fix(invoices): keep member disables from revoking payee defaults, gate payee on 1920-1999, fit the MCP payload Cycle 3 of /resolve-pr on #2233. Superagent P1: the SECURITY DEFINER mirror trigger deleted an admin's invoice_payee_defaults rows whenever cash_accounts.enabled flipped to false, and enabled is member-writable (the bank picker's "Synkas ej"), so a member could undo an admin's payee decision. The trigger now drops defaults only on the admin-only invoice_payee true -> false revoke; the mirror trigger's WHEN no longer lists enabled. Disabled accounts stay out of the pick lists and the send gate already refuses an invoice that chose one. Applied to staging as the same function + trigger definition and probed inside a rolled-back block: disable keeps the default and the mirrored bankgiro, revoke clears both. pg-real: the admin-guard test ran three expectations inside one withUserContext transaction; the first raise aborted it and the next statement failed with "current transaction is aborted". One transaction per expectation now, and the member case also flips enabled to prove the column stays member-level. Swedish review: payee eligibility was /^19\d\d$/, which admits 1910 Kassa and the 1911-1919 tills. A customer pays to a giro or bank account, so isBankCashAccount, CreateCashAccountSchema.ledger_account and the PATCH route now require BAS 1920-1999; tests cover 1910 and 1919. Unit tests (3/4): the tools/list payload guard read 60 025, then 60 014 tokens after main merged #2166 and #2163 alongside this branch. The ceiling is not bumped and no read on this surface is a demotion candidate, so gnubok_create_invoice drops payment_cash_account_id; agent-created invoices print the per-currency default and v1 REST plus the editor keep the field. Recorded in DECISIONS.md. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * chore(migrations): move invoices_payment_cash_account to 20260903183000 after colliding with main's KPI migration origin/main merged 20260903160000_kpi_monthly_include_reversed_originals while this branch held the same version; identical versions abort the Supabase apply. Staging's schema_migrations row was moved to the new version with the file. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV * fix(invoices): gate invoice_payee on BAS 1920-1999 at the database, and unblock the typecheck ratchet Cycle 4 of /resolve-pr on #2233, on Emil's go. Swedish review: the 1920-1999 payee rule lived only in the routes. The cash_accounts_payee_admin_only trigger now also refuses invoice_payee on any other ledger (INVOICE_PAYEE_ACCOUNT_INVALID, 23514), whoever writes it, and the backfill only targets giro/bank rows, so a company whose single enabled cash_accounts row is a Stripe clearing account keeps its legacy bankgiro in company_settings instead of landing it on 1686. pg test covers insert and update on 1686 and 1910; the function was applied to staging and probed. Typecheck ratchet: main is red from two merges that landed with failing Checks, and every branch that syncs it inherits the errors. - #2242 added POST(req) calls to the fiscal-periods route test without the route params argument withRouteContext handlers take (25 errors in the file, baseline 23). All 25 calls now pass createMockRouteParams({}). - #2247 made SyncResult.requestedFromDate and historyNarrowed required; the 13 mockedSync results in the enable-banking accounts-route test lacked them. They now carry a fixed date and historyNarrowed: false. Both files' tests pass unchanged in behaviour. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(migrations): move invoices_payment_cash_account to 20260903193000 after colliding with main's party_promotion origin/main merged 20260903183000_party_promotion while this branch held the same version. Staging's schema_migrations row must follow (pending: the Supabase MCP was disconnected at the time of this commit). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
1023 lines
41 KiB
TypeScript
1023 lines
41 KiB
TypeScript
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
|
|
|
// Mock jwt module before importing api-client
|
|
const mockGenerateJWT = vi.fn().mockReturnValue('test-jwt-token')
|
|
vi.mock('../jwt', () => ({
|
|
generateJWT: (...args: unknown[]) => mockGenerateJWT(...args),
|
|
getAuthorizationHeader: () => `Bearer ${mockGenerateJWT()}`,
|
|
_resetTokenCache: vi.fn(),
|
|
}))
|
|
|
|
// Mock environment
|
|
vi.stubEnv('ENABLE_BANKING_API_URL', 'https://api.test.com')
|
|
|
|
import {
|
|
getASPSPs,
|
|
getAccountBalance,
|
|
getAccountBalances,
|
|
getAccountTransactions,
|
|
getAllTransactions,
|
|
getAllTransactionsWithRaw,
|
|
AspspUnavailableError,
|
|
convertTransaction,
|
|
extractBban,
|
|
deleteSession,
|
|
probeSessionHealth,
|
|
startAuthorization,
|
|
createSession,
|
|
type Transaction,
|
|
} from '../api-client'
|
|
|
|
describe('api-client', () => {
|
|
let fetchSpy: ReturnType<typeof vi.spyOn>
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
fetchSpy = vi.spyOn(globalThis, 'fetch')
|
|
})
|
|
|
|
afterEach(() => {
|
|
fetchSpy.mockRestore()
|
|
})
|
|
|
|
// -------------------------------------------------------------------------
|
|
// Timeout
|
|
// -------------------------------------------------------------------------
|
|
describe('timeout', () => {
|
|
it('aborts fetch after timeout', async () => {
|
|
fetchSpy.mockImplementation(
|
|
() => new Promise((_, reject) => {
|
|
// Simulate a hanging request: the AbortController will fire
|
|
setTimeout(() => reject(new DOMException('Aborted', 'AbortError')), 100)
|
|
})
|
|
)
|
|
|
|
await expect(getAccountBalances('acc-1')).rejects.toThrow('Aborted')
|
|
})
|
|
})
|
|
|
|
// -------------------------------------------------------------------------
|
|
// Balance-type selection
|
|
// -------------------------------------------------------------------------
|
|
describe('getAccountBalance', () => {
|
|
function balancesResponse(balances: unknown[]): Response {
|
|
return new Response(JSON.stringify({ balances }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
}
|
|
|
|
it('returns booked (closingBooked) plus available (interimAvailable) from one response', async () => {
|
|
fetchSpy.mockResolvedValueOnce(
|
|
balancesResponse([
|
|
{ balance_type: 'interimAvailable', balance_amount: { amount: '900.50', currency: 'SEK' } },
|
|
{ balance_type: 'closingBooked', balance_amount: { amount: '1000.00', currency: 'SEK' }, reference_date: '2026-09-01' },
|
|
])
|
|
)
|
|
|
|
const result = await getAccountBalance('acc-1')
|
|
expect(result).toEqual({ amount: 1000, date: '2026-09-01', available: 900.5 })
|
|
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
})
|
|
|
|
it('accepts ISO 20022 codes (CLBD/ITAV) case-insensitively', async () => {
|
|
fetchSpy.mockResolvedValueOnce(
|
|
balancesResponse([
|
|
{ balance_type: 'ITAV', balance_amount: { amount: '450.25', currency: 'SEK' } },
|
|
{ balance_type: 'CLBD', balance_amount: { amount: '500.00', currency: 'SEK' }, reference_date: '2026-09-01' },
|
|
])
|
|
)
|
|
|
|
const result = await getAccountBalance('acc-1')
|
|
expect(result?.amount).toBe(500)
|
|
expect(result?.available).toBe(450.25)
|
|
})
|
|
|
|
it('returns available: null when the bank reports no available type', async () => {
|
|
fetchSpy.mockResolvedValueOnce(
|
|
balancesResponse([
|
|
{ balance_type: 'closingBooked', balance_amount: { amount: '1000.00', currency: 'SEK' }, reference_date: '2026-09-01' },
|
|
])
|
|
)
|
|
|
|
const result = await getAccountBalance('acc-1')
|
|
expect(result).toEqual({ amount: 1000, date: '2026-09-01', available: null })
|
|
})
|
|
|
|
it('falls back to the first balance for booked, never to an available type by preference', async () => {
|
|
// Only an unknown type: the pre-existing first-entry fallback applies.
|
|
fetchSpy.mockResolvedValueOnce(
|
|
balancesResponse([
|
|
{ balance_type: 'somethingElse', balance_amount: { amount: '42.00', currency: 'SEK' }, reference_date: '2026-08-31' },
|
|
])
|
|
)
|
|
|
|
const result = await getAccountBalance('acc-1')
|
|
expect(result).toEqual({ amount: 42, date: '2026-08-31', available: null })
|
|
})
|
|
|
|
it('prefers interimBooked (ITBD) over the generic first-entry fallback', async () => {
|
|
fetchSpy.mockResolvedValueOnce(
|
|
balancesResponse([
|
|
{ balance_type: 'somethingElse', balance_amount: { amount: '1.00', currency: 'SEK' } },
|
|
{ balance_type: 'ITBD', balance_amount: { amount: '3.00', currency: 'SEK' }, reference_date: '2026-09-01' },
|
|
])
|
|
)
|
|
|
|
const result = await getAccountBalance('acc-1')
|
|
expect(result?.amount).toBe(3)
|
|
})
|
|
|
|
it('returns null (never a fabricated 0) when the bank reports no balances at all', async () => {
|
|
fetchSpy.mockResolvedValueOnce(balancesResponse([]))
|
|
const result = await getAccountBalance('acc-1')
|
|
expect(result).toBeNull()
|
|
})
|
|
|
|
it('prefers expected over the first entry when closingBooked is missing', async () => {
|
|
fetchSpy.mockResolvedValueOnce(
|
|
balancesResponse([
|
|
{ balance_type: 'other', balance_amount: { amount: '1.00', currency: 'SEK' } },
|
|
{ balance_type: 'expected', balance_amount: { amount: '2.00', currency: 'SEK' }, reference_date: '2026-09-01' },
|
|
])
|
|
)
|
|
|
|
const result = await getAccountBalance('acc-1')
|
|
expect(result?.amount).toBe(2)
|
|
})
|
|
})
|
|
|
|
// -------------------------------------------------------------------------
|
|
// Retry
|
|
// -------------------------------------------------------------------------
|
|
describe('retry', () => {
|
|
it('retries on 503 and succeeds', async () => {
|
|
const failResponse = new Response('Service Unavailable', { status: 503 })
|
|
const successResponse = new Response(JSON.stringify({ balances: [] }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
|
|
fetchSpy
|
|
.mockResolvedValueOnce(failResponse)
|
|
.mockResolvedValueOnce(failResponse)
|
|
.mockResolvedValueOnce(successResponse)
|
|
|
|
const result = await getAccountBalances('acc-1')
|
|
expect(result).toEqual([])
|
|
expect(fetchSpy).toHaveBeenCalledTimes(3)
|
|
})
|
|
|
|
it('retries on AbortError (timeout) and succeeds', async () => {
|
|
const abortError = new DOMException('Aborted', 'AbortError')
|
|
const successResponse = new Response(JSON.stringify({ aspsps: [{ name: 'TestBank', country: 'SE' }] }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
|
|
fetchSpy
|
|
.mockRejectedValueOnce(abortError)
|
|
.mockResolvedValueOnce(successResponse)
|
|
|
|
const result = await getASPSPs('SE')
|
|
expect(result).toEqual([{ name: 'TestBank', country: 'SE' }])
|
|
expect(fetchSpy).toHaveBeenCalledTimes(2)
|
|
})
|
|
|
|
it('does not retry a 429 whose body signals a daily quota', async () => {
|
|
// PSD2 unattended consents cap balance calls per DAY (observed body:
|
|
// "Consent daily limit 4 is exceeded"). A retry a second later cannot
|
|
// succeed against a daily quota, so it must fail fast.
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
|
|
fetchSpy.mockResolvedValueOnce(
|
|
new Response('{"message":"Consent daily limit 4 is exceeded"}', { status: 429 })
|
|
)
|
|
|
|
await expect(getAccountBalances('acc-1')).rejects.toThrow(
|
|
'Failed to get account balances (429)'
|
|
)
|
|
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
|
|
warnSpy.mockRestore()
|
|
errorSpy.mockRestore()
|
|
})
|
|
|
|
it('still retries a 429 without a daily-limit body (transient rate limit)', async () => {
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
|
|
fetchSpy
|
|
.mockResolvedValueOnce(new Response('Too Many Requests', { status: 429 }))
|
|
.mockResolvedValueOnce(
|
|
new Response(JSON.stringify({ balances: [] }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
)
|
|
|
|
const result = await getAccountBalances('acc-1')
|
|
expect(result).toEqual([])
|
|
expect(fetchSpy).toHaveBeenCalledTimes(2)
|
|
|
|
warnSpy.mockRestore()
|
|
})
|
|
|
|
it('does not retry on 400 errors', async () => {
|
|
const badRequest = new Response('Bad Request', { status: 400 })
|
|
fetchSpy.mockResolvedValueOnce(badRequest)
|
|
|
|
// getAccountTransactions throws on non-ok response
|
|
await expect(getAccountTransactions('acc-1')).rejects.toThrow('Failed to get transactions')
|
|
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
})
|
|
})
|
|
|
|
// -------------------------------------------------------------------------
|
|
// Pagination cap
|
|
// -------------------------------------------------------------------------
|
|
describe('pagination cap', () => {
|
|
it('stops at MAX_PAGINATION_PAGES', async () => {
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
|
|
// Every response returns a continuation_key
|
|
fetchSpy.mockImplementation(() => {
|
|
return Promise.resolve(
|
|
new Response(
|
|
JSON.stringify({
|
|
transactions: [{ transaction_amount: { amount: '100', currency: 'SEK' } }],
|
|
continuation_key: 'keep-going',
|
|
}),
|
|
{ status: 200, headers: { 'Content-Type': 'application/json' } }
|
|
)
|
|
)
|
|
})
|
|
|
|
const result = await getAllTransactions('acc-1', '2024-01-01', '2024-12-31')
|
|
|
|
// Should have exactly 100 transactions (1 per page, 100 pages)
|
|
expect(result).toHaveLength(100)
|
|
expect(fetchSpy).toHaveBeenCalledTimes(100)
|
|
expect(warnSpy).toHaveBeenCalledWith(
|
|
expect.stringContaining('Pagination cap reached')
|
|
)
|
|
|
|
warnSpy.mockRestore()
|
|
})
|
|
})
|
|
|
|
// -------------------------------------------------------------------------
|
|
// getAllTransactionsWithRaw
|
|
// -------------------------------------------------------------------------
|
|
describe('getAllTransactionsWithRaw', () => {
|
|
it('returns both transactions and raw pages', async () => {
|
|
const page1 = {
|
|
transactions: [{ transaction_amount: { amount: '100', currency: 'SEK' } }],
|
|
continuation_key: 'page2',
|
|
}
|
|
const page2 = {
|
|
transactions: [{ transaction_amount: { amount: '200', currency: 'SEK' } }],
|
|
}
|
|
|
|
fetchSpy
|
|
.mockResolvedValueOnce(
|
|
new Response(JSON.stringify(page1), { status: 200, headers: { 'Content-Type': 'application/json' } })
|
|
)
|
|
.mockResolvedValueOnce(
|
|
new Response(JSON.stringify(page2), { status: 200, headers: { 'Content-Type': 'application/json' } })
|
|
)
|
|
|
|
const result = await getAllTransactionsWithRaw('acc-1', '2024-01-01', '2024-12-31')
|
|
|
|
expect(result.transactions).toHaveLength(2)
|
|
expect(result.rawPages).toHaveLength(2)
|
|
expect(JSON.parse(result.rawPages[0])).toEqual(page1)
|
|
expect(JSON.parse(result.rawPages[1])).toEqual(page2)
|
|
})
|
|
|
|
it('appends strategy=longest to the request URL when supplied', async () => {
|
|
fetchSpy.mockResolvedValueOnce(
|
|
new Response(JSON.stringify({ transactions: [] }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
)
|
|
|
|
await getAllTransactionsWithRaw('acc-1', '2024-01-01', '2024-12-31', 'longest')
|
|
|
|
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
const requestedUrl = fetchSpy.mock.calls[0][0] as string
|
|
expect(requestedUrl).toContain('strategy=longest')
|
|
expect(requestedUrl).toContain('date_from=2024-01-01')
|
|
expect(requestedUrl).toContain('date_to=2024-12-31')
|
|
})
|
|
|
|
it('omits the strategy param when not supplied', async () => {
|
|
fetchSpy.mockResolvedValueOnce(
|
|
new Response(JSON.stringify({ transactions: [] }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
)
|
|
|
|
await getAllTransactionsWithRaw('acc-1', '2024-01-01', '2024-12-31')
|
|
|
|
const requestedUrl = fetchSpy.mock.calls[0][0] as string
|
|
expect(requestedUrl).not.toContain('strategy=')
|
|
})
|
|
|
|
it('falls back to no-strategy on 400 and retries the same page', async () => {
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
|
|
fetchSpy
|
|
.mockResolvedValueOnce(
|
|
new Response('Invalid strategy', { status: 400 })
|
|
)
|
|
.mockResolvedValueOnce(
|
|
new Response(JSON.stringify({ transactions: [{ transaction_amount: { amount: '50', currency: 'SEK' } }] }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
)
|
|
|
|
const result = await getAllTransactionsWithRaw('acc-1', '2024-01-01', '2024-12-31', 'longest')
|
|
|
|
expect(result.transactions).toHaveLength(1)
|
|
expect(fetchSpy).toHaveBeenCalledTimes(2)
|
|
|
|
const firstUrl = fetchSpy.mock.calls[0][0] as string
|
|
const secondUrl = fetchSpy.mock.calls[1][0] as string
|
|
expect(firstUrl).toContain('strategy=longest')
|
|
expect(secondUrl).not.toContain('strategy=')
|
|
|
|
expect(warnSpy).toHaveBeenCalledWith(
|
|
'[enable-banking] strategy rejected by API, retrying without strategy',
|
|
expect.objectContaining({ strategy: 'longest' })
|
|
)
|
|
|
|
warnSpy.mockRestore()
|
|
})
|
|
|
|
// Danske Bank rejects a history window beyond its ~90-day PSD2 limit with a
|
|
// blanket ASPSP_ERROR rather than clamping. The window must be narrowed.
|
|
const ASPSP_ERROR_BODY =
|
|
'{"code":400,"message":"Error interacting with ASPSP","detail":"Unknown error","error":"ASPSP_ERROR"}'
|
|
|
|
it('narrows date_from when the ASPSP rejects the history window', async () => {
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
|
|
fetchSpy
|
|
// strategy=longest, full 120-day window → ASPSP_ERROR
|
|
.mockResolvedValueOnce(new Response(ASPSP_ERROR_BODY, { status: 400 }))
|
|
// strategy dropped, still full window → ASPSP_ERROR (window is the problem)
|
|
.mockResolvedValueOnce(new Response(ASPSP_ERROR_BODY, { status: 400 }))
|
|
// narrowed to 90 days before date_to → success
|
|
.mockResolvedValueOnce(
|
|
new Response(
|
|
JSON.stringify({ transactions: [{ transaction_amount: { amount: '42', currency: 'SEK' } }] }),
|
|
{ status: 200, headers: { 'Content-Type': 'application/json' } }
|
|
)
|
|
)
|
|
|
|
const result = await getAllTransactionsWithRaw('acc-1', '2026-02-07', '2026-06-07', 'longest')
|
|
|
|
expect(result.transactions).toHaveLength(1)
|
|
expect(fetchSpy).toHaveBeenCalledTimes(3)
|
|
|
|
const urls = fetchSpy.mock.calls.map((c: unknown[]) => c[0] as string)
|
|
expect(urls[0]).toContain('date_from=2026-02-07')
|
|
expect(urls[0]).toContain('strategy=longest')
|
|
expect(urls[1]).toContain('date_from=2026-02-07')
|
|
expect(urls[1]).not.toContain('strategy=')
|
|
// 90 days before 2026-06-07
|
|
expect(urls[2]).toContain('date_from=2026-03-09')
|
|
expect(urls[2]).toContain('date_to=2026-06-07')
|
|
|
|
expect(warnSpy).toHaveBeenCalledWith(
|
|
'[enable-banking] ASPSP rejected history window, retrying with narrower date_from',
|
|
expect.objectContaining({ previousDateFrom: '2026-02-07', nextDateFrom: '2026-03-09' })
|
|
)
|
|
|
|
warnSpy.mockRestore()
|
|
})
|
|
|
|
it('steps through successive narrower windows until one succeeds', async () => {
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
|
|
fetchSpy
|
|
.mockResolvedValueOnce(new Response(ASPSP_ERROR_BODY, { status: 400 })) // full window
|
|
.mockResolvedValueOnce(new Response(ASPSP_ERROR_BODY, { status: 400 })) // 90 days
|
|
.mockResolvedValueOnce(new Response(ASPSP_ERROR_BODY, { status: 400 })) // 60 days
|
|
.mockResolvedValueOnce(
|
|
new Response(JSON.stringify({ transactions: [] }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
) // 30 days → success
|
|
|
|
await getAllTransactionsWithRaw('acc-1', '2026-02-07', '2026-06-07')
|
|
|
|
expect(fetchSpy).toHaveBeenCalledTimes(4)
|
|
const urls = fetchSpy.mock.calls.map((c: unknown[]) => c[0] as string)
|
|
expect(urls[0]).toContain('date_from=2026-02-07')
|
|
expect(urls[1]).toContain('date_from=2026-03-09') // 90 days before date_to
|
|
expect(urls[2]).toContain('date_from=2026-04-08') // 60 days
|
|
expect(urls[3]).toContain('date_from=2026-05-08') // 30 days
|
|
|
|
warnSpy.mockRestore()
|
|
})
|
|
|
|
it('does not narrow the window on a non-ASPSP 400', async () => {
|
|
fetchSpy.mockResolvedValueOnce(new Response('{"error":"INVALID_REQUEST"}', { status: 400 }))
|
|
|
|
await expect(
|
|
getAllTransactionsWithRaw('acc-1', '2026-02-07', '2026-06-07')
|
|
).rejects.toThrow('Failed to get transactions (400)')
|
|
|
|
// No strategy to drop + not an ASPSP error → fail fast, no retries.
|
|
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
})
|
|
|
|
it('throws once every narrower window is exhausted', async () => {
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
|
|
// Fresh Response per call: a body can only be read once.
|
|
fetchSpy.mockImplementation(() => Promise.resolve(new Response(ASPSP_ERROR_BODY, { status: 400 })))
|
|
|
|
const failure = await getAllTransactionsWithRaw('acc-1', '2026-02-07', '2026-06-07').catch((e) => e)
|
|
expect(failure).toBeInstanceOf(AspspUnavailableError)
|
|
expect(failure.message).toContain('Failed to get transactions (400)')
|
|
// Every narrower window refused too: the bank is refusing, not the width.
|
|
expect(failure.reason).toBe('ladder-exhausted')
|
|
|
|
// full window + 90 + 60 + 30 = 4 attempts, then give up
|
|
expect(fetchSpy).toHaveBeenCalledTimes(4)
|
|
|
|
warnSpy.mockRestore()
|
|
errorSpy.mockRestore()
|
|
})
|
|
|
|
it('reports the requested and the effective date_from, and whether the window was narrowed', async () => {
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
fetchSpy
|
|
.mockResolvedValueOnce(new Response(ASPSP_ERROR_BODY, { status: 400 })) // full window
|
|
.mockResolvedValueOnce(
|
|
new Response(JSON.stringify({ transactions: [] }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
) // 90 days → success
|
|
|
|
const result = await getAllTransactionsWithRaw('acc-1', '2026-02-07', '2026-06-07')
|
|
expect(result).toMatchObject({
|
|
requestedDateFrom: '2026-02-07',
|
|
effectiveDateFrom: '2026-03-09',
|
|
narrowed: true,
|
|
})
|
|
warnSpy.mockRestore()
|
|
})
|
|
|
|
it('reports narrowed: false when the first call succeeds', async () => {
|
|
fetchSpy.mockResolvedValueOnce(
|
|
new Response(JSON.stringify({ transactions: [] }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
)
|
|
const result = await getAllTransactionsWithRaw('acc-1', '2026-02-07', '2026-06-07')
|
|
expect(result).toMatchObject({
|
|
requestedDateFrom: '2026-02-07',
|
|
effectiveDateFrom: '2026-02-07',
|
|
narrowed: false,
|
|
})
|
|
})
|
|
|
|
// Issue #2202: Länsförsäkringar answered a 4-month window at 23:07 (after
|
|
// narrowing to 06-26) and refused every rung of the same request at
|
|
// 23:14. ASPSP_ERROR is the same string for "too wide" and "the bank is
|
|
// refusing right now"; what the account has accepted before is the
|
|
// signal that tells them apart.
|
|
describe('accepted history width', () => {
|
|
it('a rejected window no wider than the accepted width stops after ONE call, as the bank being unavailable', async () => {
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
fetchSpy.mockImplementation(() => Promise.resolve(new Response(ASPSP_ERROR_BODY, { status: 400 })))
|
|
|
|
// 2026-02-07 .. 2026-06-07 is 120 days; the bank has answered 120 before.
|
|
const failure = await getAllTransactionsWithRaw('acc-1', '2026-02-07', '2026-06-07', undefined, {
|
|
acceptedHistoryDays: 120,
|
|
}).catch((e) => e)
|
|
|
|
expect(failure).toBeInstanceOf(AspspUnavailableError)
|
|
expect(failure.reason).toBe('window-already-accepted')
|
|
expect(failure.dateFrom).toBe('2026-02-07')
|
|
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
warnSpy.mockRestore()
|
|
})
|
|
|
|
it('a rejected wider window jumps straight to the accepted width, then stops', async () => {
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
fetchSpy.mockImplementation(() => Promise.resolve(new Response(ASPSP_ERROR_BODY, { status: 400 })))
|
|
|
|
// Accepted 54 days before; asking for 120. No 90/60/30 ladder walk.
|
|
const failure = await getAllTransactionsWithRaw('acc-1', '2026-02-07', '2026-06-07', undefined, {
|
|
acceptedHistoryDays: 54,
|
|
}).catch((e) => e)
|
|
|
|
expect(failure).toBeInstanceOf(AspspUnavailableError)
|
|
expect(failure.reason).toBe('window-already-accepted')
|
|
expect(fetchSpy).toHaveBeenCalledTimes(2)
|
|
const urls = fetchSpy.mock.calls.map((c: unknown[]) => c[0] as string)
|
|
expect(urls[0]).toContain('date_from=2026-02-07')
|
|
expect(urls[1]).toContain('date_from=2026-04-14') // 54 days before 2026-06-07
|
|
warnSpy.mockRestore()
|
|
})
|
|
|
|
it('a rejected wider window that succeeds at the accepted width is reported as narrowed to it', async () => {
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
fetchSpy
|
|
.mockResolvedValueOnce(new Response(ASPSP_ERROR_BODY, { status: 400 }))
|
|
.mockResolvedValueOnce(
|
|
new Response(JSON.stringify({ transactions: [] }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
)
|
|
|
|
const result = await getAllTransactionsWithRaw('acc-1', '2026-02-07', '2026-06-07', undefined, {
|
|
acceptedHistoryDays: 54,
|
|
})
|
|
expect(result).toMatchObject({ effectiveDateFrom: '2026-04-14', narrowed: true })
|
|
expect(fetchSpy).toHaveBeenCalledTimes(2)
|
|
warnSpy.mockRestore()
|
|
})
|
|
|
|
it('still drops an unsupported strategy before judging the window', async () => {
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
fetchSpy.mockImplementation(() => Promise.resolve(new Response(ASPSP_ERROR_BODY, { status: 400 })))
|
|
|
|
const failure = await getAllTransactionsWithRaw('acc-1', '2026-02-07', '2026-06-07', 'longest', {
|
|
acceptedHistoryDays: 120,
|
|
}).catch((e) => e)
|
|
|
|
expect(failure).toBeInstanceOf(AspspUnavailableError)
|
|
// strategy=longest, then the same window without strategy, then stop.
|
|
expect(fetchSpy).toHaveBeenCalledTimes(2)
|
|
warnSpy.mockRestore()
|
|
})
|
|
|
|
it('getAllTransactions applies the same policy', async () => {
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
fetchSpy.mockImplementation(() => Promise.resolve(new Response(ASPSP_ERROR_BODY, { status: 400 })))
|
|
|
|
const failure = await getAllTransactions('acc-1', '2026-02-07', '2026-06-07', undefined, {
|
|
acceptedHistoryDays: 120,
|
|
}).catch((e) => e)
|
|
|
|
expect(failure).toBeInstanceOf(AspspUnavailableError)
|
|
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
warnSpy.mockRestore()
|
|
errorSpy.mockRestore()
|
|
})
|
|
})
|
|
})
|
|
|
|
// -------------------------------------------------------------------------
|
|
// getAllTransactions: same first-page fallbacks via the paginated path
|
|
// -------------------------------------------------------------------------
|
|
describe('getAllTransactions fallbacks', () => {
|
|
const ASPSP_ERROR_BODY =
|
|
'{"code":400,"message":"Error interacting with ASPSP","detail":"Unknown error","error":"ASPSP_ERROR"}'
|
|
|
|
it('narrows the window when the ASPSP rejects the history range', async () => {
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
|
|
fetchSpy
|
|
.mockResolvedValueOnce(new Response(ASPSP_ERROR_BODY, { status: 400 })) // full window
|
|
.mockResolvedValueOnce(
|
|
new Response(
|
|
JSON.stringify({ transactions: [{ transaction_amount: { amount: '10', currency: 'SEK' } }] }),
|
|
{ status: 200, headers: { 'Content-Type': 'application/json' } }
|
|
)
|
|
) // narrowed to 90 days → success
|
|
|
|
const result = await getAllTransactions('acc-1', '2026-02-07', '2026-06-07')
|
|
|
|
expect(result).toHaveLength(1)
|
|
expect(fetchSpy).toHaveBeenCalledTimes(2)
|
|
const urls = fetchSpy.mock.calls.map((c: unknown[]) => c[0] as string)
|
|
expect(urls[0]).toContain('date_from=2026-02-07')
|
|
expect(urls[1]).toContain('date_from=2026-03-09') // 90 days before date_to
|
|
|
|
warnSpy.mockRestore()
|
|
})
|
|
|
|
it('drops the strategy then narrows the window (Danske flow)', async () => {
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
|
|
fetchSpy
|
|
.mockResolvedValueOnce(new Response(ASPSP_ERROR_BODY, { status: 400 })) // strategy=longest
|
|
.mockResolvedValueOnce(new Response(ASPSP_ERROR_BODY, { status: 400 })) // no strategy, full window
|
|
.mockResolvedValueOnce(
|
|
new Response(JSON.stringify({ transactions: [] }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
) // narrowed to 90 days → success
|
|
|
|
await getAllTransactions('acc-1', '2026-02-07', '2026-06-07', 'longest')
|
|
|
|
expect(fetchSpy).toHaveBeenCalledTimes(3)
|
|
const urls = fetchSpy.mock.calls.map((c: unknown[]) => c[0] as string)
|
|
expect(urls[0]).toContain('strategy=longest')
|
|
expect(urls[1]).not.toContain('strategy=')
|
|
expect(urls[1]).toContain('date_from=2026-02-07')
|
|
expect(urls[2]).toContain('date_from=2026-03-09')
|
|
|
|
warnSpy.mockRestore()
|
|
})
|
|
|
|
it('does not rewrite the query mid-pagination', async () => {
|
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
|
|
fetchSpy
|
|
.mockResolvedValueOnce(
|
|
new Response(
|
|
JSON.stringify({
|
|
transactions: [{ transaction_amount: { amount: '5', currency: 'SEK' } }],
|
|
continuation_key: 'page2',
|
|
}),
|
|
{ status: 200, headers: { 'Content-Type': 'application/json' } }
|
|
)
|
|
) // page 1 ok, hands back a continuation_key
|
|
.mockResolvedValueOnce(new Response(ASPSP_ERROR_BODY, { status: 400 })) // page 2 fails
|
|
|
|
// A continuation_key is scoped to its window, so page 2 must not narrow:
|
|
// it fails fast instead.
|
|
await expect(
|
|
getAllTransactions('acc-1', '2026-02-07', '2026-06-07')
|
|
).rejects.toThrow('Failed to get transactions (400)')
|
|
expect(fetchSpy).toHaveBeenCalledTimes(2)
|
|
|
|
errorSpy.mockRestore()
|
|
})
|
|
})
|
|
})
|
|
|
|
// -------------------------------------------------------------------------
|
|
// JWT cache tests
|
|
// -------------------------------------------------------------------------
|
|
describe('JWT cache', () => {
|
|
it('reuses cached token within validity window', async () => {
|
|
// Reset mocks and re-import to test cache behavior
|
|
vi.resetModules()
|
|
const jwtCallCount = { count: 0 }
|
|
|
|
vi.doMock('../jwt', () => ({
|
|
generateJWT: () => {
|
|
jwtCallCount.count++
|
|
return 'cached-token'
|
|
},
|
|
getAuthorizationHeader: () => {
|
|
// Simulate cached behavior: first call generates, subsequent calls reuse
|
|
jwtCallCount.count++
|
|
return `Bearer cached-token`
|
|
},
|
|
_resetTokenCache: vi.fn(),
|
|
}))
|
|
|
|
// The actual cache test is in jwt.ts: we verify the cache function exists
|
|
const jwt = await import('../jwt')
|
|
expect(typeof jwt._resetTokenCache).toBe('function')
|
|
})
|
|
})
|
|
|
|
describe('convertTransaction', () => {
|
|
function makeTx(overrides: Partial<Transaction> = {}): Transaction {
|
|
return {
|
|
transaction_amount: { amount: '250.00', currency: 'SEK' },
|
|
credit_debit_indicator: 'DBIT',
|
|
booking_date: '2024-06-15',
|
|
...overrides,
|
|
}
|
|
}
|
|
|
|
it('uses remittance_information when present', () => {
|
|
const tx = makeTx({ remittance_information: ['Faktura 123', ' '] })
|
|
expect(convertTransaction(tx, 'SEK').description).toBe('Faktura 123')
|
|
})
|
|
|
|
it('falls back to the counterparty name when remittance is empty', () => {
|
|
const out = makeTx({ remittance_information: [' '], creditor_name: 'Telia AB' })
|
|
expect(convertTransaction(out, 'SEK').description).toBe('Telia AB')
|
|
})
|
|
|
|
it('derives a Swedish label from bank_transaction_code when remittance and counterparty are both absent', () => {
|
|
const tx = makeTx({ bank_transaction_code: 'PMNT-CCRD-POSD', merchant_category_code: '5411' })
|
|
// MCC 5411 wins (most specific).
|
|
expect(convertTransaction(tx, 'SEK').description).toBe('Inköp dagligvaror')
|
|
})
|
|
|
|
it('uses the ISO family label when only bank_transaction_code is present', () => {
|
|
const tx = makeTx({ bank_transaction_code: 'PMNT/CCRD' })
|
|
expect(convertTransaction(tx, 'SEK').description).toBe('Kortköp')
|
|
})
|
|
|
|
it('falls back to the Swedish neutral (never English "Unknown") when nothing is recognized', () => {
|
|
const tx = makeTx({})
|
|
expect(convertTransaction(tx, 'SEK').description).toBe('Okänd transaktion')
|
|
})
|
|
|
|
it('carries the ISO codes through onto the converted transaction', () => {
|
|
const tx = makeTx({ bank_transaction_code: 'PMNT/RCDT', proprietary_bank_transaction_code: 'XB' })
|
|
const out = convertTransaction(tx, 'SEK')
|
|
expect(out.bank_transaction_code).toBe('PMNT/RCDT')
|
|
expect(out.proprietary_bank_transaction_code).toBe('XB')
|
|
})
|
|
|
|
// Enable Banking has no `bban` key on AccountIdentification: a Swedish
|
|
// BBAN arrives as other.identification with scheme_name BBAN. The earlier
|
|
// `.bban` read was always undefined, so domestic counterparties were lost.
|
|
it('reads a Swedish BBAN counterparty from other.identification', () => {
|
|
const tx = makeTx({
|
|
credit_debit_indicator: 'CRDT',
|
|
debtor_account: { other: { identification: '50001234567', scheme_name: 'BBAN' } },
|
|
})
|
|
expect(convertTransaction(tx, 'SEK').counterparty_account).toBe('50001234567')
|
|
})
|
|
|
|
it('prefers IBAN over a domestic identifier, and a Bankgiro from the additional list over nothing', () => {
|
|
const withIban = makeTx({
|
|
creditor_account: { iban: 'SE4550000000058398257466', other: { identification: '1234567', scheme_name: 'BGNR' } },
|
|
})
|
|
expect(convertTransaction(withIban, 'SEK').counterparty_account).toBe('SE4550000000058398257466')
|
|
|
|
const bgOnly = makeTx({
|
|
creditor_account_additional_identification: [{ identification: '5050-1234', scheme_name: 'BGNR' }],
|
|
})
|
|
expect(convertTransaction(bgOnly, 'SEK').counterparty_account).toBe('5050-1234')
|
|
})
|
|
|
|
it('takes a supplementary IBAN over a primary BBAN, and never persists a card PAN or other non-account scheme', () => {
|
|
const bbanWithIban = makeTx({
|
|
creditor_account: { other: { identification: '50001234567', scheme_name: 'BBAN' } },
|
|
creditor_account_additional_identification: [{ identification: 'SE4550000000058398257466', scheme_name: 'IBAN' }],
|
|
})
|
|
expect(convertTransaction(bbanWithIban, 'SEK').counterparty_account).toBe('SE4550000000058398257466')
|
|
|
|
const cardOnly = makeTx({
|
|
creditor_account: { other: { identification: '4571********1234', scheme_name: 'CPAN' } },
|
|
creditor_account_additional_identification: [{ identification: '12345', scheme_name: 'CUST' }],
|
|
})
|
|
expect(convertTransaction(cardOnly, 'SEK').counterparty_account).toBeUndefined()
|
|
})
|
|
})
|
|
|
|
describe('extractBban', () => {
|
|
it('returns the primary BBAN without whitespace', () => {
|
|
expect(extractBban({ account_id: { other: { identification: '5000 1234567', scheme_name: 'BBAN' } } }))
|
|
.toBe('50001234567')
|
|
})
|
|
|
|
it('falls back to all_account_ids when the primary identifier is an IBAN', () => {
|
|
expect(extractBban({
|
|
account_id: { iban: 'SE4550000000058398257466' },
|
|
all_account_ids: [
|
|
{ identification: 'SE4550000000058398257466', scheme_name: 'IBAN' },
|
|
{ identification: '50001234567', scheme_name: 'BBAN' },
|
|
],
|
|
})).toBe('50001234567')
|
|
})
|
|
|
|
it('is undefined when the ASPSP sent no BBAN', () => {
|
|
expect(extractBban({ account_id: { iban: 'SE4550000000058398257466' } })).toBeUndefined()
|
|
expect(extractBban({ account_id: { other: { identification: '1234567', scheme_name: 'BGNR' } } })).toBeUndefined()
|
|
})
|
|
})
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// probeSessionHealth: nightly liveness check
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('probeSessionHealth', () => {
|
|
let fetchSpy: ReturnType<typeof vi.spyOn>
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
fetchSpy = vi.spyOn(globalThis, 'fetch')
|
|
})
|
|
|
|
afterEach(() => {
|
|
fetchSpy.mockRestore()
|
|
})
|
|
|
|
function respond(status: number, body: unknown) {
|
|
fetchSpy.mockResolvedValue(
|
|
new Response(typeof body === 'string' ? body : JSON.stringify(body), { status }),
|
|
)
|
|
}
|
|
|
|
it('reports alive for an authorized session', async () => {
|
|
respond(200, { session_id: 's1', status: 'AUTHORIZED' })
|
|
expect(await probeSessionHealth('s1')).toBe('alive')
|
|
})
|
|
|
|
it('reports dead for a session the bank closed', async () => {
|
|
respond(200, { session_id: 's1', status: 'CLOSED' })
|
|
expect(await probeSessionHealth('s1')).toBe('dead')
|
|
})
|
|
|
|
it('reports dead when the session record is gone', async () => {
|
|
respond(404, { message: 'Not found' })
|
|
expect(await probeSessionHealth('s1')).toBe('dead')
|
|
})
|
|
|
|
it('reports dead on a 401 carrying a session-expiry signal', async () => {
|
|
respond(401, { error: 'SESSION_EXPIRED' })
|
|
expect(await probeSessionHealth('s1')).toBe('dead')
|
|
})
|
|
|
|
it('reports unknown for an unrecognized status rather than expiring a live connection', async () => {
|
|
respond(200, { session_id: 's1', status: 'SOMETHING_NEW' })
|
|
expect(await probeSessionHealth('s1')).toBe('unknown')
|
|
})
|
|
|
|
it('reports unknown on a bare 401 (app credentials, not a dead consent)', async () => {
|
|
respond(401, 'Unauthorized')
|
|
expect(await probeSessionHealth('s1')).toBe('unknown')
|
|
})
|
|
|
|
it('reports unknown when the request itself fails', async () => {
|
|
fetchSpy.mockRejectedValue(new Error('network down'))
|
|
expect(await probeSessionHealth('s1')).toBe('unknown')
|
|
})
|
|
})
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Connector mode (self-host routes upstream through the hosted bank proxy)
|
|
// ---------------------------------------------------------------------------
|
|
describe('connector mode', () => {
|
|
let fetchSpy: ReturnType<typeof vi.spyOn>
|
|
|
|
const okJson = (body: unknown) =>
|
|
new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } })
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
// A self-host with a connector key and no own EB credentials. The
|
|
// own-credentials env vars must stay unset for bankConnectorMode() to
|
|
// engage (key present AND no own credentials).
|
|
vi.stubEnv('GNUBOK_CONNECTOR_KEY', 'gnubok_ck_testsecret')
|
|
vi.stubEnv('GNUBOK_CONNECT_URL', 'https://app.test.example')
|
|
vi.stubEnv('ENABLE_BANKING_PRIVATE_KEY', '')
|
|
vi.stubEnv('ENABLE_BANKING_PRIVATE_KEY_PRODUCTION', '')
|
|
vi.stubEnv('ENABLE_BANKING_APP_ID', '')
|
|
vi.stubEnv('ENABLE_BANKING_APP_ID_PRODUCTION', '')
|
|
fetchSpy = vi.spyOn(globalThis, 'fetch')
|
|
})
|
|
|
|
afterEach(() => {
|
|
fetchSpy.mockRestore()
|
|
vi.unstubAllEnvs()
|
|
})
|
|
|
|
const lastCall = () => {
|
|
const call = fetchSpy.mock.calls[fetchSpy.mock.calls.length - 1]
|
|
const url = String(call[0])
|
|
const init = (call[1] ?? {}) as RequestInit
|
|
const headers = (init.headers ?? {}) as Record<string, string>
|
|
return { url, init, headers }
|
|
}
|
|
|
|
it('routes reads through the proxy with the connector key, never the EB JWT', async () => {
|
|
fetchSpy.mockResolvedValue(okJson({ aspsps: [] }))
|
|
await getASPSPs('SE')
|
|
const { url, headers } = lastCall()
|
|
expect(url).toContain('https://app.test.example/api/connect/bank/aspsps')
|
|
expect(headers['Authorization']).toBe('Bearer gnubok_ck_testsecret')
|
|
expect(headers['Authorization']).not.toContain('jwt')
|
|
// The JWT signer must not run: the instance holds no EB private key.
|
|
expect(mockGenerateJWT).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('sends X-Connector-Company on /auth so the proxy can meter the company quota', async () => {
|
|
fetchSpy.mockResolvedValue(okJson({ url: 'https://bank/auth', authorization_id: 'a1' }))
|
|
await startAuthorization('Bank', 'SE', 'https://instance.test/callback', 'oauth-state-1', 'business', undefined, 'company-42')
|
|
const { url, headers, init } = lastCall()
|
|
expect(url).toBe('https://app.test.example/api/connect/bank/auth')
|
|
expect(init.method).toBe('POST')
|
|
expect(headers['X-Connector-Company']).toBe('company-42')
|
|
expect(headers['Authorization']).toBe('Bearer gnubok_ck_testsecret')
|
|
})
|
|
|
|
it('binds /sessions to the signed connector_state when one is passed', async () => {
|
|
fetchSpy.mockResolvedValue(okJson({ session_id: 's1', accounts: [], access: { valid_until: '2027-01-01' } }))
|
|
await createSession('auth-code', 'signed-connector-state')
|
|
const { url, init } = lastCall()
|
|
expect(url).toBe('https://app.test.example/api/connect/bank/sessions')
|
|
expect(JSON.parse(String(init.body))).toEqual({ code: 'auth-code', connector_state: 'signed-connector-state' })
|
|
})
|
|
|
|
it('omits connector_state from /sessions when none is passed', async () => {
|
|
fetchSpy.mockResolvedValue(okJson({ session_id: 's1', accounts: [], access: { valid_until: '2027-01-01' } }))
|
|
await createSession('auth-code')
|
|
const { init } = lastCall()
|
|
expect(JSON.parse(String(init.body))).toEqual({ code: 'auth-code' })
|
|
})
|
|
|
|
it('does not engage when the instance has its own EB credentials (own-credentials seam)', async () => {
|
|
vi.stubEnv('ENABLE_BANKING_APP_ID', 'own-app-id')
|
|
fetchSpy.mockResolvedValue(okJson({ aspsps: [] }))
|
|
await getASPSPs('SE')
|
|
const { url, headers } = lastCall()
|
|
// Direct EB base (captured at import), never the connector proxy.
|
|
expect(url).not.toContain('/api/connect/bank')
|
|
expect(url).toContain('enablebanking.com')
|
|
expect(headers['Authorization']).toBe('Bearer test-jwt-token')
|
|
})
|
|
|
|
it('never sends X-Connector-Company on the direct path, even with companyId passed', async () => {
|
|
// Own EB credentials → direct path. companyId is always set on hosted /auth,
|
|
// so the header must be gated on connector mode, not on companyId: leaking
|
|
// the internal company UUID to the real Enable Banking API is a regression.
|
|
vi.stubEnv('ENABLE_BANKING_APP_ID', 'own-app-id')
|
|
fetchSpy.mockResolvedValue(okJson({ url: 'https://bank/auth', authorization_id: 'a1' }))
|
|
await startAuthorization('Bank', 'SE', 'https://instance.test/callback', 'oauth-state-1', 'business', undefined, 'company-42')
|
|
const { url, headers } = lastCall()
|
|
expect(url).toContain('enablebanking.com')
|
|
expect(headers['X-Connector-Company']).toBeUndefined()
|
|
expect(headers['Authorization']).toBe('Bearer test-jwt-token')
|
|
})
|
|
})
|
|
|
|
/**
|
|
* Log levels for the two conditions that are expected rather than broken.
|
|
*
|
|
* A PSD2 consent that ran out and a session Enable Banking has already dropped
|
|
* are both handled: the sync flips the connection to 'expired' and asks for a
|
|
* re-authorization, and the disconnect carries on regardless. Logging them at
|
|
* error filled the production error panel with events nobody could act on and
|
|
* buried the genuine ASPSP failures next to them. The thrown errors are
|
|
* unchanged: only the level moves.
|
|
*/
|
|
describe('expected-condition log levels', () => {
|
|
let fetchSpy: ReturnType<typeof vi.spyOn>
|
|
let errorSpy: ReturnType<typeof vi.spyOn>
|
|
let warnSpy: ReturnType<typeof vi.spyOn>
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
fetchSpy = vi.spyOn(globalThis, 'fetch')
|
|
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
})
|
|
|
|
afterEach(() => {
|
|
fetchSpy.mockRestore()
|
|
errorSpy.mockRestore()
|
|
warnSpy.mockRestore()
|
|
})
|
|
|
|
it('logs an expired bank session at warn, and still throws SessionExpiredError', async () => {
|
|
fetchSpy.mockResolvedValue(
|
|
new Response(JSON.stringify({ code: 'EXPIRED_SESSION' }), { status: 401 })
|
|
)
|
|
|
|
await expect(
|
|
getAllTransactionsWithRaw('acc-1', '2024-01-01', '2024-12-31')
|
|
).rejects.toThrow('Bank session expired')
|
|
|
|
expect(warnSpy).toHaveBeenCalled()
|
|
expect(errorSpy).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('still logs a genuine ASPSP failure at error', async () => {
|
|
// 500 is retried before it gives up; every attempt is the same failure.
|
|
fetchSpy.mockResolvedValue(new Response('{"message":"internal error"}', { status: 500 }))
|
|
|
|
await expect(
|
|
getAllTransactionsWithRaw('acc-1', '2024-01-01', '2024-12-31')
|
|
).rejects.toThrow('Failed to get transactions')
|
|
|
|
expect(errorSpy).toHaveBeenCalled()
|
|
})
|
|
|
|
it('logs a session that is already gone at Enable Banking at warn', async () => {
|
|
fetchSpy.mockResolvedValue(new Response('', { status: 404 }))
|
|
|
|
await expect(deleteSession('session-1')).rejects.toThrow('Failed to revoke session')
|
|
|
|
expect(warnSpy).toHaveBeenCalled()
|
|
expect(errorSpy).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('still logs an unexpected revoke failure at error', async () => {
|
|
fetchSpy.mockResolvedValue(new Response('{"message":"boom"}', { status: 500 }))
|
|
|
|
await expect(deleteSession('session-1')).rejects.toThrow('Failed to revoke session')
|
|
|
|
expect(errorSpy).toHaveBeenCalled()
|
|
})
|
|
})
|