docs(production): standardiserad produktionsberedskap och gap-analys

Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
2026-11-10 09:15:21 +01:00
parent 0fda8cae48
commit 2bee8eb778
6135 changed files with 4 additions and 1718997 deletions
@@ -1,224 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
let currentKey = {
id: 'key-1',
orgNumber: '5561234567',
instanceUrl: 'https://bokforing.example.se',
scopes: ['bank_sync'],
status: 'active' as const,
currentPeriodEnd: null as string | null,
limits: { bank_connections_per_company: 1, skv_connections_per_company: 1, sync_min_interval_s: 0 },
}
vi.mock('@/lib/connect/hosted/with-connector-auth', () => ({
withConnectorAuth: (_op: string, handler: (req: Request, ctx: unknown) => Promise<Response>) => (req: Request) =>
handler(req, { requestId: 'conn_test', log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, supabase: {}, key: currentKey }),
}))
vi.mock('@/lib/connect/upstreams/enable-banking-jwt', () => ({ getAuthorizationHeader: () => 'Bearer eb-jwt' }))
const h = vi.hoisted(() => ({
budget: vi.fn(),
ledger: {
countHeldConnections: vi.fn(),
deletePendingConnectionById: vi.fn(),
createPendingConnection: vi.fn(),
activateByPendingState: vi.fn(),
findByHandle: vi.fn(),
findPendingByState: vi.fn(),
findByAccountUid: vi.fn(),
revokeByHandle: vi.fn(),
touchConnection: vi.fn(),
},
}))
const budget = h.budget
const ledger = h.ledger
vi.mock('@/lib/connect/hosted/upstream-budget', () => ({ reserveUpstream: (...a: unknown[]) => h.budget(...a) }))
vi.mock('@/lib/connect/hosted/ledger', () => h.ledger)
vi.mock('@/lib/connect/hosted/state', () => ({
signConnectorState: () => 'ck1.signed.state',
verifyConnectorState: (token: string) =>
token === 'ck1.signed.state'
? { ok: true, payload: { kid: 'key-1', svc: 'bank', ret: 'https://bokforing.example.se/cb', st: 's', cref: 'company-1', iat: 0 } }
: token === 'ck1.other-key.state'
? { ok: true, payload: { kid: 'key-OTHER', svc: 'bank', ret: 'x', st: 's', cref: 'c', iat: 0 } }
: { ok: false, reason: 'malformed' },
}))
const fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
import { GET, POST, DELETE } from '../route'
function req(method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Request {
return new Request(`https://app.gnubok.se/api/connect/bank${path}`, {
method,
headers: { 'x-connector-company': 'company-1', ...headers },
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
})
}
function ebOk(body: unknown, status = 200) {
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }))
}
beforeEach(() => {
vi.clearAllMocks()
process.env.ENABLE_BANKING_API_URL = 'https://api.enablebanking.com'
process.env.NEXT_PUBLIC_APP_URL = 'https://app.gnubok.se'
currentKey = { ...currentKey, scopes: ['bank_sync'], limits: { bank_connections_per_company: 1, skv_connections_per_company: 1, sync_min_interval_s: 0 } }
budget.mockResolvedValue({ ok: true })
})
describe('bank proxy', () => {
it('403s when the key lacks the bank_sync scope', async () => {
currentKey = { ...currentKey, scopes: [] }
const res = await GET(req('GET', '/aspsps'))
expect(res.status).toBe(403)
expect((await res.json()).code).toBe('CONNECTOR_SCOPE_MISSING')
expect(fetchMock).not.toHaveBeenCalled()
})
it('forwards GET /aspsps with the EB JWT', async () => {
ebOk({ aspsps: [] })
const res = await GET(req('GET', '/aspsps?country=SE'))
expect(res.status).toBe(200)
const [url, init] = fetchMock.mock.calls[0]
expect(url).toBe('https://api.enablebanking.com/aspsps?country=SE')
expect((init.headers as Record<string, string>).Authorization).toBe('Bearer eb-jwt')
})
it('refuses an unknown path', async () => {
const res = await GET(req('GET', '/accounts'))
expect(res.status).toBe(403)
expect((await res.json()).code).toBe('CONNECTOR_PATH_NOT_ALLOWED')
})
it('POST /auth rewrites redirect + state, checks quota, records a pending row', async () => {
ledger.countHeldConnections.mockResolvedValue(0)
ledger.createPendingConnection.mockResolvedValue('p1')
ebOk({ url: 'https://bank.example/consent', authorization_id: 'a1' })
const res = await POST(req('POST', '/auth', {
aspsp: { name: 'SEB', country: 'SE' },
redirect_url: 'https://bokforing.example.se/api/extensions/enable-banking/callback',
state: 'inst-state',
}))
expect(res.status).toBe(200)
expect(ledger.createPendingConnection).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ keyId: 'key-1', service: 'bank', companyRef: 'company-1', provider: 'SEB', pendingState: 'ck1.signed.state' }))
const body = JSON.parse(fetchMock.mock.calls[0][1].body)
expect(body.redirect_url).toBe('https://app.gnubok.se/api/extensions/enable-banking/callback')
expect(body.state).toBe('ck1.signed.state')
})
it('POST /auth rejects a redirect_url off the pinned instance', async () => {
const res = await POST(req('POST', '/auth', { aspsp: { name: 'SEB', country: 'SE' }, redirect_url: 'https://evil.example.com/cb', state: 's' }))
expect(res.status).toBe(400)
expect((await res.json()).code).toBe('CONNECTOR_REDIRECT_INVALID')
expect(ledger.createPendingConnection).not.toHaveBeenCalled()
})
it('POST /auth 403s when the per-company quota is reached', async () => {
ledger.countHeldConnections.mockResolvedValue(1)
const res = await POST(req('POST', '/auth', { aspsp: { name: 'SEB', country: 'SE' }, redirect_url: 'https://bokforing.example.se/cb', state: 's' }))
expect(res.status).toBe(403)
expect(await res.json()).toMatchObject({ code: 'CONNECTOR_QUOTA_EXCEEDED', limit: 1 })
expect(fetchMock).not.toHaveBeenCalled()
})
it('POST /auth rolls back its own reservation when the post-insert re-count exceeds the limit (concurrent race)', async () => {
// Two concurrent /auth calls both pre-count 0; the re-count after insert
// sees both reservations and the loser deletes its own row.
ledger.countHeldConnections.mockResolvedValueOnce(0).mockResolvedValueOnce(2)
ledger.createPendingConnection.mockResolvedValue('p-race')
const res = await POST(req('POST', '/auth', { aspsp: { name: 'SEB', country: 'SE' }, redirect_url: 'https://bokforing.example.se/cb', state: 's' }))
expect(res.status).toBe(403)
expect((await res.json()).code).toBe('CONNECTOR_QUOTA_EXCEEDED')
expect(ledger.deletePendingConnectionById).toHaveBeenCalledWith(expect.anything(), 'p-race')
})
it('POST /auth 400s without the company header', async () => {
const res = await POST(new Request('https://app.gnubok.se/api/connect/bank/auth', { method: 'POST', body: '{}' }))
expect(res.status).toBe(400)
expect((await res.json()).code).toBe('CONNECTOR_COMPANY_MISSING')
})
it('POST /sessions activates the ledger row from the connector_state', async () => {
ledger.findPendingByState.mockResolvedValue({ id: 'p1', status: 'pending' })
ledger.activateByPendingState.mockResolvedValue({ id: 'p1', status: 'active' })
ebOk({ session_id: 'sess-9', accounts: [{ uid: 'acc-1' }, { uid: 'acc-2' }] })
const res = await POST(req('POST', '/sessions', { code: 'auth-code', connector_state: 'ck1.signed.state' }))
expect(res.status).toBe(200)
expect(ledger.activateByPendingState).toHaveBeenCalledWith(expect.anything(), { keyId: 'key-1', pendingState: 'ck1.signed.state', handle: 'sess-9', accountUids: ['acc-1', 'acc-2'] })
})
it('POST /sessions refuses an invalid or foreign connector state before touching EB', async () => {
let res = await POST(req('POST', '/sessions', { code: 'c', connector_state: 'garbage' }))
expect(res.status).toBe(400)
expect((await res.json()).code).toBe('CONNECTOR_STATE_INVALID')
res = await POST(req('POST', '/sessions', { code: 'c', connector_state: 'ck1.other-key.state' }))
expect(res.status).toBe(403)
ledger.findPendingByState.mockResolvedValue(null)
res = await POST(req('POST', '/sessions', { code: 'c', connector_state: 'ck1.signed.state' }))
expect(res.status).toBe(404)
expect(fetchMock).not.toHaveBeenCalled()
})
it('POST /sessions closes the upstream session and 409s when the state was consumed concurrently', async () => {
ledger.findPendingByState.mockResolvedValue({ id: 'p1', status: 'pending' })
ledger.activateByPendingState.mockResolvedValue(null)
ebOk({ session_id: 'sess-dup', accounts: [] })
fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 })) // the revoking DELETE
const res = await POST(req('POST', '/sessions', { code: 'c', connector_state: 'ck1.signed.state' }))
expect(res.status).toBe(409)
expect((await res.json()).code).toBe('CONNECTOR_STATE_CONSUMED')
expect(fetchMock.mock.calls[1][0]).toContain('/sessions/sess-dup')
expect(fetchMock.mock.calls[1][1].method).toBe('DELETE')
})
it('GET /sessions/{id} requires ownership', async () => {
ledger.findByHandle.mockResolvedValueOnce(null)
expect((await GET(req('GET', '/sessions/sess-x'))).status).toBe(404)
ledger.findByHandle.mockResolvedValueOnce({ id: 'l1' })
ebOk({ session_id: 'sess-x' })
expect((await GET(req('GET', '/sessions/sess-x'))).status).toBe(200)
expect(ledger.touchConnection).toHaveBeenCalledWith(expect.anything(), 'l1')
})
it('GET /accounts/{uid}/transactions requires account ownership', async () => {
ledger.findByAccountUid.mockResolvedValueOnce(null)
expect((await GET(req('GET', '/accounts/acc-1/transactions'))).status).toBe(404)
ledger.findByAccountUid.mockResolvedValueOnce({ id: 'l2' })
ebOk({ transactions: [] })
const res = await GET(req('GET', '/accounts/acc-1/transactions?date_from=2026-01-01'))
expect(res.status).toBe(200)
expect(fetchMock.mock.calls[0][0]).toBe('https://api.enablebanking.com/accounts/acc-1/transactions?date_from=2026-01-01')
})
it('DELETE /sessions/{id} revokes the ledger row after the upstream delete', async () => {
ledger.findByHandle.mockResolvedValueOnce({ id: 'l3' })
fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }))
const res = await DELETE(req('DELETE', '/sessions/sess-z'))
expect(res.status).toBe(204)
expect(ledger.revokeByHandle).toHaveBeenCalledWith(expect.anything(), { keyId: 'key-1', service: 'bank', handle: 'sess-z' })
})
it('DELETE /sessions/{id} keeps the ledger row on a transient upstream error', async () => {
ledger.findByHandle.mockResolvedValueOnce({ id: 'l4' })
fetchMock.mockResolvedValueOnce(new Response('upstream boom', { status: 502 }))
const res = await DELETE(req('DELETE', '/sessions/sess-w'))
expect(res.status).toBe(502)
expect(ledger.revokeByHandle).not.toHaveBeenCalled()
})
it('rejects a non-https EB base URL before sending the JWT', async () => {
process.env.ENABLE_BANKING_API_URL = 'http://api.enablebanking.com'
ledger.findByHandle.mockResolvedValueOnce({ id: 'l5' })
await expect(GET(req('GET', '/aspsps'))).rejects.toThrow(/must be https/)
expect(fetchMock).not.toHaveBeenCalled()
process.env.ENABLE_BANKING_API_URL = 'https://api.enablebanking.com'
})
it('returns 429 with Retry-After when the global budget is exhausted', async () => {
budget.mockResolvedValue({ ok: false, scope: 'minute', retryAfterSec: 60 })
const res = await GET(req('GET', '/aspsps'))
expect(res.status).toBe(429)
expect(res.headers.get('Retry-After')).toBe('60')
expect(fetchMock).not.toHaveBeenCalled()
})
})
-348
View File
@@ -1,348 +0,0 @@
import { NextResponse } from 'next/server'
import { withConnectorAuth, type ConnectorContext } from '@/lib/connect/hosted/with-connector-auth'
import { getAuthorizationHeader } from '@/lib/connect/upstreams/enable-banking-jwt'
import { reserveUpstream } from '@/lib/connect/hosted/upstream-budget'
import {
activateByPendingState,
countHeldConnections,
createPendingConnection,
deletePendingConnectionById,
findByAccountUid,
findByHandle,
findPendingByState,
revokeByHandle,
touchConnection,
} from '@/lib/connect/hosted/ledger'
import { signConnectorState, verifyConnectorState } from '@/lib/connect/hosted/state'
/**
* Enable Banking proxy for self-hosted instances (WS3 PR5).
*
* The instance calls this with its connector key; the proxy adds Arcim's EB
* JWT and forwards to Enable Banking. The instance never holds the EB
* credential; the bank session id it gets back rests on the instance. This
* route is what makes that split safe: a strict path allowlist (never an open
* passthrough), per-key + global rate budget on every upstream call, a
* per-company connection quota checked at authorize time, and an ownership
* ledger so an instance can only use sessions/accounts it obtained through its
* own key.
*
* Consent handoff: POST /auth's redirect_url is rewritten to OUR hosted EB
* callback (already registered with EB), and the upstream `state` is replaced
* by a signed connector state carrying the instance's own return URL. The
* hosted EB callback (app/api/extensions/enable-banking/callback) detects that
* signed state and 302s the browser back to the instance with the code, so no
* new redirect URI has to be registered at Enable Banking per instance.
*/
/**
* The EB base URL must be https (http only for loopback dev): forwardToEb
* sends Arcim's EB JWT in Authorization, so a plaintext override would ship
* the credential unencrypted. Resolved lazily so a bad env fails the request
* (500 via the wrapper), never the build.
*/
function ebBaseUrl(): string {
const raw = (
process.env.ENABLE_BANKING_API_URL_PRODUCTION ||
process.env.ENABLE_BANKING_API_URL ||
'https://api.enablebanking.com'
).replace(/\/+$/, '')
const url = new URL(raw)
const loopback = url.hostname === 'localhost' || url.hostname === '127.0.0.1'
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) {
throw new Error('ENABLE_BANKING_API_URL must be https: the EB JWT is sent in Authorization')
}
return raw
}
const COMPANY_HEADER = 'x-connector-company'
const FETCH_TIMEOUT_MS = 30_000
function requireScope(ctx: ConnectorContext): NextResponse | null {
if (ctx.key.scopes.includes('bank_sync')) return null
return NextResponse.json(
{ error: 'This connector key does not include bank sync', code: 'CONNECTOR_SCOPE_MISSING' },
{ status: 403 },
)
}
function companyRef(request: Request): string | null {
return request.headers.get(COMPANY_HEADER)?.trim() || null
}
async function budgetOr429(ctx: ConnectorContext): Promise<NextResponse | null> {
const budget = await reserveUpstream(ctx.supabase, 'bank')
if (budget.ok) return null
ctx.log.warn('bank connector budget exhausted', { scope: budget.scope })
return NextResponse.json(
{ error: 'Bank connector is busy, try again shortly', code: 'CONNECTOR_RATE_LIMITED', scope: budget.scope },
{ status: 429, headers: { 'Retry-After': String(budget.retryAfterSec) } },
)
}
// Statuses that must carry no body (RFC 9110). new Response(text, {status:204})
// throws in undici, so pass a null body through for these.
const NULL_BODY_STATUS = new Set([204, 205, 304])
interface EbResult {
status: number
ok: boolean
/** null for the RFC 9110 bodyless statuses. */
text: string | null
contentType: string | null
}
/**
* Forward a request to Enable Banking with Arcim's JWT and read the body
* INSIDE the timeout window: clearing the timer at headers-received left an
* upstream that stalls mid-body holding the request open forever.
*/
async function forwardToEb(method: string, path: string, body?: unknown): Promise<EbResult> {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)
try {
const res = await fetch(`${ebBaseUrl()}${path}`, {
method,
signal: controller.signal,
// A followed redirect would resend the EB JWT to the redirect target.
redirect: 'error',
headers: {
Authorization: getAuthorizationHeader(),
'Content-Type': 'application/json',
Accept: 'application/json',
},
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
})
const text = NULL_BODY_STATUS.has(res.status) ? null : await res.text()
return { status: res.status, ok: res.ok, text, contentType: res.headers.get('content-type') }
} finally {
clearTimeout(timeout)
}
}
function passthrough(res: EbResult): NextResponse {
if (res.text === null) {
return new NextResponse(null, { status: res.status })
}
return new NextResponse(res.text, {
status: res.status,
headers: { 'Content-Type': res.contentType ?? 'application/json' },
})
}
function pathOf(request: Request): string {
const idx = request.url.indexOf('/api/connect/bank')
const rest = idx === -1 ? '' : request.url.slice(idx + '/api/connect/bank'.length)
return rest.split('?')[0].replace(/\/+$/, '') || '/'
}
function queryOf(request: Request): string {
const q = request.url.indexOf('?')
return q === -1 ? '' : request.url.slice(q)
}
const HOSTED_EB_CALLBACK = () =>
`${(process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000').replace(/\/+$/, '')}/api/extensions/enable-banking/callback`
export const GET = withConnectorAuth('connect.bank', async (request, ctx) => {
const scopeError = requireScope(ctx)
if (scopeError) return scopeError
const path = pathOf(request)
// GET /aspsps — bank list. Rate-budgeted, no ownership.
if (path === '/aspsps') {
const blocked = await budgetOr429(ctx)
if (blocked) return blocked
return passthrough(await forwardToEb('GET', `/aspsps${queryOf(request)}`))
}
// GET /sessions/{id} — must own the session.
const sessionMatch = /^\/sessions\/([^/]+)$/.exec(path)
if (sessionMatch) {
const sessionId = decodeURIComponent(sessionMatch[1])
const owned = await findByHandle(ctx.supabase, { keyId: ctx.key.id, service: 'bank', handle: sessionId })
if (!owned) return notOwned()
const blocked = await budgetOr429(ctx)
if (blocked) return blocked
await touchConnection(ctx.supabase, owned.id)
return passthrough(await forwardToEb('GET', `/sessions/${encodeURIComponent(sessionId)}`))
}
// GET /accounts/{uid}/balances|transactions — must own the account.
const acctMatch = /^\/accounts\/([^/]+)\/(balances|transactions)$/.exec(path)
if (acctMatch) {
const uid = decodeURIComponent(acctMatch[1])
const owned = await findByAccountUid(ctx.supabase, { keyId: ctx.key.id, accountUid: uid })
if (!owned) return notOwned()
const blocked = await budgetOr429(ctx)
if (blocked) return blocked
await touchConnection(ctx.supabase, owned.id)
return passthrough(await forwardToEb('GET', `/accounts/${encodeURIComponent(uid)}/${acctMatch[2]}${queryOf(request)}`))
}
return notAllowed()
})
export const POST = withConnectorAuth('connect.bank', async (request, ctx) => {
const scopeError = requireScope(ctx)
if (scopeError) return scopeError
const path = pathOf(request)
const cref = companyRef(request)
// POST /auth — start a bank authorization for one company.
if (path === '/auth') {
if (!cref) return missingCompany()
let payload: Record<string, unknown>
try {
payload = (await request.json()) as Record<string, unknown>
} catch {
return NextResponse.json({ error: 'Invalid JSON', code: 'BAD_REQUEST' }, { status: 400 })
}
const instanceReturn = typeof payload.redirect_url === 'string' ? payload.redirect_url : null
if (!instanceReturn || !isOnInstance(instanceReturn, ctx.key.instanceUrl)) {
return NextResponse.json(
{ error: 'redirect_url must be on the connector key\'s instance', code: 'CONNECTOR_REDIRECT_INVALID' },
{ status: 400 },
)
}
// Per-company connection quota (the sold package). Counting alone is a
// TOCTOU race under concurrent /auth calls, so the pending row doubles as
// a reservation: fast-reject on the pre-count, insert, then RE-count and
// roll the own row back when over the limit. Fresh pending rows reserve
// quota for the 15-minute consent window (see countHeldConnections).
const quotaExceeded = () =>
NextResponse.json(
{
error: 'Bank connection quota reached for this company',
code: 'CONNECTOR_QUOTA_EXCEEDED',
limit: ctx.key.limits.bank_connections_per_company,
},
{ status: 403 },
)
const held = await countHeldConnections(ctx.supabase, ctx.key.id, 'bank', cref)
if (held >= ctx.key.limits.bank_connections_per_company) return quotaExceeded()
const blocked = await budgetOr429(ctx)
if (blocked) return blocked
const instanceState = typeof payload.state === 'string' ? payload.state : ''
const signedState = signConnectorState({ kid: ctx.key.id, svc: 'bank', ret: instanceReturn, st: instanceState, cref })
const provider = typeof (payload.aspsp as { name?: string } | undefined)?.name === 'string'
? String((payload.aspsp as { name: string }).name)
: null
const pendingId = await createPendingConnection(ctx.supabase, {
keyId: ctx.key.id,
service: 'bank',
companyRef: cref,
provider,
pendingState: signedState,
})
const heldAfter = await countHeldConnections(ctx.supabase, ctx.key.id, 'bank', cref)
if (heldAfter > ctx.key.limits.bank_connections_per_company) {
await deletePendingConnectionById(ctx.supabase, pendingId)
return quotaExceeded()
}
// Rewrite the redirect to OUR registered callback and swap in the signed state.
const ebBody = { ...payload, redirect_url: HOSTED_EB_CALLBACK(), state: signedState }
return passthrough(await forwardToEb('POST', '/auth', ebBody))
}
// POST /sessions — finalize after consent, record the session in the ledger.
if (path === '/sessions') {
let payload: Record<string, unknown>
try {
payload = (await request.json()) as Record<string, unknown>
} catch {
return NextResponse.json({ error: 'Invalid JSON', code: 'BAD_REQUEST' }, { status: 400 })
}
// The instance sends back the signed connector state it received. The
// code is only exchanged AGAINST that state's own pending row: verified
// signature, this key, bank service, and the row still pending. Without
// the binding, a code could be exchanged under a foreign or consumed
// state, minting an upstream session the ledger never records.
const pendingState = typeof payload.connector_state === 'string' ? payload.connector_state : null
if (!pendingState) {
return NextResponse.json({ error: 'Missing connector_state', code: 'BAD_REQUEST' }, { status: 400 })
}
const verified = verifyConnectorState(pendingState)
if (!verified.ok) {
return NextResponse.json({ error: 'Invalid connector state', code: 'CONNECTOR_STATE_INVALID' }, { status: 400 })
}
if (verified.payload.kid !== ctx.key.id || verified.payload.svc !== 'bank') {
return NextResponse.json({ error: 'State does not belong to this key', code: 'CONNECTOR_STATE_INVALID' }, { status: 403 })
}
const pendingRow = await findPendingByState(ctx.supabase, { keyId: ctx.key.id, pendingState })
if (!pendingRow) return notOwned()
const blocked = await budgetOr429(ctx)
if (blocked) return blocked
const ebRes = await forwardToEb('POST', '/sessions', { code: payload.code })
if (ebRes.ok && ebRes.text !== null) {
try {
const session = JSON.parse(ebRes.text) as { session_id?: string; accounts?: Array<{ uid?: string }> }
if (session.session_id) {
const accountUids = (session.accounts ?? [])
.map((a) => a.uid)
.filter((u): u is string => typeof u === 'string')
const activated = await activateByPendingState(ctx.supabase, {
keyId: ctx.key.id,
pendingState,
handle: session.session_id,
accountUids,
})
if (!activated) {
// The pending row was consumed between the precheck and now (a
// concurrent replay of the same state). An unrecorded upstream
// session must not be handed out: close it and refuse.
await forwardToEb('DELETE', `/sessions/${encodeURIComponent(session.session_id)}`)
return NextResponse.json(
{ error: 'Connector state already consumed', code: 'CONNECTOR_STATE_CONSUMED' },
{ status: 409 },
)
}
}
} catch (err) {
ctx.log.warn('could not record session in ledger', { err: err instanceof Error ? err.message : String(err) })
}
}
return passthrough(ebRes)
}
return notAllowed()
})
export const DELETE = withConnectorAuth('connect.bank', async (request, ctx) => {
const scopeError = requireScope(ctx)
if (scopeError) return scopeError
const path = pathOf(request)
const sessionMatch = /^\/sessions\/([^/]+)$/.exec(path)
if (!sessionMatch) return notAllowed()
const sessionId = decodeURIComponent(sessionMatch[1])
const owned = await findByHandle(ctx.supabase, { keyId: ctx.key.id, service: 'bank', handle: sessionId })
if (!owned) return notOwned()
const blocked = await budgetOr429(ctx)
if (blocked) return blocked
const res = await forwardToEb('DELETE', `/sessions/${encodeURIComponent(sessionId)}`)
// Revoke the ledger row only when the upstream delete actually took (or the
// session is already gone upstream): revoking on a transient EB error would
// leave the remote session alive but permanently unreachable via the proxy.
if (res.ok || res.status === 404) {
await revokeByHandle(ctx.supabase, { keyId: ctx.key.id, service: 'bank', handle: sessionId })
}
return passthrough(res)
})
function isOnInstance(url: string, instanceUrl: string | null): boolean {
if (!instanceUrl) return false
try {
return new URL(url).origin === new URL(instanceUrl).origin
} catch {
return false
}
}
function notAllowed(): NextResponse {
return NextResponse.json({ error: 'Not allowed', code: 'CONNECTOR_PATH_NOT_ALLOWED' }, { status: 403 })
}
function notOwned(): NextResponse {
return NextResponse.json({ error: 'Unknown connection for this key', code: 'CONNECTOR_NOT_OWNED' }, { status: 404 })
}
function missingCompany(): NextResponse {
return NextResponse.json({ error: 'Missing X-Connector-Company header', code: 'CONNECTOR_COMPANY_MISSING' }, { status: 400 })
}
@@ -1,127 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
const KEY = {
id: '11111111-1111-4111-8111-111111111111',
orgNumber: '5561234567',
instanceUrl: null as string | null,
scopes: ['bank_sync', 'skatteverket', 'org_lookup', 'migration'],
status: 'active' as const,
currentPeriodEnd: '2027-01-01T00:00:00.000Z',
}
type UpdateResult = { error: unknown; data: Array<{ instance_url: string | null }> | null }
const updateResults: UpdateResult[] = []
const updateSelect = vi.fn(() => Promise.resolve(updateResults.shift() ?? { error: null, data: [{ instance_url: null }] }))
const updateIs = vi.fn(() => ({ select: updateSelect }))
const updateEq = vi.fn(() => ({ is: updateIs, select: updateSelect }))
const update = vi.fn((_payload: Record<string, unknown>) => ({ eq: updateEq }))
const from = vi.fn(() => ({ update }))
const logWarn = vi.fn()
// The wrapper is exercised in its own test; here it is replaced by a
// pass-through that injects the validated key so the handler logic is what
// gets tested.
vi.mock('@/lib/connect/hosted/with-connector-auth', () => ({
withConnectorAuth: (_op: string, handler: (req: Request, ctx: unknown) => Promise<Response>) => (req: Request) =>
handler(req, {
requestId: 'conn_test',
log: { info: vi.fn(), warn: logWarn, error: vi.fn() },
supabase: { from },
key: { ...KEY, instanceUrl: currentInstanceUrl },
}),
}))
let currentInstanceUrl: string | null = null
import { GET, POST } from '../route'
beforeEach(() => {
vi.clearAllMocks()
currentInstanceUrl = null
updateResults.length = 0
})
describe('GET /api/connect/entitlements', () => {
it('returns the key entitlements', async () => {
const res = await GET(createMockRequest('/api/connect/entitlements'))
const { status, body } = await parseJsonResponse<{ data: Record<string, unknown> }>(res)
expect(status).toBe(200)
expect(body.data).toMatchObject({
status: 'active',
scopes: KEY.scopes,
current_period_end: KEY.currentPeriodEnd,
org_number: '5561234567',
instance_url: null,
})
expect(typeof body.data.server_time).toBe('string')
})
})
describe('POST /api/connect/entitlements', () => {
it('400 on an invalid report', async () => {
const res = await POST(createMockRequest('/api/connect/entitlements', { method: 'POST', body: { active_company_count: -1 } }))
expect(res.status).toBe(400)
expect(update).not.toHaveBeenCalled()
})
it('records the active company count and pins instance_url on first report', async () => {
const res = await POST(
createMockRequest('/api/connect/entitlements', {
method: 'POST',
body: { active_company_count: 12, instance_url: 'https://bokforing.example.se', app_version: '1.2.3' },
}),
)
const { status, body } = await parseJsonResponse<{ data: { instance_url: string | null } }>(res)
expect(status).toBe(200)
expect(from).toHaveBeenCalledWith('connector_keys')
const payload = update.mock.calls[0][0]
expect(payload).toMatchObject({ active_company_count: 12, instance_url: 'https://bokforing.example.se' })
expect(typeof payload.last_synced_at).toBe('string')
expect(updateEq).toHaveBeenCalledWith('id', KEY.id)
expect(body.data.instance_url).toBe('https://bokforing.example.se')
})
// A leaked key must not be able to re-home the subscription.
it('never moves a pinned instance_url; logs the mismatch', async () => {
currentInstanceUrl = 'https://bokforing.example.se'
const res = await POST(
createMockRequest('/api/connect/entitlements', {
method: 'POST',
body: { active_company_count: 3, instance_url: 'https://evil.example.com' },
}),
)
expect(res.status).toBe(200)
const payload = update.mock.calls[0][0]
expect(payload.instance_url).toBeUndefined()
expect(logWarn).toHaveBeenCalled()
const { body } = await parseJsonResponse<{ data: { instance_url: string | null } }>(res)
expect(body.data.instance_url).toBe('https://bokforing.example.se')
})
it('500 when the update fails', async () => {
updateResults.push({ error: { message: 'boom' }, data: null })
const res = await POST(createMockRequest('/api/connect/entitlements', { method: 'POST', body: { active_company_count: 1 } }))
expect(res.status).toBe(500)
})
// Two concurrent FIRST reports: the pinning update is conditional on
// instance_url IS NULL, so the loser affects no row and must surface the
// winner's pin instead of its own URL.
it('losing the pin race keeps the first pin and reports it back', async () => {
updateResults.push({ error: null, data: [] }) // conditional pin: no row matched
updateResults.push({ error: null, data: [{ instance_url: 'https://first.example.se' }] }) // counter-only fallback
const res = await POST(
createMockRequest('/api/connect/entitlements', {
method: 'POST',
body: { active_company_count: 2, instance_url: 'https://second.example.se' },
}),
)
const { status, body } = await parseJsonResponse<{ data: { instance_url: string | null } }>(res)
expect(status).toBe(200)
expect(body.data.instance_url).toBe('https://first.example.se')
expect(logWarn).toHaveBeenCalled()
expect(update).toHaveBeenCalledTimes(2)
expect(update.mock.calls[1][0]).not.toHaveProperty('instance_url')
})
})
-99
View File
@@ -1,99 +0,0 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { validateBody } from '@/lib/api/validate'
import { withConnectorAuth, type ConnectorContext } from '@/lib/connect/hosted/with-connector-auth'
import type { ConnectorEntitlements } from '@/lib/connect/contract'
/**
* /api/connect/entitlements: what a self-hosted instance's connector key
* entitles it to. The instance's hourly sync (lib/connect/instance/sync.ts)
* POSTs its active company count (quantity billing input) and gets back
* status, scopes and the paid period; it then writes source='connector'
* capability grants that expire at min(now + 72h, period_end + 3d), so the
* grant rows are the offline cache and the hosted service only has to be
* reachable once every three days.
*
* GET -> entitlements (no side effects beyond last_seen_at)
* POST -> { active_company_count, instance_url?, app_version? } -> entitlements;
* records the count and pins instance_url on first report.
*/
const SyncReportSchema = z.object({
active_company_count: z.number().int().min(0).max(1_000_000),
instance_url: z.string().url().max(512).optional(),
app_version: z.string().max(64).optional(),
})
function entitlementsOf(ctx: ConnectorContext, instanceUrl: string | null): ConnectorEntitlements {
return {
status: ctx.key.status,
scopes: ctx.key.scopes,
current_period_end: ctx.key.currentPeriodEnd,
org_number: ctx.key.orgNumber,
instance_url: instanceUrl,
server_time: new Date().toISOString(),
}
}
export const GET = withConnectorAuth('connect.entitlements', async (_request, ctx) => {
return NextResponse.json({ data: entitlementsOf(ctx, ctx.key.instanceUrl) })
})
export const POST = withConnectorAuth('connect.entitlements', async (request, ctx) => {
const parsed = await validateBody(request, SyncReportSchema, { log: ctx.log, operation: 'connect.entitlements' })
if (!parsed.success) return parsed.response
const report = parsed.data
// instance_url is pinned: the first report claims it, later reports that
// disagree are logged but never move it (a leaked key cannot re-home the
// subscription to another instance).
let instanceUrl = ctx.key.instanceUrl
const pinNow = !!report.instance_url && !instanceUrl
if (report.instance_url && instanceUrl && instanceUrl !== report.instance_url) {
ctx.log.warn('sync reported a different instance_url than the pinned one', {
pinned: instanceUrl,
reported: report.instance_url,
})
}
if (pinNow) instanceUrl = report.instance_url ?? null
const lastSyncedAt = new Date().toISOString()
// Two literal payloads rather than one built object: the no-phantom-columns
// scanner resolves literals only. The pinning update additionally filters
// on instance_url IS NULL so two concurrent first reports cannot both pin:
// the loser's conditional update matches no row and re-reads the winner's
// URL below (first-report-wins, later reports never move the pin).
const { error, data: pinned } = pinNow
? await ctx.supabase
.from('connector_keys')
.update({
active_company_count: report.active_company_count,
last_synced_at: lastSyncedAt,
instance_url: instanceUrl,
})
.eq('id', ctx.key.id)
.is('instance_url', null)
.select('instance_url')
: await ctx.supabase
.from('connector_keys')
.update({ active_company_count: report.active_company_count, last_synced_at: lastSyncedAt })
.eq('id', ctx.key.id)
.select('instance_url')
if (error) {
ctx.log.error('failed to record connector sync', error)
return NextResponse.json({ error: 'Failed to record sync', code: 'INTERNAL_ERROR' }, { status: 500 })
}
if (pinNow && (pinned ?? []).length === 0) {
// Lost the pin race: record the counters and surface the winner's pin.
const { data: existing } = await ctx.supabase
.from('connector_keys')
.update({ active_company_count: report.active_company_count, last_synced_at: lastSyncedAt })
.eq('id', ctx.key.id)
.select('instance_url')
instanceUrl = (existing?.[0] as { instance_url: string | null } | undefined)?.instance_url ?? null
ctx.log.warn('instance_url pin race lost; keeping the first pin', {
reported: report.instance_url,
pinned: instanceUrl,
})
}
return NextResponse.json({ data: entitlementsOf(ctx, instanceUrl) })
})
@@ -1,429 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { PeppolTransportError } from '@/lib/invoices/peppol-transport'
let currentKey = {
id: 'key-1',
orgNumber: '5561234567',
instanceUrl: 'https://bokforing.example.se',
scopes: ['peppol'],
status: 'active' as const,
currentPeriodEnd: null as string | null,
limits: { bank_connections_per_company: 1, skv_connections_per_company: 1, peppol_connections_per_company: 1, sync_min_interval_s: 0 },
}
const h = vi.hoisted(() => ({
budget: vi.fn(),
ledger: {
countHeldConnections: vi.fn(),
deletePendingConnectionById: vi.fn(),
createPendingConnection: vi.fn(),
activateByPendingState: vi.fn(),
findByAccountUid: vi.fn(),
revokeByHandle: vi.fn(),
touchConnection: vi.fn(),
},
peppolLedger: {
countConnectorPeppolRegistrations: vi.fn(),
findOwnedPeppolSubmission: vi.fn(),
getPeppolAllowedIdentifiers: vi.fn(),
isHostedPeppolParticipantLive: vi.fn(),
isPeppolParticipantHeld: vi.fn(),
listActivePeppolParticipants: vi.fn(),
recordPeppolSubmission: vi.fn(),
},
registration: { countLivePeppolRegistrations: vi.fn(), getPeppolReceivingCap: vi.fn() },
transport: {
provider: 'qvalia',
lookupRecipient: vi.fn(),
submit: vi.fn(),
verifyWebhook: vi.fn(),
retrieveEvidence: vi.fn(),
pollDeliveryStatus: vi.fn(),
registerRecipient: vi.fn(),
unregisterRecipient: vi.fn(),
listInboundDocuments: vi.fn(),
fetchInboundDocumentXml: vi.fn(),
},
qvaliaConfigured: { value: true },
archive: { rows: [] as unknown[], single: null as unknown, ins: [] as Array<[string, unknown]> },
}))
vi.mock('@/lib/connect/hosted/with-connector-auth', () => ({
withConnectorAuth: (_op: string, handler: (req: Request, ctx: unknown) => Promise<Response>) => (req: Request) =>
handler(req, {
requestId: 'conn_test',
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
supabase: {
from: (table: string) => {
if (table !== 'peppol_inbound_documents') throw new Error(`unexpected table ${table}`)
const chain: Record<string, unknown> = {}
const self = () => chain
for (const m of ['select', 'eq', 'order']) chain[m] = self
chain.in = (col: string, vals: unknown) => { h.archive.ins.push([col, vals]); return chain }
chain.limit = () => Promise.resolve({ data: h.archive.rows, error: null })
chain.maybeSingle = () => Promise.resolve({ data: h.archive.single, error: null })
return chain
},
},
key: currentKey,
}),
}))
vi.mock('@/lib/connect/hosted/upstream-budget', () => ({ reserveUpstream: (...a: unknown[]) => h.budget(...a) }))
vi.mock('@/lib/connect/hosted/ledger', () => ({ ...h.ledger, hashHandle: (s: string) => `h:${s}` }))
vi.mock('@/lib/connect/hosted/peppol-ledger', async () => {
const actual = await vi.importActual<typeof import('@/lib/connect/hosted/peppol-ledger')>('@/lib/connect/hosted/peppol-ledger')
return {
...h.peppolLedger,
peppolHandle: actual.peppolHandle,
parsePeppolHandle: actual.parsePeppolHandle,
describePeppolUpstreamFailure: actual.describePeppolUpstreamFailure,
}
})
vi.mock('@/lib/invoices/peppol-registration', () => h.registration)
vi.mock('@/lib/invoices/transports/qvalia', () => ({
QVALIA_PROVIDER: 'qvalia',
readQvaliaConfigFromEnv: () => (h.qvaliaConfigured.value ? { apiKey: 'k' } : null),
createQvaliaTransport: () => h.transport,
}))
import { POST, PUT, DELETE } from '../route'
const participant = { scheme: '0007', identifier: '5561234567' }
const businessCard = { companyName: 'Testbolaget AB', countryCode: 'SE', orgNumber: '5561234567' }
const documentTypes = [{ processId: 'urn:fdc:peppol.eu:2017:poacc:billing:01:1.0', documentTypeId: 'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2::Invoice' }]
function req(method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Request {
return new Request(`https://app.gnubok.se/api/connect/peppol${path}`, {
method,
headers: { 'x-connector-company': 'company-1', 'content-type': 'application/json', ...headers },
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
})
}
beforeEach(() => {
vi.clearAllMocks()
currentKey = { ...currentKey, scopes: ['peppol'], limits: { ...currentKey.limits, peppol_connections_per_company: 1 } }
h.budget.mockResolvedValue({ ok: true })
h.qvaliaConfigured.value = true
h.archive.rows = []
h.archive.single = null
h.archive.ins = []
h.ledger.findByAccountUid.mockResolvedValue(null)
h.ledger.countHeldConnections.mockResolvedValue(0)
h.ledger.createPendingConnection.mockResolvedValue('pending-1')
h.ledger.activateByPendingState.mockResolvedValue({ id: 'row-1' })
h.peppolLedger.isPeppolParticipantHeld.mockResolvedValue(false)
h.peppolLedger.isHostedPeppolParticipantLive.mockResolvedValue(false)
h.peppolLedger.countConnectorPeppolRegistrations.mockResolvedValue(0)
h.peppolLedger.getPeppolAllowedIdentifiers.mockResolvedValue(new Set(['5561234567']))
h.peppolLedger.listActivePeppolParticipants.mockResolvedValue([participant])
h.registration.getPeppolReceivingCap.mockReturnValue(null)
h.registration.countLivePeppolRegistrations.mockResolvedValue(0)
})
describe('scope, configuration and path allowlist', () => {
it('403s when the key lacks the peppol scope', async () => {
currentKey = { ...currentKey, scopes: ['bank_sync'] }
const res = await POST(req('POST', '/lookup', { participant }))
expect(res.status).toBe(403)
expect((await res.json()).code).toBe('CONNECTOR_SCOPE_MISSING')
})
it('503s when the hosted access point is not configured', async () => {
h.qvaliaConfigured.value = false
const res = await POST(req('POST', '/lookup', { participant }))
expect(res.status).toBe(503)
expect((await res.json()).code).toBe('CONNECTOR_UPSTREAM_UNCONFIGURED')
})
it('refuses unknown operations', async () => {
const res = await POST(req('POST', '/partner/123/anything', {}))
expect(res.status).toBe(403)
expect((await res.json()).code).toBe('CONNECTOR_PATH_NOT_ALLOWED')
})
it('400s on a malformed body', async () => {
const res = await POST(req('POST', '/lookup', { participant: { scheme: 'abc', identifier: '' } }))
expect(res.status).toBe(400)
expect(h.transport.lookupRecipient).not.toHaveBeenCalled()
})
})
describe('lookup and submit', () => {
it('forwards a lookup after reserving budget', async () => {
h.transport.lookupRecipient.mockResolvedValue({ reachable: true, participant, capabilities: [], checkedAt: 'now' })
const res = await POST(req('POST', '/lookup', { participant }))
expect(res.status).toBe(200)
expect((await res.json()).reachable).toBe(true)
expect(h.budget).toHaveBeenCalledWith(expect.anything(), 'peppol')
})
it('429s with Retry-After when the global budget is exhausted', async () => {
h.budget.mockResolvedValue({ ok: false, scope: 'minute', retryAfterSec: 17 })
const res = await POST(req('POST', '/lookup', { participant }))
expect(res.status).toBe(429)
expect(res.headers.get('Retry-After')).toBe('17')
expect(h.transport.lookupRecipient).not.toHaveBeenCalled()
})
const submissionBody = () => ({
idempotencyKey: 'idem-1',
tenantReference: 'company-OTHER',
sender: participant,
recipient: { scheme: '0007', identifier: '5569876543' },
documentTypeId: documentTypes[0].documentTypeId,
processId: documentTypes[0].processId,
filename: 'inv.xml',
contentType: 'application/xml',
document: '<Invoice/>',
documentSha256: 'a'.repeat(64),
})
it('refuses to send as a participant this key has not registered, or registered for another company', async () => {
h.ledger.findByAccountUid.mockResolvedValue(null)
let res = await POST(req('POST', '/submit', submissionBody()))
expect(res.status).toBe(403)
expect((await res.json()).code).toBe('CONNECTOR_PEPPOL_SENDER_NOT_REGISTERED')
h.ledger.findByAccountUid.mockResolvedValue({ id: 'row-other', company_ref: 'company-2' })
res = await POST(req('POST', '/submit', submissionBody()))
expect(res.status).toBe(403)
expect(h.transport.submit).not.toHaveBeenCalled()
})
it('submits under the header company and records ownership of the provider submission id', async () => {
h.ledger.findByAccountUid.mockResolvedValue({ id: 'row-sender', company_ref: 'company-1' })
h.transport.submit.mockResolvedValue({ provider: 'qvalia', providerSubmissionId: 'int-9', idempotencyKey: 'idem-1', tenantReference: 'company-1', acceptedAt: 'now' })
const submission = {
idempotencyKey: 'idem-1',
tenantReference: 'company-OTHER',
sender: participant,
recipient: { scheme: '0007', identifier: '5569876543' },
documentTypeId: documentTypes[0].documentTypeId,
processId: documentTypes[0].processId,
filename: 'inv.xml',
contentType: 'application/xml',
document: '<Invoice/>',
documentSha256: 'a'.repeat(64),
}
const res = await POST(req('POST', '/submit', submission))
expect(res.status).toBe(200)
expect(h.transport.submit).toHaveBeenCalledWith(expect.objectContaining({ tenantReference: 'company-1' }))
expect(h.peppolLedger.recordPeppolSubmission).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
keyId: 'key-1', companyRef: 'company-1', providerSubmissionId: 'int-9', idempotencyKey: 'idem-1',
}))
})
it('requires the company header for submit', async () => {
const res = await POST(new Request('https://app.gnubok.se/api/connect/peppol/submit', { method: 'POST', body: '{}' }))
expect(res.status).toBe(400)
expect((await res.json()).code).toBe('CONNECTOR_COMPANY_MISSING')
})
it('maps a non-retryable provider rejection to 422 and a retryable one to 502', async () => {
h.transport.lookupRecipient.mockRejectedValueOnce(new PeppolTransportError('rejected', { retryable: false, detail: 'bad id' }))
let res = await POST(req('POST', '/lookup', { participant }))
expect(res.status).toBe(422)
expect(await res.json()).toMatchObject({ code: 'CONNECTOR_UPSTREAM_ERROR', retryable: false, detail: 'bad id' })
h.transport.lookupRecipient.mockRejectedValueOnce(new PeppolTransportError('down', { retryable: true }))
res = await POST(req('POST', '/lookup', { participant }))
expect(res.status).toBe(502)
expect((await res.json()).retryable).toBe(true)
})
})
describe('status and evidence are ownership-gated', () => {
it('404s for a submission this key did not make, and looks it up under the header company', async () => {
h.peppolLedger.findOwnedPeppolSubmission.mockResolvedValue(null)
const res = await POST(req('POST', '/status', { providerSubmissionId: 'int-foreign' }))
expect(res.status).toBe(404)
expect((await res.json()).code).toBe('CONNECTOR_NOT_OWNED')
expect(h.peppolLedger.findOwnedPeppolSubmission).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ keyId: 'key-1', companyRef: 'company-1', providerSubmissionId: 'int-foreign' }))
expect(h.transport.pollDeliveryStatus).not.toHaveBeenCalled()
const noCompany = await POST(new Request('https://app.gnubok.se/api/connect/peppol/status', { method: 'POST', body: JSON.stringify({ providerSubmissionId: 'int-9' }) }))
expect(noCompany.status).toBe(400)
})
it('polls and retrieves evidence for an owned submission', async () => {
h.peppolLedger.findOwnedPeppolSubmission.mockResolvedValue({ id: 's1', company_ref: 'company-1' })
h.transport.pollDeliveryStatus.mockResolvedValue([{ eventCode: 'status_poll' }])
h.transport.retrieveEvidence.mockResolvedValue([{ evidenceType: 'qvalia_message_record' }])
const status = await POST(req('POST', '/status', { providerSubmissionId: 'int-9' }))
expect(await status.json()).toEqual([{ eventCode: 'status_poll' }])
const evidence = await POST(req('POST', '/evidence', { providerSubmissionId: 'int-9' }))
expect(await evidence.json()).toEqual([{ evidenceType: 'qvalia_message_record' }])
})
})
describe('receiving registration', () => {
const body = { participant, businessCard, documentTypes }
it('registers a new participant: reserves quota, calls the access point, activates the ledger row', async () => {
h.transport.registerRecipient.mockResolvedValue({ status: 'registered', participant, providerAccountReference: '5560000000', raw: { secret: 'x' } })
const res = await PUT(req('PUT', '/recipient', body))
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toEqual({ status: 'registered', participant, providerAccountReference: 'accounted-connector', raw: {} })
expect(h.ledger.createPendingConnection).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ service: 'peppol', companyRef: 'company-1', provider: 'qvalia' }))
expect(h.ledger.activateByPendingState).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ handle: '0007:5561234567', accountUids: ['0007:5561234567'] }))
expect(h.transport.registerRecipient).toHaveBeenCalledWith(expect.objectContaining({ participant }))
})
it('refuses a participant another key already holds, before touching the access point', async () => {
h.peppolLedger.isPeppolParticipantHeld.mockResolvedValue(true)
const res = await PUT(req('PUT', '/recipient', body))
expect(res.status).toBe(409)
expect((await res.json()).code).toBe('CONNECTOR_PEPPOL_PARTICIPANT_TAKEN')
expect(h.transport.registerRecipient).not.toHaveBeenCalled()
})
it('refuses a participant a hosted company holds', async () => {
h.peppolLedger.isHostedPeppolParticipantLive.mockResolvedValue(true)
const res = await PUT(req('PUT', '/recipient', body))
expect(res.status).toBe(409)
expect(h.transport.registerRecipient).not.toHaveBeenCalled()
})
it('enforces the per-company quota with a reservation re-count', async () => {
h.ledger.countHeldConnections.mockResolvedValueOnce(0).mockResolvedValueOnce(2)
const res = await PUT(req('PUT', '/recipient', body))
expect(res.status).toBe(403)
expect((await res.json()).code).toBe('CONNECTOR_QUOTA_EXCEEDED')
expect(h.ledger.deletePendingConnectionById).toHaveBeenCalledWith(expect.anything(), 'pending-1')
expect(h.transport.registerRecipient).not.toHaveBeenCalled()
})
it('shares the provider-account cap between hosted companies and connector instances', async () => {
h.registration.getPeppolReceivingCap.mockReturnValue(10)
h.registration.countLivePeppolRegistrations.mockResolvedValue(7)
h.peppolLedger.countConnectorPeppolRegistrations.mockResolvedValue(3)
const res = await PUT(req('PUT', '/recipient', body))
expect(res.status).toBe(403)
expect((await res.json()).code).toBe('PEPPOL_REGISTRATION_CAP_REACHED')
expect(h.ledger.createPendingConnection).not.toHaveBeenCalled()
})
it('re-checks the cap after its own reservation and rolls back when a concurrent registration won', async () => {
h.registration.getPeppolReceivingCap.mockReturnValue(10)
h.registration.countLivePeppolRegistrations.mockResolvedValue(7)
h.peppolLedger.countConnectorPeppolRegistrations.mockResolvedValueOnce(2).mockResolvedValueOnce(4)
const res = await PUT(req('PUT', '/recipient', body))
expect(res.status).toBe(403)
expect((await res.json()).code).toBe('PEPPOL_REGISTRATION_CAP_REACHED')
expect(h.ledger.deletePendingConnectionById).toHaveBeenCalledWith(expect.anything(), 'pending-1')
expect(h.transport.registerRecipient).not.toHaveBeenCalled()
})
it('refuses a participant identifier the key is not authorized to publish', async () => {
h.peppolLedger.getPeppolAllowedIdentifiers.mockResolvedValue(new Set(['5560000001']))
const res = await PUT(req('PUT', '/recipient', body))
expect(res.status).toBe(403)
expect((await res.json()).code).toBe('CONNECTOR_PEPPOL_PARTICIPANT_NOT_ALLOWED')
expect(h.peppolLedger.isPeppolParticipantHeld).not.toHaveBeenCalled()
expect(h.transport.registerRecipient).not.toHaveBeenCalled()
})
it('refuses to register through an access point that cannot deregister', async () => {
const original = h.transport.unregisterRecipient
;(h.transport as { unregisterRecipient?: unknown }).unregisterRecipient = undefined
try {
const res = await PUT(req('PUT', '/recipient', body))
expect(res.status).toBe(422)
expect((await res.json()).code).toBe('PEPPOL_RECEIVING_UNSUPPORTED')
const del = await DELETE(req('DELETE', '/recipient?scheme=0007&identifier=5561234567'))
expect(del.status).toBe(404)
h.ledger.findByAccountUid.mockResolvedValue({ id: 'row-1', company_ref: 'company-1' })
const del2 = await DELETE(req('DELETE', '/recipient?scheme=0007&identifier=5561234567'))
expect(del2.status).toBe(422)
expect(h.ledger.revokeByHandle).not.toHaveBeenCalled()
} finally {
h.transport.unregisterRecipient = original
}
})
it('rolls the reservation back when the access point rejects', async () => {
h.transport.registerRecipient.mockRejectedValue(new PeppolTransportError('nope', { retryable: false }))
const res = await PUT(req('PUT', '/recipient', body))
expect(res.status).toBe(422)
expect(h.ledger.deletePendingConnectionById).toHaveBeenCalledWith(expect.anything(), 'pending-1')
})
it('unregisters upstream and answers 409 when activation loses the participant race', async () => {
h.transport.registerRecipient.mockResolvedValue({ status: 'registered', participant, providerAccountReference: 'x', raw: {} })
h.ledger.activateByPendingState.mockRejectedValue(new Error('duplicate key value violates unique constraint "idx_connector_connections_handle"'))
const res = await PUT(req('PUT', '/recipient', body))
expect(res.status).toBe(409)
expect(h.transport.unregisterRecipient).toHaveBeenCalledWith(participant)
expect(h.ledger.deletePendingConnectionById).toHaveBeenCalledWith(expect.anything(), 'pending-1')
})
it('refuses to touch a participant this key holds for another company', async () => {
h.ledger.findByAccountUid.mockResolvedValue({ id: 'row-2', company_ref: 'company-2' })
const res = await PUT(req('PUT', '/recipient', body))
expect(res.status).toBe(409)
expect(h.transport.registerRecipient).not.toHaveBeenCalled()
})
it('re-registers an owned participant without consuming quota', async () => {
h.ledger.findByAccountUid.mockResolvedValue({ id: 'row-1', company_ref: 'company-1' })
h.transport.registerRecipient.mockResolvedValue({ status: 'updated', participant, providerAccountReference: 'x', raw: {} })
const res = await PUT(req('PUT', '/recipient', body))
expect(res.status).toBe(200)
expect((await res.json()).status).toBe('updated')
expect(h.ledger.createPendingConnection).not.toHaveBeenCalled()
expect(h.ledger.touchConnection).toHaveBeenCalledWith(expect.anything(), 'row-1')
})
it('DELETE unregisters only an owned participant of the header company and revokes the ledger row', async () => {
let res = await DELETE(req('DELETE', '/recipient?scheme=0007&identifier=5561234567'))
expect(res.status).toBe(404)
h.ledger.findByAccountUid.mockResolvedValue({ id: 'row-2', company_ref: 'company-2' })
res = await DELETE(req('DELETE', '/recipient?scheme=0007&identifier=5561234567'))
expect(res.status).toBe(404)
expect(h.transport.unregisterRecipient).not.toHaveBeenCalled()
h.ledger.findByAccountUid.mockResolvedValue({ id: 'row-1', company_ref: 'company-1' })
res = await DELETE(req('DELETE', '/recipient?scheme=0007&identifier=5561234567'))
expect(res.status).toBe(204)
expect(h.transport.unregisterRecipient).toHaveBeenCalledWith(participant)
expect(h.ledger.revokeByHandle).toHaveBeenCalledWith(expect.anything(), { keyId: 'key-1', service: 'peppol', handle: '0007:5561234567' })
})
})
describe('inbound documents come from the hosted archive, scoped to owned participants', () => {
it('lists only documents addressed to a participant this key holds', async () => {
h.archive.rows = [
{ provider_document_id: 'doc-1', document_type: 'Invoice', ubl_json: { a: 1 }, received_at: 't1', recipient_scheme: '0007', recipient_identifier: '5561234567' },
{ provider_document_id: 'doc-2', document_type: 'Invoice', ubl_json: { b: 2 }, received_at: 't2', recipient_scheme: '0088', recipient_identifier: '5561234567' },
]
const res = await POST(req('POST', '/inbound/list', { documentType: 'Invoice', limit: 10 }))
expect(res.status).toBe(200)
const items = await res.json()
expect(items).toEqual([{ provider: 'qvalia', providerDocumentId: 'doc-1', documentType: 'Invoice', payload: { a: 1 }, receivedAt: 't1' }])
// One query per scheme with that scheme's identifiers: exact pairs, so
// neither foreign nor cross-pair rows can consume the limit.
expect(h.archive.ins).toEqual([['recipient_identifier', ['5561234567']]])
expect(h.transport.listInboundDocuments).not.toHaveBeenCalled()
})
it('answers an empty list without touching the archive when the key holds no participant', async () => {
h.peppolLedger.listActivePeppolParticipants.mockResolvedValue([])
const res = await POST(req('POST', '/inbound/list', { documentType: 'Invoice' }))
expect(await res.json()).toEqual([])
})
it('serves the archived XML for an owned document and 404s otherwise', async () => {
h.archive.single = { xml_payload: '<Invoice/>', recipient_scheme: '0007', recipient_identifier: '5561234567' }
let res = await POST(req('POST', '/inbound/xml', { providerDocumentId: 'doc-1', documentType: 'Invoice' }))
expect(await res.json()).toEqual({ xml: '<Invoice/>' })
h.archive.single = { xml_payload: '<Invoice/>', recipient_scheme: '0007', recipient_identifier: '5569999999' }
res = await POST(req('POST', '/inbound/xml', { providerDocumentId: 'doc-1', documentType: 'Invoice' }))
expect(res.status).toBe(404)
})
it('fetches the XML live when the archive only holds JSON', async () => {
h.archive.single = { xml_payload: null, recipient_scheme: '0007', recipient_identifier: '5561234567' }
h.transport.fetchInboundDocumentXml.mockResolvedValue('<CreditNote/>')
const res = await POST(req('POST', '/inbound/xml', { providerDocumentId: 'doc-1', documentType: 'CreditNote' }))
expect(await res.json()).toEqual({ xml: '<CreditNote/>' })
expect(h.transport.fetchInboundDocumentXml).toHaveBeenCalledWith('doc-1', 'CreditNote')
})
})
File diff suppressed because it is too large Load Diff
@@ -1,123 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
let key = {
id: 'key-1', orgNumber: 'x', instanceUrl: 'https://i', scopes: ['skatteverket'], status: 'active' as const,
currentPeriodEnd: null as string | null, limits: { bank_connections_per_company: 1, skv_connections_per_company: 1, sync_min_interval_s: 0 },
}
vi.mock('@/lib/connect/hosted/with-connector-auth', () => ({
withConnectorAuth: (_o: string, h: (r: Request, c: unknown) => Promise<Response>) => (r: Request) =>
h(r, { requestId: 't', log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, supabase: {}, key }),
}))
const hh = vi.hoisted(() => ({ budget: vi.fn(), find: vi.fn(), touch: vi.fn() }))
vi.mock('@/lib/connect/hosted/upstream-budget', () => ({ reserveUpstream: (...a: unknown[]) => hh.budget(...a) }))
vi.mock('@/lib/connect/hosted/ledger', () => ({ findByHandle: (...a: unknown[]) => hh.find(...a), touchConnection: (...a: unknown[]) => hh.touch(...a) }))
vi.mock('@/lib/connect/upstreams/skatteverket-oauth', () => ({
SKV_API_BASES: {
moms: () => 'https://api.skv/momsdeklaration/v1',
skattekonto: () => 'https://api.skv/skattekonto/v2',
'agd-inlamning': () => 'https://api.skv/agd/inlamning/v1',
'agd-period': () => 'https://api.skv/agd/period/v1',
},
skvGatewayHeaders: () => ({ Client_Id: 'gw', Client_Secret: 'gws', skv_client_correlation_id: 'corr' }),
}))
const fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
import { GET, POST } from '../route'
function req(method: string, path: string, token = 'user-token', body?: string): Request {
const headers: Record<string, string> = { 'x-connector-upstream-authorization': `Bearer ${token}` }
return new Request(`https://app.gnubok.se/api/connect/skv/api${path}`, { method, headers, ...(body !== undefined ? { body } : {}) })
}
function skvOk(body: unknown, status = 200) {
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }))
}
beforeEach(() => {
vi.clearAllMocks()
key = { ...key, scopes: ['skatteverket'] }
hh.budget.mockResolvedValue({ ok: true })
hh.find.mockResolvedValue({ id: 'l1' })
})
describe('skv data proxy', () => {
it('rejects dot-segment traversal, raw and percent-encoded', async () => {
// Raw ../ and %2E dot segments are normalized away by the WHATWG URL
// parser before the route sees them (they cannot escape past the route
// prefix). What survives to splitPath is an encoded separator INSIDE a
// segment, which would traverse once the upstream fetch re-normalizes:
// those must be rejected here.
for (const path of ['/moms/a%2Fb', '/moms/..%2Fx', '/moms/a%5Cb']) {
const res = await GET(req('GET', path))
expect(res.status, path).toBe(403)
expect((await res.json()).code).toBe('CONNECTOR_PATH_NOT_ALLOWED')
}
})
it('403 without the scope', async () => {
key = { ...key, scopes: [] }
expect((await GET(req('GET', '/moms/deklarationer'))).status).toBe(403)
})
it('403 on an unknown service', async () => {
const res = await GET(req('GET', '/unknown/x'))
expect(res.status).toBe(403)
expect((await res.json()).code).toBe('CONNECTOR_PATH_NOT_ALLOWED')
})
it('400 without a user token', async () => {
const res = await GET(new Request('https://app.gnubok.se/api/connect/skv/api/moms/x', { method: 'GET' }))
expect(res.status).toBe(400)
expect((await res.json()).code).toBe('CONNECTOR_UPSTREAM_TOKEN_MISSING')
})
it('404 when the token is not owned by this key', async () => {
hh.find.mockResolvedValue(null)
expect((await GET(req('GET', '/moms/x'))).status).toBe(404)
})
it('forwards a GET with the user Bearer + Arcim gateway headers to the right backing API', async () => {
skvOk({ ok: true })
const res = await GET(req('GET', '/skattekonto/saldo?period=2026-08'))
expect(res.status).toBe(200)
const [url, init] = fetchMock.mock.calls[0]
expect(url).toBe('https://api.skv/skattekonto/v2/saldo?period=2026-08')
expect(init.headers.Authorization).toBe('Bearer user-token')
expect(init.headers.Client_Id).toBe('gw')
expect(hh.touch).toHaveBeenCalledWith(expect.anything(), 'l1')
})
it('forwards a POST body to the AGI inlämning API', async () => {
skvOk({ id: 'u1' }, 201)
const res = await POST(req('POST', '/agd-inlamning/underlag', 'user-token', '<xml/>'))
expect(res.status).toBe(201)
expect(fetchMock.mock.calls[0][0]).toBe('https://api.skv/agd/inlamning/v1/underlag')
expect(fetchMock.mock.calls[0][1].body).toBe('<xml/>')
})
it('forwards SKV diagnostic headers (WWW-Authenticate, x-skv-*) but nothing else', async () => {
// The instance's 401 classifier reads WWW-Authenticate (insufficient_scope
// → MISSING_SCOPE) and the x-skv-* family on body-less gateway
// rejections; stripping them blinded connector-mode classification.
fetchMock.mockResolvedValueOnce(new Response('', {
status: 401,
headers: {
'content-type': 'application/json',
'WWW-Authenticate': 'Bearer error="insufficient_scope", scope="agd"',
'x-skv-trace': 'abc',
'x-amzn-requestid': 'req-1',
'set-cookie': 'secret=1',
'x-internal-other': 'nope',
},
}))
const res = await GET(req('GET', '/moms/x'))
expect(res.status).toBe(401)
expect(res.headers.get('WWW-Authenticate')).toBe('Bearer error="insufficient_scope", scope="agd"')
expect(res.headers.get('x-skv-trace')).toBe('abc')
expect(res.headers.get('x-amzn-requestid')).toBe('req-1')
expect(res.headers.get('set-cookie')).toBeNull()
expect(res.headers.get('x-internal-other')).toBeNull()
})
it('429 when the budget is exhausted', async () => {
hh.budget.mockResolvedValue({ ok: false, scope: 'hour', retryAfterSec: 3600 })
const res = await GET(req('GET', '/moms/x'))
expect(res.status).toBe(429)
expect(res.headers.get('Retry-After')).toBe('3600')
expect(fetchMock).not.toHaveBeenCalled()
})
})
-132
View File
@@ -1,132 +0,0 @@
import { NextResponse } from 'next/server'
import { withConnectorAuth, type ConnectorContext } from '@/lib/connect/hosted/with-connector-auth'
import { reserveUpstream } from '@/lib/connect/hosted/upstream-budget'
import { findByHandle, touchConnection } from '@/lib/connect/hosted/ledger'
import { SKV_API_BASES, skvGatewayHeaders } from '@/lib/connect/upstreams/skatteverket-oauth'
/**
* Skatteverket data proxy for self-hosted instances.
*
* ANY /api/connect/skv/api/<service>/<path>
* Authorization: Bearer <the END USER's SKV access token, from the instance>
* X-Connector-Key: gnubok_ck_... (the instance's key auth)
*
* The instance holds the user token (it did the BankID flow through our
* broker); it presents that token as the upstream Bearer while proving its
* own subscription with X-Connector-Key. The proxy checks that the presented
* token belongs to a connection this key owns (ledger), then adds Arcim's
* API-gateway client credentials (Client_Id/Client_Secret) and forwards to
* the right SKV backing API. Arcim's gateway secret never leaves us.
*
* <service> is one of the SKV_API_BASES keys (moms, skattekonto,
* agd-inlamning, agd-period): an allowlist, never an open passthrough.
*/
const FETCH_TIMEOUT_MS = 20_000
function requireScope(ctx: ConnectorContext): NextResponse | null {
if (ctx.key.scopes.includes('skatteverket')) return null
return NextResponse.json({ error: 'This connector key does not include Skatteverket', code: 'CONNECTOR_SCOPE_MISSING' }, { status: 403 })
}
function splitPath(request: Request): { service: string; rest: string; query: string } | null {
const marker = '/api/connect/skv/api'
const idx = request.url.indexOf(marker)
if (idx === -1) return null
const after = request.url.slice(idx + marker.length)
const [pathPart, ...q] = after.split('?')
const segments = pathPart.split('/').filter(Boolean)
if (segments.length === 0) return null
// Traversal guard: a '.'/'..' segment (raw or percent-encoded) would let
// the proxied URL escape the allowlisted service base once fetch
// normalizes it. Decode each segment and reject dot segments and anything
// that decodes to contain a path separator.
for (const seg of segments) {
let decoded: string
try {
decoded = decodeURIComponent(seg)
} catch {
return null
}
if (decoded === '.' || decoded === '..' || decoded.includes('/') || decoded.includes('\\')) return null
}
const [service, ...restSegs] = segments
return { service, rest: `/${restSegs.join('/')}`, query: q.length ? `?${q.join('?')}` : '' }
}
/** The end-user SKV token the instance forwards, from the upstream-Authorization header. */
function userToken(request: Request): string | null {
const h = request.headers.get('x-connector-upstream-authorization') || request.headers.get('authorization')
if (!h?.startsWith('Bearer ')) return null
return h.slice(7).trim() || null
}
async function handle(request: Request, ctx: ConnectorContext): Promise<Response> {
const scopeError = requireScope(ctx)
if (scopeError) return scopeError
const parts = splitPath(request)
if (!parts || !(parts.service in SKV_API_BASES)) {
return NextResponse.json({ error: 'Unknown Skatteverket service', code: 'CONNECTOR_PATH_NOT_ALLOWED' }, { status: 403 })
}
const token = userToken(request)
if (!token) {
return NextResponse.json({ error: 'Missing user token', code: 'CONNECTOR_UPSTREAM_TOKEN_MISSING' }, { status: 400 })
}
const owned = await findByHandle(ctx.supabase, { keyId: ctx.key.id, service: 'skatteverket', handle: token })
if (!owned) {
return NextResponse.json({ error: 'Unknown Skatteverket connection for this key', code: 'CONNECTOR_NOT_OWNED' }, { status: 404 })
}
const budget = await reserveUpstream(ctx.supabase, 'skatteverket')
if (!budget.ok) {
return NextResponse.json({ error: 'Skatteverket connector is busy', code: 'CONNECTOR_RATE_LIMITED' }, { status: 429, headers: { 'Retry-After': String(budget.retryAfterSec) } })
}
await touchConnection(ctx.supabase, owned.id)
const url = `${SKV_API_BASES[parts.service]()}${parts.rest}${parts.query}`
const contentType = request.headers.get('x-connector-upstream-content-type') || request.headers.get('content-type') || 'application/json'
const method = request.method
const hasBody = method !== 'GET' && method !== 'HEAD'
const body = hasBody ? await request.text() : undefined
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)
try {
const res = await fetch(url, {
method,
signal: controller.signal,
// A followed redirect would resend the gateway Client_Secret headers.
redirect: 'error',
headers: {
Authorization: `Bearer ${token}`,
...skvGatewayHeaders(),
...(hasBody ? { 'Content-Type': contentType } : {}),
},
...(body !== undefined && body.length > 0 ? { body } : {}),
})
const text = await res.text()
if ([204, 205, 304].includes(res.status)) return new NextResponse(null, { status: res.status })
// Forward SKV's diagnostic headers: WWW-Authenticate carries OAuth's
// machine-readable failure reason (the instance's insufficient_scope →
// MISSING_SCOPE classification depends on it), and the x-skv-*/x-amzn-*/
// x-api-* families are the only signal on body-less gateway rejections.
// Nothing secret rides in them; stripping them blinded the instance's
// 401 classifier (skeptic finding on PR6b-2).
const headers: Record<string, string> = { 'Content-Type': res.headers.get('content-type') ?? 'application/json' }
res.headers.forEach((v, k) => {
const lk = k.toLowerCase()
if (lk === 'www-authenticate' || lk.startsWith('x-skv-') || lk.startsWith('x-amzn-') || lk.startsWith('x-api-')) {
headers[k] = v
}
})
return new NextResponse(text, { status: res.status, headers })
} finally {
clearTimeout(timeout)
}
}
export const GET = withConnectorAuth('connect.skv', handle)
export const POST = withConnectorAuth('connect.skv', handle)
export const PUT = withConnectorAuth('connect.skv', handle)
export const PATCH = withConnectorAuth('connect.skv', handle)
export const DELETE = withConnectorAuth('connect.skv', handle)
@@ -1,67 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
let key = {
id: 'key-1', orgNumber: '5561234567', instanceUrl: 'https://bokforing.example.se',
scopes: ['skatteverket'], status: 'active' as const, currentPeriodEnd: null as string | null,
limits: { bank_connections_per_company: 1, skv_connections_per_company: 1, sync_min_interval_s: 0 },
}
vi.mock('@/lib/connect/hosted/with-connector-auth', () => ({
withConnectorAuth: (_o: string, h: (r: Request, c: unknown) => Promise<Response>) => (r: Request) =>
h(r, { requestId: 't', log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, supabase: {}, key }),
}))
const hh = vi.hoisted(() => ({ budget: vi.fn(), count: vi.fn(), deletePending: vi.fn(), pending: vi.fn() }))
vi.mock('@/lib/connect/hosted/upstream-budget', () => ({ reserveUpstream: (...a: unknown[]) => hh.budget(...a) }))
vi.mock('@/lib/connect/hosted/ledger', () => ({ countHeldConnections: (...a: unknown[]) => hh.count(...a), deletePendingConnectionById: (...a: unknown[]) => hh.deletePending(...a), createPendingConnection: (...a: unknown[]) => hh.pending(...a) }))
vi.mock('@/lib/connect/hosted/state', () => ({ signConnectorState: () => 'ck1.signed' }))
vi.mock('@/lib/connect/upstreams/skatteverket-oauth', () => ({
buildSkvAuthorizeUrl: (redirectUri: string, state: string) => `https://skv/authorize?redirect_uri=${encodeURIComponent(redirectUri)}&state=${state}`,
skvDefaultScopes: () => 'moms agd',
}))
import { POST } from '../route'
const body = (o: Record<string, unknown> = {}) => ({
company_ref: 'company-1', return_url: 'https://bokforing.example.se/cb', state: 'inst', code_challenge: 'a'.repeat(43), ...o,
})
beforeEach(() => {
vi.clearAllMocks()
process.env.NEXT_PUBLIC_SKV_OAUTH_BASE_URL = 'https://app.gnubok.se'
key = { ...key, scopes: ['skatteverket'], limits: { bank_connections_per_company: 1, skv_connections_per_company: 1, sync_min_interval_s: 0 } }
hh.budget.mockResolvedValue({ ok: true })
hh.count.mockResolvedValue(0)
})
describe('POST /api/connect/skv/oauth/authorize-url', () => {
it('403 without the skatteverket scope', async () => {
key = { ...key, scopes: [] }
const res = await POST(createMockRequest('/api/connect/skv/oauth/authorize-url', { method: 'POST', body: body() }))
expect(res.status).toBe(403)
})
it('400 on a return_url off the instance', async () => {
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ return_url: 'https://evil.example.com/cb' }) }))
const { status, body: b } = await parseJsonResponse<{ code: string }>(res)
expect(status).toBe(400)
expect(b.code).toBe('CONNECTOR_REDIRECT_INVALID')
})
it('403 when the per-company SKV quota is reached', async () => {
hh.count.mockResolvedValue(1)
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }))
expect(res.status).toBe(403)
expect((await res.json()).code).toBe('CONNECTOR_QUOTA_EXCEEDED')
})
it('records a pending row and returns the authorize URL with our redirect + signed state', async () => {
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }))
const { status, body: b } = await parseJsonResponse<{ data: { authorize_url: string; redirect_uri: string; connector_state: string } }>(res)
expect(status).toBe(200)
expect(hh.pending).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ service: 'skatteverket', companyRef: 'company-1', pendingState: 'ck1.signed' }))
expect(b.data.redirect_uri).toBe('https://app.gnubok.se/api/extensions/ext/skatteverket/callback')
expect(b.data.connector_state).toBe('ck1.signed')
expect(b.data.authorize_url).toContain('state=ck1.signed')
})
it('429 when the budget is exhausted', async () => {
hh.budget.mockResolvedValue({ ok: false, scope: 'minute', retryAfterSec: 60 })
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }))
expect(res.status).toBe(429)
})
})
@@ -1,88 +0,0 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { validateBody } from '@/lib/api/validate'
import { withConnectorAuth, type ConnectorContext } from '@/lib/connect/hosted/with-connector-auth'
import { buildSkvAuthorizeUrl, skvDefaultScopes } from '@/lib/connect/upstreams/skatteverket-oauth'
import { reserveUpstream } from '@/lib/connect/hosted/upstream-budget'
import { countHeldConnections, createPendingConnection, deletePendingConnectionById } from '@/lib/connect/hosted/ledger'
import { signConnectorState } from '@/lib/connect/hosted/state'
/**
* POST /api/connect/skv/oauth/authorize-url
*
* The instance asks the connector broker to start a Skatteverket BankID
* consent for one company. The broker builds the authorize URL against
* Arcim's registered SKV client, using OUR registered redirect_uri, with a
* signed connector state that carries the instance's own return URL; the SKV
* extension callback (on the hosted host) detects that state and bounces the
* browser back to the instance with the code. The instance keeps its own PKCE
* verifier and later calls /oauth/token with the code.
*
* Tokens never touch us: the token exchange returns them to the instance,
* which stores them (encrypted) in its own database.
*/
const Schema = z.object({
company_ref: z.string().min(1).max(200),
return_url: z.string().url().max(512),
state: z.string().min(1).max(200),
code_challenge: z.string().min(16).max(256),
scope: z.string().max(400).optional(),
})
function requireScope(ctx: ConnectorContext): NextResponse | null {
if (ctx.key.scopes.includes('skatteverket')) return null
return NextResponse.json({ error: 'This connector key does not include Skatteverket', code: 'CONNECTOR_SCOPE_MISSING' }, { status: 403 })
}
function hostedRedirectUri(): string {
const base = (process.env.NEXT_PUBLIC_SKV_OAUTH_BASE_URL || process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000').replace(/\/+$/, '')
return `${base}/api/extensions/ext/skatteverket/callback`
}
function isOnInstance(url: string, instanceUrl: string | null): boolean {
if (!instanceUrl) return false
try {
return new URL(url).origin === new URL(instanceUrl).origin
} catch {
return false
}
}
export const POST = withConnectorAuth('connect.skv', async (request, ctx) => {
const scopeError = requireScope(ctx)
if (scopeError) return scopeError
const parsed = await validateBody(request, Schema, { log: ctx.log, operation: 'connect.skv.authorize-url' })
if (!parsed.success) return parsed.response
const { company_ref: cref, return_url, state, code_challenge, scope } = parsed.data
if (!isOnInstance(return_url, ctx.key.instanceUrl)) {
return NextResponse.json({ error: 'return_url must be on the connector key\'s instance', code: 'CONNECTOR_REDIRECT_INVALID' }, { status: 400 })
}
// Quota with a reservation re-count (same TOCTOU fix as the bank /auth):
// pre-count fast-rejects, the pending row reserves, the post-insert
// re-count rolls the own row back when concurrent authorizes overshoot.
const quotaExceeded = () =>
NextResponse.json(
{ error: 'Skatteverket connection quota reached for this company', code: 'CONNECTOR_QUOTA_EXCEEDED', limit: ctx.key.limits.skv_connections_per_company },
{ status: 403 },
)
const held = await countHeldConnections(ctx.supabase, ctx.key.id, 'skatteverket', cref)
if (held >= ctx.key.limits.skv_connections_per_company) return quotaExceeded()
const budget = await reserveUpstream(ctx.supabase, 'skatteverket')
if (!budget.ok) {
return NextResponse.json({ error: 'Skatteverket connector is busy', code: 'CONNECTOR_RATE_LIMITED' }, { status: 429, headers: { 'Retry-After': String(budget.retryAfterSec) } })
}
const signedState = signConnectorState({ kid: ctx.key.id, svc: 'skv', ret: return_url, st: state, cref })
const redirectUri = hostedRedirectUri()
const pendingId = await createPendingConnection(ctx.supabase, { keyId: ctx.key.id, service: 'skatteverket', companyRef: cref, provider: 'skatteverket', pendingState: signedState })
const heldAfter = await countHeldConnections(ctx.supabase, ctx.key.id, 'skatteverket', cref)
if (heldAfter > ctx.key.limits.skv_connections_per_company) {
await deletePendingConnectionById(ctx.supabase, pendingId)
return quotaExceeded()
}
const authorizeUrl = buildSkvAuthorizeUrl(redirectUri, signedState, { scope: scope || skvDefaultScopes(), codeChallenge: code_challenge })
return NextResponse.json({ data: { authorize_url: authorizeUrl, redirect_uri: redirectUri, connector_state: signedState } })
})
@@ -1,155 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
let key = {
id: 'key-1', orgNumber: 'x', instanceUrl: 'https://i', scopes: ['skatteverket'], status: 'active' as const,
currentPeriodEnd: null as string | null, limits: { bank_connections_per_company: 1, skv_connections_per_company: 1, sync_min_interval_s: 0 },
}
const chain = { update: vi.fn(() => chain), eq: vi.fn(() => chain), then: (r: (v: unknown) => void) => r({ error: null }) }
const supabase = { from: vi.fn(() => chain) }
vi.mock('@/lib/connect/hosted/with-connector-auth', () => ({
withConnectorAuth: (_o: string, h: (r: Request, c: unknown) => Promise<Response>) => (r: Request) =>
h(r, { requestId: 't', log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, supabase, key }),
}))
const hh = vi.hoisted(() => ({
budget: vi.fn(),
exchange: vi.fn(),
refresh: vi.fn(),
activate: vi.fn(),
findPending: vi.fn(),
findRefresh: vi.fn(),
}))
vi.mock('@/lib/connect/hosted/upstream-budget', () => ({ reserveUpstream: (...a: unknown[]) => hh.budget(...a) }))
vi.mock('@/lib/connect/upstreams/skatteverket-oauth', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/connect/upstreams/skatteverket-oauth')>()
return {
exchangeSkvCode: (...a: unknown[]) => hh.exchange(...a),
refreshSkvToken: (...a: unknown[]) => hh.refresh(...a),
// The dead-dialect classifier stays REAL: these tests pin that the route
// re-codes exactly the dialects the classifier recognizes.
isSkvDeadRefreshTokenError: actual.isSkvDeadRefreshTokenError,
}
})
vi.mock('@/lib/connect/hosted/ledger', () => ({
activateByPendingState: (...a: unknown[]) => hh.activate(...a),
findPendingByState: (...a: unknown[]) => hh.findPending(...a),
findByRefreshHash: (...a: unknown[]) => hh.findRefresh(...a),
hashHandle: (s: string) => `h(${s})`,
}))
vi.mock('@/lib/connect/hosted/state', () => ({
verifyConnectorState: (token: string) =>
token === 'ck1.signed'
? { ok: true, payload: { kid: 'key-1', svc: 'skv', ret: 'https://i/cb', st: 's', cref: 'c1', iat: 0 } }
: token === 'ck1.foreign'
? { ok: true, payload: { kid: 'key-OTHER', svc: 'skv', ret: 'x', st: 's', cref: 'c', iat: 0 } }
: { ok: false, reason: 'malformed' },
}))
import { POST } from '../route'
beforeEach(() => {
vi.clearAllMocks()
key = { ...key, scopes: ['skatteverket'] }
hh.budget.mockResolvedValue({ ok: true })
hh.findPending.mockResolvedValue({ id: 'p1', status: 'pending' })
hh.activate.mockResolvedValue({ id: 'p1', status: 'active' })
hh.findRefresh.mockResolvedValue({ id: 'r1', status: 'active' })
})
describe('POST /api/connect/skv/oauth/token', () => {
it('exchanges an authorization code, activates the ledger row, returns tokens', async () => {
hh.exchange.mockResolvedValue({ access_token: 'at', refresh_token: 'rt', expires_in: 3600, scope: 's' })
const res = await POST(createMockRequest('/x', { method: 'POST', body: { grant_type: 'authorization_code', code: 'c', redirect_uri: 'https://app.gnubok.se/cb', code_verifier: 'v'.repeat(20), connector_state: 'ck1.signed' } }))
const { status, body } = await parseJsonResponse<{ data: { access_token: string; refresh_token: string } }>(res)
expect(status).toBe(200)
expect(body.data).toEqual({ access_token: 'at', refresh_token: 'rt', expires_in: 3600, scope: 's' })
expect(hh.activate).toHaveBeenCalledWith(supabase, { keyId: 'key-1', pendingState: 'ck1.signed', handle: 'at' })
})
it('refuses an invalid or foreign connector state before spending the client secret', async () => {
let res = await POST(createMockRequest('/x', { method: 'POST', body: { grant_type: 'authorization_code', code: 'c', redirect_uri: 'https://app.gnubok.se/cb', connector_state: 'garbage' } }))
expect(res.status).toBe(400)
expect((await res.json()).code).toBe('CONNECTOR_STATE_INVALID')
res = await POST(createMockRequest('/x', { method: 'POST', body: { grant_type: 'authorization_code', code: 'c', redirect_uri: 'https://app.gnubok.se/cb', connector_state: 'ck1.foreign' } }))
expect(res.status).toBe(403)
hh.findPending.mockResolvedValue(null)
res = await POST(createMockRequest('/x', { method: 'POST', body: { grant_type: 'authorization_code', code: 'c', redirect_uri: 'https://app.gnubok.se/cb', connector_state: 'ck1.signed' } }))
expect(res.status).toBe(404)
expect(hh.exchange).not.toHaveBeenCalled()
})
it('withholds tokens with 409 when the state was consumed concurrently', async () => {
hh.exchange.mockResolvedValue({ access_token: 'at', refresh_token: 'rt', expires_in: 3600, scope: 's' })
hh.activate.mockResolvedValue(null)
const res = await POST(createMockRequest('/x', { method: 'POST', body: { grant_type: 'authorization_code', code: 'c', redirect_uri: 'https://app.gnubok.se/cb', connector_state: 'ck1.signed' } }))
expect(res.status).toBe(409)
expect((await res.json()).code).toBe('CONNECTOR_STATE_CONSUMED')
})
it('refreshes only a refresh token owned by this key (rotates the ledger hashes)', async () => {
hh.refresh.mockResolvedValue({ access_token: 'at2', refresh_token: 'rt2', expires_in: 3600, scope: 's' })
const res = await POST(createMockRequest('/x', { method: 'POST', body: { grant_type: 'refresh_token', refresh_token: 'rt' } }))
expect(res.status).toBe(200)
expect(hh.findRefresh).toHaveBeenCalledWith(supabase, { keyId: 'key-1', refreshHash: 'h(rt)' })
expect(supabase.from).toHaveBeenCalledWith('connector_connections')
})
it('404s a refresh token with no active ledger row for this key, never calling upstream', async () => {
hh.findRefresh.mockResolvedValue(null)
const res = await POST(createMockRequest('/x', { method: 'POST', body: { grant_type: 'refresh_token', refresh_token: 'stolen-rt' } }))
expect(res.status).toBe(404)
expect((await res.json()).code).toBe('CONNECTOR_NOT_OWNED')
expect(hh.refresh).not.toHaveBeenCalled()
})
it('400 on an invalid grant shape', async () => {
const res = await POST(createMockRequest('/x', { method: 'POST', body: { grant_type: 'client_credentials' } }))
expect(res.status).toBe(400)
})
it('502 when the upstream exchange fails', async () => {
hh.exchange.mockRejectedValue(new Error('boom'))
const res = await POST(createMockRequest('/x', { method: 'POST', body: { grant_type: 'authorization_code', code: 'c', redirect_uri: 'https://app.gnubok.se/cb', connector_state: 'ck1.signed' } }))
expect(res.status).toBe(502)
})
// SKV per-flow refresh tokens live 65 minutes, so a dead refresh token is
// the DOMINANT refresh outcome. The broker must re-code SKV's terminal
// dialects distinctly: the instance maps this to SESSION_EXPIRED and shows
// its reconnect flow. Collapsing it into the generic 502 stripped every
// connector instance of that flow (skeptic refutation on PR6b-2).
it('401 CONNECTOR_SKV_REFRESH_DEAD when SKV declares the refresh token dead', async () => {
hh.refresh.mockRejectedValue(new Error(
'Skatteverket token refresh failed (404): {"error":"id_not_found","error_description":"The refresh token is not found"}',
))
const res = await POST(createMockRequest('/x', { method: 'POST', body: { grant_type: 'refresh_token', refresh_token: 'rt' } }))
expect(res.status).toBe(401)
expect((await res.json()).code).toBe('CONNECTOR_SKV_REFRESH_DEAD')
})
it('401 CONNECTOR_SKV_REFRESH_DEAD on the 400 invalid_grant dialect too', async () => {
hh.refresh.mockRejectedValue(new Error(
'Skatteverket token refresh failed (400): {"error": "invalid_grant"}',
))
const res = await POST(createMockRequest('/x', { method: 'POST', body: { grant_type: 'refresh_token', refresh_token: 'rt' } }))
expect(res.status).toBe(401)
expect((await res.json()).code).toBe('CONNECTOR_SKV_REFRESH_DEAD')
})
it('keeps transient refresh failures as the generic 502 (never a reconnect signal)', async () => {
hh.refresh.mockRejectedValue(new Error('Skatteverket token refresh failed (503): upstream unavailable'))
const res = await POST(createMockRequest('/x', { method: 'POST', body: { grant_type: 'refresh_token', refresh_token: 'rt' } }))
expect(res.status).toBe(502)
expect((await res.json()).code).toBe('CONNECTOR_SKV_TOKEN_FAILED')
})
it('does NOT re-code a dead-dialect failure on the authorization_code grant', async () => {
// An expired one-shot code also answers 400 invalid_grant, but that is
// not "refresh token dead": the exchange keeps the generic 502.
hh.exchange.mockRejectedValue(new Error(
'Skatteverket token exchange failed (400): {"error": "invalid_grant"}',
))
const res = await POST(createMockRequest('/x', { method: 'POST', body: { grant_type: 'authorization_code', code: 'c', redirect_uri: 'https://app.gnubok.se/cb', connector_state: 'ck1.signed' } }))
expect(res.status).toBe(502)
expect((await res.json()).code).toBe('CONNECTOR_SKV_TOKEN_FAILED')
})
})
-161
View File
@@ -1,161 +0,0 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { validateBody } from '@/lib/api/validate'
import { withConnectorAuth, type ConnectorContext } from '@/lib/connect/hosted/with-connector-auth'
import { exchangeSkvCode, isSkvDeadRefreshTokenError, refreshSkvToken, type SkvTokenResponse } from '@/lib/connect/upstreams/skatteverket-oauth'
import { reserveUpstream } from '@/lib/connect/hosted/upstream-budget'
import { activateByPendingState, findByRefreshHash, findPendingByState, hashHandle } from '@/lib/connect/hosted/ledger'
import { verifyConnectorState } from '@/lib/connect/hosted/state'
/**
* POST /api/connect/skv/oauth/token
*
* The broker exchanges an authorization code (or refreshes) with Arcim's SKV
* client secret and returns the tokens to the instance, which stores them.
* The ledger records only the SHA-256 of the access token (and refresh token),
* so later data calls can prove the presenting bearer belongs to this key.
*
* grant_type = authorization_code : { code, redirect_uri, code_verifier?, connector_state }
* grant_type = refresh_token : { refresh_token }
*/
const AuthCodeSchema = z.object({
grant_type: z.literal('authorization_code'),
code: z.string().min(1).max(4096),
redirect_uri: z.string().url().max(512),
code_verifier: z.string().min(16).max(256).optional(),
connector_state: z.string().min(1).max(2048),
})
const RefreshSchema = z.object({
grant_type: z.literal('refresh_token'),
refresh_token: z.string().min(1).max(4096),
})
const Schema = z.discriminatedUnion('grant_type', [AuthCodeSchema, RefreshSchema])
function requireScope(ctx: ConnectorContext): NextResponse | null {
if (ctx.key.scopes.includes('skatteverket')) return null
return NextResponse.json({ error: 'This connector key does not include Skatteverket', code: 'CONNECTOR_SCOPE_MISSING' }, { status: 403 })
}
function tokenResponse(t: SkvTokenResponse): NextResponse {
return NextResponse.json({
data: { access_token: t.access_token, refresh_token: t.refresh_token, expires_in: t.expires_in, scope: t.scope },
})
}
export const POST = withConnectorAuth('connect.skv', async (request, ctx) => {
const scopeError = requireScope(ctx)
if (scopeError) return scopeError
const parsed = await validateBody(request, Schema, { log: ctx.log, operation: 'connect.skv.token' })
if (!parsed.success) return parsed.response
const budget = await reserveUpstream(ctx.supabase, 'skatteverket')
if (!budget.ok) {
return NextResponse.json({ error: 'Skatteverket connector is busy', code: 'CONNECTOR_RATE_LIMITED' }, { status: 429, headers: { 'Retry-After': String(budget.retryAfterSec) } })
}
try {
if (parsed.data.grant_type === 'authorization_code') {
const { code, redirect_uri, code_verifier, connector_state } = parsed.data
// Same binding as the bank /sessions exchange: verified state signature,
// this key, skv service, and an existing pending row are preconditions
// for the privileged exchange (Arcim's client secret). Without them a
// code could be exchanged under a foreign or consumed state and live
// tokens handed out with no ledger row proving ownership.
const verified = verifyConnectorState(connector_state)
if (!verified.ok) {
return NextResponse.json({ error: 'Invalid connector state', code: 'CONNECTOR_STATE_INVALID' }, { status: 400 })
}
if (verified.payload.kid !== ctx.key.id || verified.payload.svc !== 'skv') {
return NextResponse.json({ error: 'State does not belong to this key', code: 'CONNECTOR_STATE_INVALID' }, { status: 403 })
}
const pendingRow = await findPendingByState(ctx.supabase, { keyId: ctx.key.id, pendingState: connector_state })
if (!pendingRow) {
return NextResponse.json({ error: 'Unknown connection for this key', code: 'CONNECTOR_NOT_OWNED' }, { status: 404 })
}
const tokens = await exchangeSkvCode(code, redirect_uri, code_verifier)
const activated = await activateByPendingState(ctx.supabase, {
keyId: ctx.key.id,
pendingState: connector_state,
handle: tokens.access_token,
})
if (!activated) {
// Consumed concurrently (replay of the same state): never hand out
// tokens the ledger cannot vouch for. SKV has no revoke endpoint;
// the unreturned pair simply expires unused.
ctx.log.warn('skv token exchange raced a consumed state; tokens withheld')
return NextResponse.json(
{ error: 'Connector state already consumed', code: 'CONNECTOR_STATE_CONSUMED' },
{ status: 409 },
)
}
if (tokens.refresh_token) {
// The ledger write must take before the tokens leave: a silently
// failed update strands a connection the ledger cannot vouch for.
const { error: hashError } = await ctx.supabase
.from('connector_connections')
.update({ refresh_hash: hashHandle(tokens.refresh_token) })
.eq('connector_key_id', ctx.key.id)
.eq('handle_hash', hashHandle(tokens.access_token))
if (hashError) {
ctx.log.error('skv ledger refresh-hash write failed; tokens withheld', hashError)
return NextResponse.json({ error: 'Ledger update failed', code: 'CONNECTOR_LEDGER_FAILED' }, { status: 502 })
}
}
return tokenResponse(tokens)
}
// refresh: ownership FIRST. The presented refresh token must hash to an
// ACTIVE ledger row under the presenting key before the broker spends
// Arcim's client secret on it; without this the route was an open refresh
// oracle for any leaked refresh token. Then rotate the ledger's handle +
// refresh hashes to the new pair. Two literal payloads (no runtime-built
// object) so the no-phantom-columns scanner can resolve the columns.
const { refresh_token } = parsed.data
const oldRefreshHash = hashHandle(refresh_token)
const owned = await findByRefreshHash(ctx.supabase, { keyId: ctx.key.id, refreshHash: oldRefreshHash })
if (!owned) {
return NextResponse.json({ error: 'Unknown connection for this key', code: 'CONNECTOR_NOT_OWNED' }, { status: 404 })
}
const tokens = await refreshSkvToken(refresh_token)
const newHandleHash = tokens.access_token ? hashHandle(tokens.access_token) : null
const lastUsedAt = new Date().toISOString()
// The rotation write must take before the tokens leave: SKV has already
// consumed the old refresh token, so a silently failed update would leave
// a ledger that can vouch for neither the old nor the new pair.
const { error: rotateError } = tokens.refresh_token
? await ctx.supabase
.from('connector_connections')
.update({ handle_hash: newHandleHash, last_used_at: lastUsedAt, refresh_hash: hashHandle(tokens.refresh_token) })
.eq('id', owned.id)
.eq('status', 'active')
: await ctx.supabase
.from('connector_connections')
.update({ handle_hash: newHandleHash, last_used_at: lastUsedAt })
.eq('id', owned.id)
.eq('status', 'active')
if (rotateError) {
ctx.log.error('skv ledger rotation write failed; tokens withheld', rotateError)
return NextResponse.json({ error: 'Ledger update failed', code: 'CONNECTOR_LEDGER_FAILED' }, { status: 502 })
}
return tokenResponse(tokens)
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
// Ordinary session expiry must be distinguishable from a transient
// failure: SKV's per-flow refresh tokens live 65 minutes, so a dead
// refresh token is the DOMINANT outcome here, and collapsing it into the
// generic 502 stripped every connector instance of its reconnect flow
// (raw 500s, no banner, cron retry spam). The instance maps this code to
// SESSION_EXPIRED; everything else stays the opaque 502 so a transient
// SKV outage never masquerades as "reconnect needed".
if (parsed.data.grant_type === 'refresh_token' && isSkvDeadRefreshTokenError(message)) {
ctx.log.info('skv refresh token expired at upstream', { code: 'CONNECTOR_SKV_REFRESH_DEAD' })
return NextResponse.json(
{ error: 'Skatteverket refresh token is no longer valid; a new BankID consent is required', code: 'CONNECTOR_SKV_REFRESH_DEAD' },
{ status: 401 },
)
}
ctx.log.warn('skv token exchange failed', { err: message })
return NextResponse.json({ error: 'Skatteverket token exchange failed', code: 'CONNECTOR_SKV_TOKEN_FAILED' }, { status: 502 })
}
})