import { describe, it, expect, vi, beforeEach } from 'vitest' // Mock dependencies: factory must not reference outer variables const mockCreateSession = vi.fn() const mockGetAccountBalance = vi.fn() vi.mock('@/extensions/general/enable-banking/lib/api-client', () => ({ createSession: (...args: unknown[]) => mockCreateSession(...args), getAccountBalance: (...args: unknown[]) => mockGetAccountBalance(...args), })) // Use hoisted to safely create mock objects referenced in vi.mock factories const { mockFrom, mockUpsertFromPsd2, mockAllocate } = vi.hoisted(() => { const mockFrom = vi.fn() const mockUpsertFromPsd2 = vi.fn() const mockAllocate = vi.fn() return { mockFrom, mockUpsertFromPsd2, mockAllocate } }) vi.mock('@/lib/supabase/server', () => ({ createServiceClient: vi.fn().mockResolvedValue({ from: mockFrom, }), })) const CURRENCY_DEFAULTS: Record = { SEK: '1930', EUR: '1932', USD: '1933', GBP: '1934', } vi.mock('@/lib/cash-accounts/service', () => ({ upsertFromPsd2: (...args: unknown[]) => mockUpsertFromPsd2(...args), // The route resolves ledgers through resolvePsd2LedgerAccount (IBAN match // first, allocation second). mockAllocate remains the allocation stand-in; // the wrapper puts its answer in the resolver's envelope so the existing // "did we allocate?" assertions keep their meaning. Tests that exercise the // IBAN path override resolvePsd2LedgerAccount's outcome via mockAllocate's // own implementation. resolvePsd2LedgerAccount: async (...args: unknown[]) => { const ledgerAccount = await mockAllocate(...args) if (!ledgerAccount) return null if (typeof ledgerAccount === 'object') return ledgerAccount return { ledgerAccount, reuseCashAccountId: null, source: 'allocated' } }, defaultLedgerForCurrency: (currency: string) => CURRENCY_DEFAULTS[currency.toUpperCase()] ?? '1930', })) vi.stubEnv('NEXT_PUBLIC_APP_URL', 'http://localhost:3000') import { GET } from '../route' function makeRequest(params: Record) { const url = new URL('http://localhost:3000/api/extensions/enable-banking/callback') for (const [k, v] of Object.entries(params)) { url.searchParams.set(k, v) } return new Request(url.toString()) } function mockChain(result: { data?: unknown; error?: unknown }) { const chain: Record = {} for (const m of ['select', 'eq', 'in', 'is', 'single', 'update', 'delete', 'order', 'limit']) { chain[m] = vi.fn().mockReturnValue(chain) } chain.single = vi.fn().mockResolvedValue({ data: result.data ?? null, error: result.error ?? null }) // For chains ending without .single() chain.then = (resolve: (v: unknown) => void) => resolve({ data: result.data ?? null, error: result.error ?? null }) return chain } describe('GET /api/extensions/enable-banking/callback', () => { beforeEach(() => { vi.clearAllMocks() mockUpsertFromPsd2.mockResolvedValue(undefined) // Allocator stand-in mirroring the real behavior: currency default first, // then the next free 1931–1959 slot (skipping other currency defaults). mockAllocate.mockImplementation( async ( _supabase: unknown, _companyId: unknown, _userId: unknown, input: { currency: string; exclude?: ReadonlySet }, ) => { const preferred = CURRENCY_DEFAULTS[input.currency.toUpperCase()] ?? '1930' const exclude = input.exclude ?? new Set() if (!exclude.has(preferred)) return preferred const reserved = new Set(Object.values(CURRENCY_DEFAULTS)) for (let n = 1931; n <= 1959; n++) { const candidate = String(n) if (!reserved.has(candidate) && !exclude.has(candidate)) return candidate } return null }, ) }) it('rejects when state does not match any pending connection', async () => { mockFrom.mockImplementation(() => mockChain({ data: null, error: { message: 'not found' } }) ) const response = await GET(makeRequest({ code: 'auth-code', state: 'unknown-state' })) expect(response.status).toBe(307) const location = response.headers.get('location') || '' expect(location).toContain('/settings/banking?') expect(location).toContain('bank_error=invalid_state') }) it('writes pending_selection and streams a finalizing page that redirects to the picker', async () => { const capturedUpdates: Record[] = [] let callIndex = 0 mockFrom.mockImplementation(() => { callIndex++ if (callIndex === 1) { // Find pending connection by oauth_state return mockChain({ data: { id: 'conn-1', user_id: 'user-1', company_id: 'company-1', bank_name: 'TestBank', status: 'pending' }, error: null, }) } // Update connection: capture the payload, then chain returns the // updated row via .select().single() for the audit event emission. const chain: Record = {} chain.update = vi.fn((payload: Record) => { capturedUpdates.push(payload) return chain }) chain.eq = vi.fn().mockReturnValue(chain) chain.select = vi.fn().mockReturnValue(chain) chain.single = vi.fn().mockResolvedValue({ data: { id: 'conn-1', bank_name: 'TestBank', company_id: 'company-1', user_id: 'user-1', }, error: null, }) // Back-compat fallthrough for chains that aren't terminated by .single() chain.then = (resolve: (v: unknown) => void) => resolve({ data: null, error: null }) return chain }) mockCreateSession.mockResolvedValue({ session_id: 'sess-1', accounts: [ { uid: 'acc-1', account_id: { iban: 'SE1234' }, name: 'Företagskonto', currency: 'SEK' }, { uid: 'acc-2', account_id: { iban: 'SE5678' }, name: 'Privatkonto', currency: 'SEK' }, ], access: { valid_until: '2024-12-31T00:00:00Z' }, aspsp: { name: 'TestBank', country: 'SE' }, }) mockGetAccountBalance.mockRejectedValue(new Error('skip balance fetch')) const response = await GET(makeRequest({ code: 'auth-code', state: 'valid-state' })) // Success streams an interim page (instant feedback during the session // exchange) that ends with a client-side redirect to the account picker. expect(response.status).toBe(200) expect(response.headers.get('content-type')).toContain('text/html') expect(response.headers.get('cache-control')).toBe('no-store') const body = await response.text() // Shell flushed with the bank name, then the redirect to the picker. expect(body).toContain('TestBank') expect(body).toContain('window.location.replace') expect(body).toContain('select_accounts=conn-1') expect(body).not.toContain('bank_error') // ASVS V3.3: inline scripts are nonce-bound. The response-level CSP // declares the nonce and BOTH chunks (shell watchdog + redirect) carry // it; no un-nonced inline script may exist on this page. const csp = response.headers.get('content-security-policy') ?? '' const nonceMatch = /script-src 'nonce-([^']+)'/.exec(csp) expect(nonceMatch).not.toBeNull() const nonce = nonceMatch![1] expect(body.split(`