feat(bank-sync): close the F2 report: gap backfill, consent and paused chip states, agent-triggered sync (#2165)

* fix(bank-sync): cron backfills the gap since the last successful sync

The daily incremental sync always asked the bank for the last 7 days. Any
pause longer than that (a lapsed subscription paid again, a consent renewed
after expiry, an outage) silently lost the days in between: the connection
came back, looked healthy, and the missing transactions never arrived.

The lookback now widens to cover the gap since last_synced_at plus one day
of overlap, capped at the 90-day PSD2 limit, and a gap of a month or more
asks for strategy=longest like the manual sync route does. Dedup via
external_id makes the overlap harmless. First syncs keep their 90-day path.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QdcDV7CngLkWUvfKSsxFhS

* feat(bank-sync): chip warns seven days before a bank consent expires

The transactions-page chip only reacted once a connection was already dead
(expired/error) or had gone stale. A consent that is about to end looked
healthy until the morning it stopped syncing. New "expiring" state when a
live connection's consent_expires is within seven days, the same threshold
as the consent-expiry email in the sync cron. Precedence: attention,
expiring, stale, healthy.

getChipState moves to lib/transactions/bank-sync-chip-state.ts so the
precedence is unit-tested; the component keeps the rendering only.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QdcDV7CngLkWUvfKSsxFhS

* feat(bank-sync): chip says paused when the subscription lapsed

The daily cron filters connections by the bank_sync capability, so a
company whose trial or subscription ended keeps status=active rows with a
frozen last_synced_at. The chip read that as "stale, check the connection",
which sends the user to re-authorise a connection that is perfectly alive.
56 of 191 active connections on prod were in this state on 2026-09-01.

New "paused" state, ranked above everything else, when the company lacks
bank_sync: hosted points at billing, self-host at the connector key, the
same split BankSyncNowButton already makes. getChipState takes an options
object so the clock stays out of render (react-hooks/purity).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QdcDV7CngLkWUvfKSsxFhS

* feat(api): agent-triggerable bank sync in v1 and MCP

Closes the first wish in the F2 report: an integration could read bank
data but never refresh it. New POST /api/v1/companies/{id}/bank-connections/
{connectionId}/sync and MCP gnubok_sync_bank, both on a shared runner
(extensions/general/enable-banking/lib/trigger-sync.ts).

Cost is bounded structurally, not by policy: the window is never
caller-controlled (the cron's gap-aware 7 to 90 day lookback), a connection
synced within 15 minutes answers BANK_SYNC_COOLDOWN with next_allowed_at
(429 + Retry-After on v1; synced=false in-band on MCP so the agent reads on
instead of retrying), and a failing connection is throttled per process by
attempt time. A dead session is flipped to expired with a remediation that
hands the user the connect link: no API call revives a consent.

Gated on bank_sync like gnubok_connect_bank; scope transactions:write.
Registry, scope map, load-routes, spec snapshot and the generated
accounted-api skill updated; five BANK_SYNC_* / BANK_SESSION_EXPIRED codes
added to the structured-error registry. The web Synka-nu route is left as
is (see DECISIONS.md).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QdcDV7CngLkWUvfKSsxFhS

* test(bank-sync): use the options object in the remaining chip-state calls

Four multi-line calls still passed the clock positionally after
getChipState moved to an options object; tsc flagged them (vitest did not,
the extra argument was ignored at runtime).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QdcDV7CngLkWUvfKSsxFhS

* fix(api): address skeptic findings on the agent-triggered bank sync

Three refutations from the pre-publish skeptic pass:

1. Core imported the extension. The v1 sync route pulled the runner
   straight from @/extensions, which the core-build gate rejects and which
   left a live bank endpoint on zero-extension builds. The route now
   resolves it through the registry's services channel against a contract
   in lib/bank-sync/trigger-sync-contract.ts (same pattern as the
   Skatteverket read service) and answers EXTENSION_DISABLED when the
   extension is absent.

2. The idempotency cache stored the handler-level 429. A same-key retry
   after Retry-After, which is the documented retry, replayed the stale
   cooldown as a 400 for the cache's 24-hour TTL. withApiV1 no longer
   caches 429 responses; regression test added. The endpoint's pitfall no
   longer claims Idempotency-Key is mandatory (it was never enforced).

3. Two cron tests read the clock twice and failed whenever a millisecond
   passed between the reads. They now pin the clock with fake timers.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QdcDV7CngLkWUvfKSsxFhS

* fix(bank-sync): durable cooldown lease and review wording

Resolves the PR #2165 review findings in one pass.

Superagent P1: the attempt throttle was a process-local Map, so two agent
calls on different serverless instances (or a retry after a cold start on
a failing connection) could each bill an Enable Banking call, contradicting
the one-sync-per-15-minutes promise. New bank_connections.sync_lease_until
(migration 20260902150000), claimed with one conditional UPDATE before the
bank is called; Postgres row locking makes exactly one claimer win, the
rest answer BANK_SYNC_COOLDOWN. The lease stays for the full window on
success and failure. Tests cover the claim order, a failed attempt seen
from a second instance, a lost race, and an expired lease.

CodeRabbit: the =1 plural branch now reads "in 1 day" / "om 1 dag"
(daysUntilConsentExpiry rounds a partial day up, so "tomorrow" could be
today); the cooldown pitfall on the v1 endpoint, the MCP description and
the in-band cooldown instruction now say a cooldown can follow a failed
attempt and tell the agent to compare last_synced_at before deciding.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0125TMQQBjBBZG9YxP7wQWub

* fix(bank-sync): lease claim as a literal filter for the schema guard

CI's no-phantom-columns guard counts runtime-built query expressions and
its ceiling is exact; the templated `.or('sync_lease_until.is.null,...')`
claim added one. The column now defaults to epoch (NOT NULL), so "never
claimed" is just "expired long ago" and the atomic claim is a single
literal `.lte('sync_lease_until', now)` the guard can check. Migration is
unshipped (same PR), so it is edited in place.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0125TMQQBjBBZG9YxP7wQWub

* fix(bank-sync): runner verifies company membership before the lease

Superagent (round 3): the MCP path reached the shared runner without a
membership check of its own. Both callers do enforce it upstream
(withApiV1's company resolution and resolveMcpCompanyContext in the MCP
dispatcher), but the runner writes transactions and bills a bank call, so
it now checks company_members itself, before the cooldown and the lease
claim, and answers NOT_FOUND for a non-member. The viewer check that was
buried inside the sync block moves up with it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0125TMQQBjBBZG9YxP7wQWub

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-09-02 17:17:41 +02:00
committed by GitHub
co-authored by Claude Fable 5.1
parent 723a0f537b
commit b68c082ef5
30 changed files with 1914 additions and 53 deletions
@@ -457,3 +457,67 @@ describe('GET /api/extensions/enable-banking/sync/cron: failure log level', () =
consoleError.mockRestore()
})
})
describe('GET /api/extensions/enable-banking/sync/cron: incremental lookback', () => {
const DAY_MS = 24 * 60 * 60 * 1000
// Pin the clock: the route reads Date.now() after the fixture does, and a
// single elapsed millisecond makes Math.ceil in incrementalLookbackDays
// count one more day than the fixture intended.
const NOW = Date.parse('2026-09-02T05:00:00.000Z')
const isoDate = (msAgo: number) => new Date(NOW - msAgo).toISOString().split('T')[0]
const syncedDaysAgo = (days: number) => new Date(NOW - days * DAY_MS).toISOString()
beforeEach(() => {
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(NOW)
})
afterEach(() => {
vi.useRealTimers()
})
it('uses the 7-day window when the connection synced yesterday', async () => {
state.active = [connection({ last_synced_at: syncedDaysAgo(1) })]
mocks.probeSessionHealth.mockResolvedValue('alive')
await GET(cronRequest())
expect(mocks.syncAccountTransactions).toHaveBeenCalledTimes(1)
const [, , , , , fromDate, , , options] = mocks.syncAccountTransactions.mock.calls[0]
expect(fromDate).toBe(isoDate(7 * DAY_MS))
expect(options).not.toHaveProperty('strategy')
})
it('widens the window to cover a gap since the last sync', async () => {
// A subscription that lapsed for 20 days and was paid again: a fixed
// 7-day window would silently drop the 13 days in between.
state.active = [connection({ last_synced_at: syncedDaysAgo(20) })]
mocks.probeSessionHealth.mockResolvedValue('alive')
await GET(cronRequest())
expect(mocks.syncAccountTransactions).toHaveBeenCalledTimes(1)
const [, , , , , fromDate] = mocks.syncAccountTransactions.mock.calls[0]
expect(fromDate).toBe(isoDate(21 * DAY_MS))
})
it('asks for the deepest history the bank serves on a gap of a month or more', async () => {
state.active = [connection({ last_synced_at: syncedDaysAgo(40) })]
mocks.probeSessionHealth.mockResolvedValue('alive')
await GET(cronRequest())
const [, , , , , fromDate, , , options] = mocks.syncAccountTransactions.mock.calls[0]
expect(fromDate).toBe(isoDate(41 * DAY_MS))
expect(options).toMatchObject({ strategy: 'longest' })
})
it('caps the widened window at 90 days', async () => {
state.active = [connection({ last_synced_at: syncedDaysAgo(200) })]
mocks.probeSessionHealth.mockResolvedValue('alive')
await GET(cronRequest())
const [, , , , , fromDate] = mocks.syncAccountTransactions.mock.calls[0]
expect(fromDate).toBe(isoDate(90 * DAY_MS))
})
})
@@ -29,6 +29,11 @@ import { getBranding } from '@/lib/branding/service'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { updateBalancesFromSync } from '@/lib/cash-accounts/service'
import type { StoredAccount } from '@/extensions/general/enable-banking/types'
import {
INCREMENTAL_LOOKBACK_DAYS,
MAX_LOOKBACK_DAYS,
incrementalLookbackDays,
} from '@/extensions/general/enable-banking/lib/cron-lookback'
ensureInitialized()
@@ -194,17 +199,28 @@ export const GET = withCronContext('cron.bank_sync', async (_request, ctx) => {
}
const toDate = new Date().toISOString().split('T')[0]
// First sync: 90-day lookback (PSD2 max). Subsequent: 7-day window.
// First sync: 90-day lookback (PSD2 max). Subsequent: 7-day window,
// widened to cover any gap since the last successful sync (a paused
// subscription that was paid again, a renewed consent) so the days in
// between are not lost. See cron-lookback.ts.
// Gate on initial_sync_completed_at, not last_synced_at: manual "Sync now"
// sets last_synced_at without doing the deep backfill, and we want the cron
// to still fall back to 90 days if the inline activation backfill failed.
const isFirstSync = !connection.initial_sync_completed_at
const lookbackDays = isFirstSync ? 90 : 7
const lookbackDays = isFirstSync
? MAX_LOOKBACK_DAYS
: incrementalLookbackDays(connection.last_synced_at)
if (isFirstSync) {
ctx.log.info('first sync for connection: using 90-day lookback', {
connectionId: connection.id,
lookbackDays,
})
} else if (lookbackDays > INCREMENTAL_LOOKBACK_DAYS) {
ctx.log.info('gap since last sync: widening lookback', {
connectionId: connection.id,
lastSyncedAt: connection.last_synced_at,
lookbackDays,
})
}
const fromDate = new Date(Date.now() - lookbackDays * 24 * 60 * 60 * 1000)
.toISOString()
@@ -246,11 +262,12 @@ export const GET = withCronContext('cron.bank_sync', async (_request, ctx) => {
.maybeSingle()
// First sync uses strategy=longest to pull the deepest history available
// from the ASPSP. Incremental syncs skip it: the implicit default is
// faster and we already have the older data.
// from the ASPSP, and so does a gap backfill of a month or more (same
// threshold as the manual sync route). Routine incremental syncs skip
// it: the implicit default is faster and we already have the older data.
const syncOptions = {
...(sieOverlap ? { skipAutoCategorization: true } : {}),
...(isFirstSync ? { strategy: 'longest' as const } : {}),
...(isFirstSync || lookbackDays >= 30 ? { strategy: 'longest' as const } : {}),
}
const syncResults = await Promise.all(
@@ -0,0 +1,254 @@
/**
* Tests for POST /api/v1/companies/{companyId}/bank-connections/{connectionId}/sync.
*
* Exercises the real withApiV1 wrapper (auth, scope, company membership,
* idempotency header) with the Supabase client and the sync runner mocked.
*/
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
beforeAll(() => {
if (process.env.NODE_ENV !== 'test') throw new Error('NODE_ENV=test required')
process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key'
})
vi.mock('@/lib/auth/api-keys', async () => {
const actual = await vi.importActual<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
return { ...actual, validateApiKey: vi.fn(), createServiceClientNoCookies: vi.fn() }
})
vi.mock('@supabase/supabase-js', async () => {
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@supabase/supabase-js')
return { ...actual, createClient: vi.fn().mockReturnValue({}) }
})
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
const { requireCapabilityMock, triggerSyncMock, registryGetMock } = vi.hoisted(() => ({
requireCapabilityMock: vi.fn(),
triggerSyncMock: vi.fn(),
registryGetMock: vi.fn(),
}))
vi.mock('@/lib/entitlements/has-capability', () => ({
requireCapability: requireCapabilityMock,
}))
// Core cannot import the extension: the route resolves the runner through
// the registry's `services` channel, so that is what gets stubbed.
vi.mock('@/lib/extensions/registry', () => ({
extensionRegistry: { get: registryGetMock },
}))
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
import { POST } from '../route'
const mockValidate = validateApiKey as ReturnType<typeof vi.fn>
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
type MockResult = { data?: unknown; error?: unknown }
function makeFlexibleSupabase(byTable: Record<string, MockResult | MockResult[]>) {
const queues = new Map<string, MockResult[]>()
for (const [t, val] of Object.entries(byTable)) queues.set(t, Array.isArray(val) ? [...val] : [val])
const buildChain = (table: string): unknown => {
const handler: ProxyHandler<object> = {
get(_target, prop) {
if (prop === 'then') {
return (resolve: (v: unknown) => void) => {
const q = queues.get(table)
const next = q && q.length > 1 ? q.shift()! : (q?.[0] ?? { data: null, error: null })
resolve(next)
}
}
return (..._args: unknown[]) => buildChain(table)
},
}
return new Proxy({}, handler)
}
return { from: vi.fn((table: string) => buildChain(table)) }
}
const COMPANY_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
const CONNECTION_ID = '11111111-1111-4111-8111-111111111111'
const BASE = `http://localhost/api/v1/companies/${COMPANY_ID}/bank-connections/${CONNECTION_ID}/sync`
function req(opts: { idempotencyKey?: string | null; dryRun?: boolean } = {}): Request {
const headers: Record<string, string> = {
Authorization: 'Bearer test-fixture-not-a-real-key',
'Content-Type': 'application/json',
}
if (opts.idempotencyKey !== null) headers['Idempotency-Key'] = opts.idempotencyKey ?? 'idem-1'
const url = opts.dryRun ? `${BASE}?dry_run=true` : BASE
return new Request(url, { method: 'POST', headers, body: '{}' })
}
function authOk(scopes: string[], mode: 'live' | 'test' = 'live') {
mockValidate.mockResolvedValue({
valid: true,
userId: 'user-1',
keyId: 'key-1',
keyName: 'Test key',
scopes,
mode,
})
}
const params = { params: Promise.resolve({ companyId: COMPANY_ID, connectionId: CONNECTION_ID }) }
const OK_RESULT = {
ok: true,
connection_id: CONNECTION_ID,
bank: 'Swedbank',
imported: 3,
duplicates: 12,
from_date: '2026-08-26',
to_date: '2026-09-02',
last_synced_at: '2026-09-02T09:14:03.000Z',
}
describe('v1 bank-connections sync', () => {
beforeEach(() => {
vi.clearAllMocks()
requireCapabilityMock.mockResolvedValue(null)
triggerSyncMock.mockResolvedValue(OK_RESULT)
registryGetMock.mockImplementation((id: string) =>
id === 'enable-banking' ? { services: { triggerConnectionSync: triggerSyncMock } } : undefined,
)
mockServiceClient.mockReturnValue(
makeFlexibleSupabase({
company_members: { data: { role: 'owner' } },
idempotency_keys: { data: null },
}),
)
})
it('401 without a valid key', async () => {
mockValidate.mockResolvedValue({ valid: false, error: 'invalid' })
const res = await POST(req(), params)
expect(res.status).toBe(401)
expect(triggerSyncMock).not.toHaveBeenCalled()
})
it('403 INSUFFICIENT_SCOPE when the key lacks transactions:write', async () => {
authOk(['transactions:read', 'companies:read'])
const res = await POST(req(), params)
expect(res.status).toBe(403)
expect(triggerSyncMock).not.toHaveBeenCalled()
})
it('returns the capability-blocked response when bank_sync is not entitled', async () => {
authOk(['transactions:write'])
requireCapabilityMock.mockResolvedValue(
Response.json({ error: { code: 'CAPABILITY_BLOCKED' } }, { status: 403 }),
)
const res = await POST(req(), params)
expect(res.status).toBe(403)
expect(requireCapabilityMock).toHaveBeenCalledWith(expect.anything(), COMPANY_ID, 'bank_sync')
expect(triggerSyncMock).not.toHaveBeenCalled()
})
it('404 when the key user is not a member of the company', async () => {
authOk(['transactions:write'])
mockServiceClient.mockReturnValue(makeFlexibleSupabase({ company_members: { data: null } }))
const res = await POST(req(), params)
expect(res.status).toBe(404)
expect(triggerSyncMock).not.toHaveBeenCalled()
})
it('blocks a test key: the bank call cannot be simulated', async () => {
authOk(['transactions:write'], 'test')
const res = await POST(req(), params)
expect(res.status).toBeGreaterThanOrEqual(400)
expect(res.status).toBeLessThan(500)
expect(triggerSyncMock).not.toHaveBeenCalled()
})
it('refuses ?dry_run=true on a live key with a VALIDATION_ERROR', async () => {
authOk(['transactions:write'])
const res = await POST(req({ dryRun: true }), params)
expect(res.status).toBe(400)
const body = (await res.json()) as { error: { code: string; details: { field: string } } }
expect(body.error.code).toBe('VALIDATION_ERROR')
expect(body.error.details.field).toBe('dry_run')
expect(triggerSyncMock).not.toHaveBeenCalled()
})
it('answers EXTENSION_DISABLED when the enable-banking extension is not registered', async () => {
authOk(['transactions:write'])
registryGetMock.mockReturnValue(undefined)
const res = await POST(req(), params)
const body = (await res.json()) as { error: { code: string } }
expect(body.error.code).toBe('EXTENSION_DISABLED')
expect(triggerSyncMock).not.toHaveBeenCalled()
})
it('runs the sync for the path connection and returns the outcome', async () => {
authOk(['transactions:write'])
const res = await POST(req(), params)
expect(res.status).toBe(200)
const body = (await res.json()) as {
data: Record<string, unknown>
meta: { request_id: string }
}
expect(triggerSyncMock).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ companyId: COMPANY_ID, userId: 'user-1', connectionId: CONNECTION_ID }),
)
expect(body.data).toEqual({
connection_id: CONNECTION_ID,
bank: 'Swedbank',
imported: 3,
duplicates: 12,
from_date: '2026-08-26',
to_date: '2026-09-02',
last_synced_at: '2026-09-02T09:14:03.000Z',
})
expect(body.meta.request_id).toMatch(/^req_/)
})
it('429 BANK_SYNC_COOLDOWN with next_allowed_at and Retry-After', async () => {
authOk(['transactions:write'])
triggerSyncMock.mockResolvedValue({
ok: false,
code: 'BANK_SYNC_COOLDOWN',
connection_id: CONNECTION_ID,
next_allowed_at: '2026-09-02T09:29:03.000Z',
retry_after_seconds: 600,
})
const res = await POST(req(), params)
expect(res.status).toBe(429)
expect(res.headers.get('Retry-After')).toBe('600')
const body = (await res.json()) as {
error: { code: string; details: { next_allowed_at: string } }
}
expect(body.error.code).toBe('BANK_SYNC_COOLDOWN')
expect(body.error.details.next_allowed_at).toBe('2026-09-02T09:29:03.000Z')
})
it('409 BANK_SESSION_EXPIRED with a recovery hint pointing at the connect link', async () => {
authOk(['transactions:write'])
triggerSyncMock.mockResolvedValue({
ok: false,
code: 'BANK_SESSION_EXPIRED',
connection_id: CONNECTION_ID,
status: 'expired',
})
const res = await POST(req(), params)
expect(res.status).toBe(409)
const body = (await res.json()) as { error: { code: string; recovery_hint?: string } }
expect(body.error.code).toBe('BANK_SESSION_EXPIRED')
expect(body.error.recovery_hint).toContain('connect_url')
})
it('404 NOT_FOUND for a connection outside the company', async () => {
authOk(['transactions:write'])
triggerSyncMock.mockResolvedValue({ ok: false, code: 'NOT_FOUND', connection_id: CONNECTION_ID })
const res = await POST(req(), params)
expect(res.status).toBe(404)
})
it('maps a thrown database error into the v1 error envelope', async () => {
authOk(['transactions:write'])
triggerSyncMock.mockRejectedValue({ message: 'boom', code: '57014' })
const res = await POST(req(), params)
expect(res.status).toBeGreaterThanOrEqual(500)
const body = (await res.json()) as { error: { code: string } }
expect(body.error.code).toBeTruthy()
})
})
@@ -0,0 +1,157 @@
/**
* POST /api/v1/companies/{companyId}/bank-connections/{connectionId}/sync
*
* Trigger a PSD2 sync of one bank connection now, instead of waiting for
* the nightly cron. The window is not caller-controlled: the same gap-aware
* incremental lookback the cron uses (7 days, widened to cover any gap since
* last_synced_at, capped at 90). A connection synced or attempted within the
* last 15 minutes answers 429 BANK_SYNC_COOLDOWN with next_allowed_at (the
* attempt guard is a durable lease on the row, claimed atomically), so an
* unattended agent can never run up the Enable Banking bill by polling, even
* across serverless instances.
*
* What this cannot do: revive a dead consent. status=expired (or a session
* the bank reports dead mid-sync) needs BankID in a browser; the response
* says so and points at the connect link.
*
* The runner lives in the enable-banking extension. Core cannot import it
* (CI guard), so it is reached through the registry-resolved `services`
* channel declared in lib/bank-sync/trigger-sync-contract.ts, and a
* deployment without the extension answers EXTENSION_DISABLED.
*/
import { z } from 'zod'
import { ok } from '@/lib/api/v1/response'
import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry'
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
import { requireCapability } from '@/lib/entitlements/has-capability'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { ensureInitialized } from '@/lib/init'
import { extensionRegistry } from '@/lib/extensions/registry'
import {
SYNC_COOLDOWN_MS,
type EnableBankingServices,
} from '@/lib/bank-sync/trigger-sync-contract'
ensureInitialized()
const SyncResponse = z.object({
connection_id: z.string().uuid(),
bank: z.string().nullable(),
imported: z.number().int().nonnegative(),
duplicates: z.number().int().nonnegative(),
from_date: z.string(),
to_date: z.string(),
last_synced_at: z.string(),
})
registerEndpoint({
operation: 'bank-connections.sync',
method: 'POST',
path: '/api/v1/companies/:companyId/bank-connections/:connectionId/sync',
summary: 'Sync one bank connection now instead of waiting for the nightly run.',
description:
'Fetches new transactions and balances for one PSD2 bank connection right away. The window is chosen server-side: the last 7 days, widened to cover any gap since last_synced_at, capped at 90 days. Returns how many transactions were imported and the new last_synced_at. A connection synced within the last 15 minutes is refused with 429 BANK_SYNC_COOLDOWN and next_allowed_at: the data is already fresh. Not dry-runnable: the bank call itself is the side effect.',
useWhen:
'GET /bank-connections shows a stale last_synced_at on an active connection and you need current bank data before building on it (liquidity, reconciliation, a report), or the user asks for the latest transactions now.',
doNotUseFor:
'Polling. Connections sync every night on their own; call this once when freshness matters, then read /transactions. Fixing a dead connection: status=expired needs BankID in a browser, not a sync.',
pitfalls: [
'Idempotency-Key is optional here. If you send one, use a fresh key per attempt: a cooldown answer is never cached, but a completed sync is, and replaying it fetches nothing new.',
'429 BANK_SYNC_COOLDOWN follows a recent successful sync OR a recent attempt that failed (the 15-minute lease is taken before the bank is called, on every instance). Compare last_synced_at from GET /bank-connections: if it is fresh, use the data you have; if it is still stale, the previous attempt failed, so retry once after next_allowed_at (Retry-After is set).',
'409 BANK_SESSION_EXPIRED means the bank reported the consent dead during the sync; the connection is now status=expired. Hand the user the connect link; no API call revives it.',
'imported: 0 is normal on a quiet account. Banks report with up to 48 hours of delay, so today\'s transactions often arrive tomorrow.',
'Costs one Enable Banking call per enabled account: 403 CAPABILITY_BLOCKED when the company has no bank_sync entitlement.',
],
example: {
response: {
data: {
connection_id: '4f6c…',
bank: 'Swedbank',
imported: 3,
duplicates: 12,
from_date: '2026-08-26',
to_date: '2026-09-02',
last_synced_at: '2026-09-02T09:14:03Z',
},
meta: { request_id: 'req_…', api_version: '2026-05-12' },
},
},
scope: 'transactions:write',
risk: 'low',
idempotent: false,
reversible: false,
dryRunSupported: false,
response: {
success: dataEnvelope(SyncResponse),
errorCodes: [
'BANK_SYNC_COOLDOWN',
'BANK_SYNC_NOT_ACTIVE',
'BANK_SYNC_NO_ACCOUNTS',
'BANK_SESSION_EXPIRED',
'BANK_SYNC_FAILED',
'CAPABILITY_BLOCKED',
'EXTENSION_DISABLED',
'NOT_FOUND',
],
},
})
export const POST = withApiV1<{ params: Promise<{ companyId: string; connectionId: string }> }>(
'bank-connections.sync',
async (_request, ctx, params) => {
const { connectionId } = await params.params
const capBlocked = await requireCapability(ctx.supabase, ctx.companyId!, CAPABILITY.bank_sync)
if (capBlocked) return capBlocked
// The bank round-trip IS the side effect, so there is nothing to simulate.
// Test keys never reach this line (the wrapper blocks them on endpoints
// that cannot dry-run); a live key passing ?dry_run=true is told why.
if (ctx.dryRun) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: {
field: 'dry_run',
message: 'dry_run is not supported: the bank call is the side effect.',
cooldown_ms: SYNC_COOLDOWN_MS,
},
})
}
// The enable-banking extension is opt-in (extensions.config.json) and the
// registry is the runtime source of truth: absent registration means the
// deployment does not offer PSD2 sync at all.
const services = extensionRegistry.get('enable-banking')?.services as
| Partial<EnableBankingServices>
| undefined
if (!services?.triggerConnectionSync) {
return v1ErrorResponseFromCode('EXTENSION_DISABLED', ctx.log, {
requestId: ctx.requestId,
})
}
try {
const result = await services.triggerConnectionSync(ctx.supabase, {
companyId: ctx.companyId!,
userId: ctx.userId,
connectionId,
log: ctx.log,
})
if (!result.ok) {
const { ok: _ok, code, ...details } = result
return v1ErrorResponseFromCode(code, ctx.log, {
requestId: ctx.requestId,
details,
retryAfterSeconds: result.retry_after_seconds,
})
}
const { ok: _ok, ...data } = result
return ok(data, { requestId: ctx.requestId })
} catch (error) {
return v1ErrorResponse(error, ctx.log, { requestId: ctx.requestId })
}
},
)