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
-25
View File
@@ -1,25 +0,0 @@
/**
* The wire contract between a self-hosted Accounted instance and the hosted
* connector service (connect.accounted.se/api/connect/*). The definitions live in
* the MIT package packages/connect-contract (published as
* @accounted/connect-contract) so that either side can be implemented outside
* this repository; this module re-exports them for in-repo callers.
*
* Background: a self-hosted instance runs everything itself except the
* services only Accounted can operate (bank sync via our PSD2/AISP
* credentials, the Skatteverket API client, TIC org lookup, the migration
* gateway). A connector key (`gnubok_ck_...`) is the subscription token for
* those; this is the Nabu Casa model: everything local is free AGPL, the key
* buys access to the hosted connectors, and enforcement is key auth at the
* hosted proxy, never a licence check inside the instance.
*/
export {
CONNECTOR_KEY_PREFIX,
CONNECTOR_KEY_HEADER,
CONNECTOR_ENTITLEMENTS_PATH,
DEFAULT_CONNECT_BASE_URL,
type ConnectorKeyStatus,
type ConnectorEntitlements,
type ConnectorSyncReport,
} from '@accounted/connect-contract'
-94
View File
@@ -1,94 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import { generateConnectorKey, hashConnectorKey, isConnectorKeyFormat, validateConnectorKey } from '../keys'
function supabaseWithRpc(result: { data?: unknown; error?: unknown }): { supabase: SupabaseClient; rpc: ReturnType<typeof vi.fn> } {
const rpc = vi.fn().mockResolvedValue({ data: result.data ?? null, error: result.error ?? null })
return { supabase: { rpc } as unknown as SupabaseClient, rpc }
}
const ROW = {
connector_key_id: '11111111-1111-4111-8111-111111111111',
org_number: '5561234567',
instance_url: 'https://bokforing.example.se',
scopes: ['bank_sync', 'skatteverket'],
status: 'active',
current_period_end: '2027-01-01T00:00:00.000Z',
rate_limited: false,
limits: { bank_connections_per_company: 2, skv_connections_per_company: 1, peppol_connections_per_company: 1, sync_min_interval_s: 3600 },
}
describe('connector key primitives', () => {
it('generates a gnubok_ck_ key with a display prefix and a SHA-256 hash', () => {
const { key, hash, prefix } = generateConnectorKey()
expect(key.startsWith('gnubok_ck_')).toBe(true)
expect(key.length).toBeGreaterThan(40)
expect(prefix).toBe(key.slice(0, 18))
expect(hash).toBe(hashConnectorKey(key))
expect(hash).toMatch(/^[0-9a-f]{64}$/)
expect(generateConnectorKey().key).not.toBe(key)
})
it('recognises the key format', () => {
expect(isConnectorKeyFormat(generateConnectorKey().key)).toBe(true)
expect(isConnectorKeyFormat('gnubok_sk_abcdefghijklmnopqrstuvwxyz')).toBe(false)
expect(isConnectorKeyFormat('gnubok_ck_short')).toBe(false)
})
})
describe('validateConnectorKey', () => {
it('rejects a malformed key without touching the database', async () => {
const { supabase, rpc } = supabaseWithRpc({ data: [ROW] })
expect(await validateConnectorKey('nope', supabase)).toMatchObject({ ok: false, status: 401, code: 'CONNECTOR_KEY_INVALID' })
expect(rpc).not.toHaveBeenCalled()
})
it('hashes the key and calls the atomic RPC', async () => {
const { key, hash } = generateConnectorKey()
const { supabase, rpc } = supabaseWithRpc({ data: [ROW] })
const result = await validateConnectorKey(key, supabase)
expect(rpc).toHaveBeenCalledWith('validate_and_increment_connector_key', { p_key_hash: hash })
expect(result).toEqual({
ok: true,
key: {
id: ROW.connector_key_id,
orgNumber: '5561234567',
instanceUrl: 'https://bokforing.example.se',
scopes: ['bank_sync', 'skatteverket'],
status: 'active',
currentPeriodEnd: '2027-01-01T00:00:00.000Z',
limits: { bank_connections_per_company: 2, skv_connections_per_company: 1, peppol_connections_per_company: 1, sync_min_interval_s: 3600 },
},
})
})
it('fills default limits when the RPC returns null limits', async () => {
const { key } = generateConnectorKey()
const result = await validateConnectorKey(key, supabaseWithRpc({ data: [{ ...ROW, limits: null }] }).supabase)
expect(result.ok && result.key.limits).toEqual({ bank_connections_per_company: 1, skv_connections_per_company: 1, peppol_connections_per_company: 1, sync_min_interval_s: 0 })
})
it('maps no row (unknown/revoked) to 401, but an RPC error to 503', async () => {
const { key } = generateConnectorKey()
expect(await validateConnectorKey(key, supabaseWithRpc({ data: [] }).supabase)).toMatchObject({ ok: false, status: 401 })
// NEVER 401 on a database error: the instance sync deletes its whole
// connector grant cache on 401/403, so a hosted pooler blip answered as
// 401 would destroy a paying instance's 72h offline grace. 503 lands in
// the sync's keep-grants branch.
expect(await validateConnectorKey(key, supabaseWithRpc({ error: { message: 'boom' } }).supabase)).toMatchObject({
ok: false,
status: 503,
code: 'CONNECTOR_VALIDATION_UNAVAILABLE',
})
})
it('maps a suspended key to 403 and a rate-limited one to 429', async () => {
const { key } = generateConnectorKey()
expect(
await validateConnectorKey(key, supabaseWithRpc({ data: [{ ...ROW, status: 'suspended' }] }).supabase),
).toMatchObject({ ok: false, status: 403, code: 'CONNECTOR_KEY_SUSPENDED' })
expect(
await validateConnectorKey(key, supabaseWithRpc({ data: [{ ...ROW, rate_limited: true }] }).supabase),
).toMatchObject({ ok: false, status: 429, code: 'CONNECTOR_RATE_LIMITED' })
})
})
@@ -1,53 +0,0 @@
import { describe, it, expect, afterEach, vi } from 'vitest'
import { isConnectorState, signConnectorState, verifyConnectorState } from '../state'
afterEach(() => vi.unstubAllEnvs())
const BASE = { kid: 'k1', svc: 'bank' as const, ret: 'https://bokforing.example.se/cb', st: 'inst-state', cref: 'company-1' }
describe('connector state', () => {
it('round-trips a signed payload', () => {
vi.stubEnv('CONNECTOR_STATE_SECRET', 'secret')
const now = 1_000_000
const token = signConnectorState(BASE, now)
expect(isConnectorState(token)).toBe(true)
const v = verifyConnectorState(token, now)
expect(v).toEqual({ ok: true, payload: { ...BASE, iat: now } })
})
it('rejects a tampered payload', () => {
vi.stubEnv('CONNECTOR_STATE_SECRET', 'secret')
const token = signConnectorState(BASE, 1000)
const [ver, body, sig] = token.split('.')
const tamperedBody = Buffer.from(JSON.stringify({ ...BASE, cref: 'other', iat: 1000 })).toString('base64url')
expect(verifyConnectorState(`${ver}.${tamperedBody}.${sig}`, 1000)).toEqual({ ok: false, reason: 'bad_signature' })
})
it('rejects a signature made with a different secret', () => {
vi.stubEnv('CONNECTOR_STATE_SECRET', 'secret-a')
const token = signConnectorState(BASE, 1000)
vi.stubEnv('CONNECTOR_STATE_SECRET', 'secret-b')
expect(verifyConnectorState(token, 1000)).toEqual({ ok: false, reason: 'bad_signature' })
})
it('expires after the TTL and rejects a future iat', () => {
vi.stubEnv('CONNECTOR_STATE_SECRET', 'secret')
const token = signConnectorState(BASE, 1000)
expect(verifyConnectorState(token, 1000 + 16 * 60 * 1000)).toEqual({ ok: false, reason: 'expired' })
const future = signConnectorState(BASE, 10_000_000)
expect(verifyConnectorState(future, 1000)).toEqual({ ok: false, reason: 'expired' })
})
it('flags malformed tokens', () => {
vi.stubEnv('CONNECTOR_STATE_SECRET', 'secret')
expect(verifyConnectorState('nope')).toEqual({ ok: false, reason: 'malformed' })
expect(isConnectorState('random-uuid-state')).toBe(false)
})
it('derives a secret from the service-role key when none is set (still verifiable)', () => {
vi.stubEnv('CONNECTOR_STATE_SECRET', '')
vi.stubEnv('SUPABASE_SERVICE_ROLE_KEY', 'svc-key')
const token = signConnectorState(BASE, 2000)
expect(verifyConnectorState(token, 2000).ok).toBe(true)
})
})
@@ -1,37 +0,0 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import { budgetFor, reserveUpstream } from '../upstream-budget'
afterEach(() => vi.unstubAllEnvs())
function supa(result: { data?: unknown; error?: unknown }) {
const rpc = vi.fn().mockResolvedValue({ data: result.data ?? null, error: result.error ?? null })
return { supabase: { rpc } as unknown as SupabaseClient, rpc }
}
describe('budgetFor', () => {
it('defaults sit under the EB per-minute quota and are env-overridable', () => {
expect(budgetFor('bank').minuteMax).toBe(90)
vi.stubEnv('CONNECT_BANK_RPM_BUDGET', '50')
expect(budgetFor('bank').minuteMax).toBe(50)
})
})
describe('reserveUpstream', () => {
it('passes the service and the resolved budget to the RPC and returns ok', async () => {
const { supabase, rpc } = supa({ data: { ok: true } })
expect(await reserveUpstream(supabase, 'bank')).toEqual({ ok: true })
expect(rpc).toHaveBeenCalledWith('connector_reserve_upstream', { p_service: 'bank', p_minute_max: 90, p_hour_max: 3000 })
})
it('maps a budget rejection to a Retry-After result', async () => {
const { supabase } = supa({ data: { ok: false, scope: 'hour', retry_after_sec: 3600 } })
expect(await reserveUpstream(supabase, 'bank')).toEqual({ ok: false, scope: 'hour', retryAfterSec: 3600 })
})
// Fail-open: a broken counter table must not block every connector call.
it('fails open on a DB error', async () => {
const { supabase } = supa({ error: { message: 'boom' } })
expect(await reserveUpstream(supabase, 'skatteverket')).toEqual({ ok: true })
})
})
@@ -1,125 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
const validateMock = vi.fn()
vi.mock('../keys', () => ({
validateConnectorKey: (...args: unknown[]) => validateMock(...args),
}))
const usageInsert = vi.fn()
const from = vi.fn(() => ({ insert: usageInsert }))
vi.mock('@/lib/auth/api-keys', () => ({
createServiceClientNoCookies: () => ({ from }),
}))
import { extractConnectorKey, withConnectorAuth, redactEndpoint } from '../with-connector-auth'
const VALID = {
ok: true,
key: {
id: '11111111-1111-4111-8111-111111111111',
orgNumber: '5561234567',
instanceUrl: null,
scopes: ['bank_sync'],
status: 'active',
currentPeriodEnd: null,
},
}
function req(headers: Record<string, string> = {}): Request {
return new Request('https://app.gnubok.se/api/connect/entitlements', { headers })
}
beforeEach(() => {
vi.clearAllMocks()
usageInsert.mockResolvedValue({ error: null })
})
describe('extractConnectorKey', () => {
it('takes a connector-prefixed Bearer, else X-Connector-Key, else the raw Bearer for the format-check 401', () => {
expect(extractConnectorKey(req({ authorization: 'Bearer gnubok_ck_a' }))).toBe('gnubok_ck_a')
expect(extractConnectorKey(req({ 'x-connector-key': 'gnubok_ck_b' }))).toBe('gnubok_ck_b')
// A connector-prefixed Bearer is unambiguous and wins.
expect(extractConnectorKey(req({ authorization: 'Bearer gnubok_ck_a', 'x-connector-key': 'gnubok_ck_b' }))).toBe('gnubok_ck_a')
// The proxied-call shape (SKV data proxy): Authorization is the user's
// upstream SKV token, X-Connector-Key authenticates the instance. The
// connector key MUST win or every such request 401s on a hashed upstream
// token.
expect(extractConnectorKey(req({ authorization: 'Bearer upstream-skv-token', 'x-connector-key': 'gnubok_ck_b' }))).toBe('gnubok_ck_b')
// Non-prefixed Bearer alone still reaches the format check (401).
expect(extractConnectorKey(req({ authorization: 'Bearer not-a-connector-key' }))).toBe('not-a-connector-key')
expect(extractConnectorKey(req())).toBeNull()
expect(extractConnectorKey(req({ authorization: 'Basic xyz' }))).toBeNull()
})
})
describe('redactEndpoint', () => {
it('replaces opaque handle segments with :id so raw EB session ids never rest in metering', () => {
expect(redactEndpoint('/api/connect/bank/sessions/8f14e45f-ceea-467f-a8d5-91be6ce7cbc4')).toBe(
'/api/connect/bank/sessions/:id',
)
expect(redactEndpoint('/api/connect/bank/accounts/9a1b2c3d-0000-4111-8222-333344445555/transactions')).toBe(
'/api/connect/bank/accounts/:id/transactions',
)
expect(redactEndpoint('/api/connect/bank/sessions/deadbeefdeadbeefdeadbeef')).toBe('/api/connect/bank/sessions/:id')
expect(redactEndpoint('/api/connect/bank/sessions/8f14e45f%2Dceea-467f-a8d5-91be6ce7cbc4')).toBe(
'/api/connect/bank/sessions/:id',
)
expect(redactEndpoint('/api/connect/entitlements')).toBe('/api/connect/entitlements')
expect(redactEndpoint('/api/connect/bank/aspsps')).toBe('/api/connect/bank/aspsps')
})
})
describe('withConnectorAuth', () => {
const handler = vi.fn(async (_req: Request, _ctx: { key: { id: string } }) => NextResponse.json({ data: 'ok' }))
const wrapped = withConnectorAuth('connect.entitlements', handler)
it('401 without a key, and never calls the handler', async () => {
const res = await wrapped(req())
expect(res.status).toBe(401)
expect(await res.json()).toMatchObject({ code: 'CONNECTOR_KEY_MISSING' })
expect(handler).not.toHaveBeenCalled()
expect(validateMock).not.toHaveBeenCalled()
})
it('passes the validation failure through (401/403/429) with its code', async () => {
for (const failure of [
{ ok: false, status: 401, code: 'CONNECTOR_KEY_INVALID', error: 'Invalid connector key' },
{ ok: false, status: 403, code: 'CONNECTOR_KEY_SUSPENDED', error: 'Connector key is suspended' },
{ ok: false, status: 429, code: 'CONNECTOR_RATE_LIMITED', error: 'Rate limit exceeded' },
]) {
validateMock.mockResolvedValueOnce(failure)
const res = await wrapped(req({ authorization: 'Bearer gnubok_ck_x' }))
expect(res.status).toBe(failure.status)
expect(await res.json()).toEqual({ error: failure.error, code: failure.code })
}
expect(handler).not.toHaveBeenCalled()
})
it('runs the handler with the validated key and records one usage event', async () => {
validateMock.mockResolvedValueOnce(VALID)
const res = await wrapped(req({ authorization: 'Bearer gnubok_ck_x' }))
expect(res.status).toBe(200)
expect(res.headers.get('X-Request-Id')).toMatch(/^conn_/)
expect(handler).toHaveBeenCalledTimes(1)
expect(handler.mock.calls[0][1].key.id).toBe(VALID.key.id)
expect(from).toHaveBeenCalledWith('connector_usage_events')
expect(usageInsert).toHaveBeenCalledWith({
connector_key_id: VALID.key.id,
service: 'entitlements',
endpoint: '/api/connect/entitlements',
status_code: 200,
})
})
it('turns a throwing handler into a 500 envelope and still meters it', async () => {
validateMock.mockResolvedValueOnce(VALID)
const boom = withConnectorAuth('connect.entitlements', async () => {
throw new Error('db down')
})
const res = await boom(req({ authorization: 'Bearer gnubok_ck_x' }))
expect(res.status).toBe(500)
expect(await res.json()).toEqual({ error: 'Internal error', code: 'INTERNAL_ERROR' })
expect(usageInsert).toHaveBeenCalledWith(expect.objectContaining({ status_code: 500 }))
})
})
-119
View File
@@ -1,119 +0,0 @@
import crypto from 'node:crypto'
import type { SupabaseClient } from '@supabase/supabase-js'
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
import { CONNECTOR_KEY_PREFIX, type ConnectorKeyStatus } from '../contract'
/**
* Hosted-side connector key primitives. Mirrors lib/auth/api-keys.ts for
* `gnubok_sk_` API keys: 32 CSPRNG bytes, SHA-256 at rest (the hash is the
* lookup; a slow KDF adds nothing on a 256-bit random secret and would sit on
* the hot path of every proxied request), atomic validate + rate-limit in a
* SECURITY DEFINER RPC that only service_role may execute.
*/
export function generateConnectorKey(): { key: string; hash: string; prefix: string } {
const random = crypto.randomBytes(32).toString('base64url')
const key = `${CONNECTOR_KEY_PREFIX}${random}`
return { key, hash: hashConnectorKey(key), prefix: key.slice(0, CONNECTOR_KEY_PREFIX.length + 8) }
}
export function hashConnectorKey(key: string): string {
return crypto.createHash('sha256').update(key).digest('hex')
}
export function isConnectorKeyFormat(key: string): boolean {
return key.startsWith(CONNECTOR_KEY_PREFIX) && key.length > CONNECTOR_KEY_PREFIX.length + 16
}
export interface ConnectorKeyLimits {
bank_connections_per_company: number
skv_connections_per_company: number
/** Active Peppol receiving registrations per company ("one address"). */
peppol_connections_per_company: number
sync_min_interval_s: number
}
export const DEFAULT_CONNECTOR_LIMITS: ConnectorKeyLimits = {
bank_connections_per_company: 1,
skv_connections_per_company: 1,
peppol_connections_per_company: 1,
sync_min_interval_s: 0,
}
export interface ValidatedConnectorKey {
id: string
orgNumber: string
instanceUrl: string | null
scopes: string[]
status: ConnectorKeyStatus
currentPeriodEnd: string | null
limits: ConnectorKeyLimits
}
export type ConnectorKeyValidation =
| { ok: true; key: ValidatedConnectorKey }
| { ok: false; status: 401 | 403 | 429; code: 'CONNECTOR_KEY_INVALID' | 'CONNECTOR_KEY_SUSPENDED' | 'CONNECTOR_RATE_LIMITED'; error: string }
| { ok: false; status: 503; code: 'CONNECTOR_VALIDATION_UNAVAILABLE'; error: string }
/**
* Validate a presented key: format check, RPC lookup (atomic rate-limit
* increment), status mapping. Never throws on a bad key.
*
* A database/RPC error maps to 503, NEVER 401: the instance-side sync treats
* 401/403 as key revocation and deletes its entire connector grant cache
* (lib/connect/instance/sync.ts), so answering a hosted pooler blip with 401
* would let a transient hosted incident destroy a paying instance's 72h
* offline grace. 503 lands in the sync's keep-grants branch. Only a genuine
* empty result (unknown or revoked key) is 401. This deliberately diverges
* from the api-keys precedent, where a spurious 401 costs one request.
*/
export async function validateConnectorKey(
key: string,
supabase: SupabaseClient = createServiceClientNoCookies(),
): Promise<ConnectorKeyValidation> {
if (!isConnectorKeyFormat(key)) {
return { ok: false, status: 401, code: 'CONNECTOR_KEY_INVALID', error: 'Invalid connector key' }
}
const { data, error } = await supabase.rpc('validate_and_increment_connector_key', {
p_key_hash: hashConnectorKey(key),
})
if (error) {
return {
ok: false,
status: 503,
code: 'CONNECTOR_VALIDATION_UNAVAILABLE',
error: 'Connector key validation temporarily unavailable',
}
}
if (!data || (Array.isArray(data) && data.length === 0)) {
return { ok: false, status: 401, code: 'CONNECTOR_KEY_INVALID', error: 'Invalid connector key' }
}
const row = (Array.isArray(data) ? data[0] : data) as {
connector_key_id: string
org_number: string
instance_url: string | null
scopes: string[] | null
status: string
current_period_end: string | null
rate_limited: boolean
limits: Partial<ConnectorKeyLimits> | null
}
if (row.status !== 'active') {
return { ok: false, status: 403, code: 'CONNECTOR_KEY_SUSPENDED', error: 'Connector key is suspended' }
}
if (row.rate_limited) {
return { ok: false, status: 429, code: 'CONNECTOR_RATE_LIMITED', error: 'Rate limit exceeded' }
}
return {
ok: true,
key: {
id: row.connector_key_id,
orgNumber: row.org_number,
instanceUrl: row.instance_url,
scopes: row.scopes ?? [],
status: 'active',
currentPeriodEnd: row.current_period_end,
limits: { ...DEFAULT_CONNECTOR_LIMITS, ...(row.limits ?? {}) },
},
}
}
-203
View File
@@ -1,203 +0,0 @@
import crypto from 'node:crypto'
import type { SupabaseClient } from '@supabase/supabase-js'
/**
* The connector connection ledger: proof, without secrets, that a connection
* belongs to a given connector key. Every bank/SKV connection is born through
* the proxy (the consent redirect is ours), so the proxy records it at
* creation and checks ownership on every later use. The upstream handle (EB
* session id, SKV access token) is hashed; the value never rests here.
*/
export type ConnectorService = 'bank' | 'skatteverket' | 'peppol'
export function hashHandle(handle: string): string {
return crypto.createHash('sha256').update(handle).digest('hex')
}
export interface LedgerRow {
id: string
connector_key_id: string
service: ConnectorService
company_ref: string
provider: string | null
account_uids: string[]
status: 'pending' | 'active' | 'revoked'
}
/**
* Pending rows count toward quota only while their consent window is open:
* the signed connector state expires after 15 minutes, so an abandoned
* consent stops reserving capacity once its state can no longer activate it.
*/
export const PENDING_QUOTA_WINDOW_MS = 15 * 60 * 1000
/**
* Rows currently holding or reserving quota for (key, service, company):
* active connections plus fresh pending reservations. Used by the /auth
* quota check both before insert (fast reject) and after insert (the
* reservation re-count that closes the concurrent-auth race).
*/
export async function countHeldConnections(
supabase: SupabaseClient,
keyId: string,
service: ConnectorService,
companyRef: string,
now: Date = new Date(),
): Promise<number> {
const freshPendingSince = new Date(now.getTime() - PENDING_QUOTA_WINDOW_MS).toISOString()
const { count, error } = await supabase
.from('connector_connections')
.select('id', { count: 'exact', head: true })
.eq('connector_key_id', keyId)
.eq('service', service)
.eq('company_ref', companyRef)
.or(`status.eq.active,and(status.eq.pending,created_at.gte.${freshPendingSince})`)
if (error) throw new Error(`ledger count failed: ${error.message}`)
return count ?? 0
}
/** Roll back a just-created pending reservation (lost the quota re-count). */
export async function deletePendingConnectionById(supabase: SupabaseClient, id: string): Promise<void> {
await supabase.from('connector_connections').delete().eq('id', id).eq('status', 'pending')
}
export async function createPendingConnection(
supabase: SupabaseClient,
params: { keyId: string; service: ConnectorService; companyRef: string; provider: string | null; pendingState: string },
): Promise<string> {
const { data, error } = await supabase
.from('connector_connections')
.insert({
connector_key_id: params.keyId,
service: params.service,
company_ref: params.companyRef,
provider: params.provider,
pending_state: params.pendingState,
status: 'pending',
})
.select('id')
.single()
if (error || !data) throw new Error(`ledger insert failed: ${error?.message}`)
return (data as { id: string }).id
}
/**
* The pending row a signed state belongs to, under the presenting key.
* Precondition for the code exchange at POST /sessions: exchanging a code
* against a state with no pending row would mint an upstream session the
* ledger never records (and cross-flow substitution could smuggle a code
* into a foreign state). The state's own TTL bounds freshness.
*/
export async function findPendingByState(
supabase: SupabaseClient,
params: { keyId: string; pendingState: string },
): Promise<LedgerRow | null> {
const { data, error } = await supabase
.from('connector_connections')
.select('id, connector_key_id, service, company_ref, provider, account_uids, status')
.eq('connector_key_id', params.keyId)
.eq('pending_state', params.pendingState)
.eq('status', 'pending')
.maybeSingle()
if (error) throw new Error(`ledger pending lookup failed: ${error.message}`)
return (data as LedgerRow | null) ?? null
}
/**
* The ACTIVE row whose refresh-token hash matches, under the presenting key.
* Ownership precondition for the SKV refresh exchange: without it the broker
* was an open refresh oracle for any leaked refresh token.
*/
export async function findByRefreshHash(
supabase: SupabaseClient,
params: { keyId: string; refreshHash: string },
): Promise<LedgerRow | null> {
const { data, error } = await supabase
.from('connector_connections')
.select('id, connector_key_id, service, company_ref, provider, account_uids, status')
.eq('connector_key_id', params.keyId)
.eq('service', 'skatteverket')
.eq('refresh_hash', params.refreshHash)
.eq('status', 'active')
.maybeSingle()
if (error) throw new Error(`ledger refresh lookup failed: ${error.message}`)
return (data as LedgerRow | null) ?? null
}
/** Activate a pending connection (found by its signed pending_state) with the live handle + accounts. */
export async function activateByPendingState(
supabase: SupabaseClient,
params: { keyId: string; pendingState: string; handle: string; accountUids?: string[] },
): Promise<LedgerRow | null> {
const { data, error } = await supabase
.from('connector_connections')
.update({
status: 'active',
handle_hash: hashHandle(params.handle),
account_uids: params.accountUids ?? [],
pending_state: null,
activated_at: new Date().toISOString(),
last_used_at: new Date().toISOString(),
})
.eq('connector_key_id', params.keyId)
.eq('pending_state', params.pendingState)
.eq('status', 'pending')
.select('id, connector_key_id, service, company_ref, provider, account_uids, status')
.maybeSingle()
if (error) throw new Error(`ledger activate failed: ${error.message}`)
return (data as LedgerRow | null) ?? null
}
/** The active ledger row that owns a given handle under a key. Ownership check for reads/writes. */
export async function findByHandle(
supabase: SupabaseClient,
params: { keyId: string; service: ConnectorService; handle: string },
): Promise<LedgerRow | null> {
const { data, error } = await supabase
.from('connector_connections')
.select('id, connector_key_id, service, company_ref, provider, account_uids, status')
.eq('connector_key_id', params.keyId)
.eq('service', params.service)
.eq('handle_hash', hashHandle(params.handle))
.eq('status', 'active')
.maybeSingle()
if (error) throw new Error(`ledger lookup failed: ${error.message}`)
return (data as LedgerRow | null) ?? null
}
/** The active ledger row that owns a bank account uid under a key. */
export async function findByAccountUid(
supabase: SupabaseClient,
params: { keyId: string; accountUid: string },
): Promise<LedgerRow | null> {
const { data, error } = await supabase
.from('connector_connections')
.select('id, connector_key_id, service, company_ref, provider, account_uids, status')
.eq('connector_key_id', params.keyId)
.eq('service', 'bank')
.eq('status', 'active')
.contains('account_uids', [params.accountUid])
.limit(1)
.maybeSingle()
if (error) throw new Error(`ledger account lookup failed: ${error.message}`)
return (data as LedgerRow | null) ?? null
}
export async function touchConnection(supabase: SupabaseClient, id: string): Promise<void> {
await supabase.from('connector_connections').update({ last_used_at: new Date().toISOString() }).eq('id', id)
}
/** Revoke by handle (DELETE /sessions). Idempotent. */
export async function revokeByHandle(
supabase: SupabaseClient,
params: { keyId: string; service: ConnectorService; handle: string },
): Promise<void> {
await supabase
.from('connector_connections')
.update({ status: 'revoked', revoked_at: new Date().toISOString() })
.eq('connector_key_id', params.keyId)
.eq('service', params.service)
.eq('handle_hash', hashHandle(params.handle))
.eq('status', 'active')
}
-204
View File
@@ -1,204 +0,0 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import { isPeppolTransportError, type PeppolParticipant } from '@/lib/invoices/peppol-transport'
import { hashHandle } from './ledger'
/**
* Peppol-specific reads over the connector ledger (hosted side).
*
* A Peppol "connection" is a receiving registration: one participant id
* (scheme:identifier) published under Arcim's access point on behalf of one
* company on one instance. The ledger row stores the participant id in
* `account_uids` (it is public directory data, not a secret) so inbound
* documents can be routed to the key that owns the recipient, and its sha256
* in `handle_hash` so the partial unique index makes a participant claimable
* by exactly one key at a time.
*
* Outbound submissions are tracked in `connector_peppol_submissions`: the
* hosted Qvalia account is shared, so status polls and evidence reads must
* prove the caller submitted the document.
*/
export function peppolHandle(participant: PeppolParticipant): string {
return `${participant.scheme}:${participant.identifier.replace(/\s/g, '')}`
}
export function parsePeppolHandle(handle: string): PeppolParticipant | null {
const colon = handle.indexOf(':')
if (colon === -1) return null
const scheme = handle.slice(0, colon)
const identifier = handle.slice(colon + 1)
// ISO 6523 ICD scheme: four digits (not a BAS account, hence no shared schema).
if (scheme.length !== 4 || !/^\d+$/.test(scheme) || !identifier) return null
return { scheme, identifier }
}
/**
* Every participant this key currently holds an active registration for,
* optionally narrowed to one company on the instance. Inbound routing is
* key-wide (the instance's inbound sync lists for all its companies and
* routes by its own registrations); everything else is company-bound.
*/
export async function listActivePeppolParticipants(
supabase: SupabaseClient,
keyId: string,
companyRef?: string,
): Promise<PeppolParticipant[]> {
let query = supabase
.from('connector_connections')
.select('account_uids')
.eq('connector_key_id', keyId)
.eq('service', 'peppol')
.eq('status', 'active')
if (companyRef) query = query.eq('company_ref', companyRef)
const { data, error } = await query
if (error) throw new Error(`ledger read failed: ${error.message}`)
const participants: PeppolParticipant[] = []
for (const row of (data ?? []) as Array<{ account_uids: string[] | null }>) {
for (const uid of row.account_uids ?? []) {
const parsed = parsePeppolHandle(uid)
if (parsed) participants.push(parsed)
}
}
return participants
}
/** Whether ANY key holds an active registration for this participant. */
export async function isPeppolParticipantHeld(supabase: SupabaseClient, handle: string): Promise<boolean> {
const { data, error } = await supabase
.from('connector_connections')
.select('id')
.eq('service', 'peppol')
.eq('status', 'active')
.eq('handle_hash', hashHandle(handle))
.limit(1)
.maybeSingle()
if (error) throw new Error(`ledger read failed: ${error.message}`)
return !!data
}
/** Whether a HOSTED company holds a live registration for this participant at the provider. */
export async function isHostedPeppolParticipantLive(
supabase: SupabaseClient,
params: { provider: string; participant: PeppolParticipant },
): Promise<boolean> {
const { data, error } = await supabase
.from('peppol_registrations')
.select('id')
.eq('provider', params.provider)
.eq('participant_scheme', params.participant.scheme)
.eq('participant_identifier', params.participant.identifier.replace(/\s/g, ''))
.in('status', ['pending', 'registered'])
.limit(1)
.maybeSingle()
if (error) throw new Error(`peppol registration read failed: ${error.message}`)
return !!data
}
/** Same reservation window as countHeldConnections in ./ledger.ts. */
const PENDING_CAP_WINDOW_MS = 15 * 60 * 1000
/**
* Connector-held registrations across every key, for the provider-account
* cap: active rows plus fresh pending reservations, so two concurrent
* registrations cannot both pass the cap check and both land.
*/
export async function countConnectorPeppolRegistrations(supabase: SupabaseClient, now: Date = new Date()): Promise<number> {
const freshPendingSince = new Date(now.getTime() - PENDING_CAP_WINDOW_MS).toISOString()
const [active, pending] = await Promise.all([
supabase
.from('connector_connections')
.select('id', { count: 'exact', head: true })
.eq('service', 'peppol')
.eq('status', 'active'),
supabase
.from('connector_connections')
.select('id', { count: 'exact', head: true })
.eq('service', 'peppol')
.eq('status', 'pending')
.gte('created_at', freshPendingSince),
])
if (active.error) throw new Error(`ledger count failed: ${active.error.message}`)
if (pending.error) throw new Error(`ledger count failed: ${pending.error.message}`)
return (active.count ?? 0) + (pending.count ?? 0)
}
/**
* Participant identifiers a key may publish under Arcim's access point: the
* allowlist Arcim recorded at issuance plus the licensee's own org number.
* Whitespace is stripped the same way peppolHandle() does.
*/
export async function getPeppolAllowedIdentifiers(supabase: SupabaseClient, keyId: string): Promise<Set<string>> {
const { data, error } = await supabase
.from('connector_keys')
.select('org_number, peppol_participants')
.eq('id', keyId)
.maybeSingle()
if (error) throw new Error(`connector key read failed: ${error.message}`)
const row = data as { org_number: string | null; peppol_participants: string[] | null } | null
const allowed = new Set<string>()
for (const value of [row?.org_number ?? '', ...(row?.peppol_participants ?? [])]) {
const cleaned = value.replace(/\s/g, '')
if (cleaned) allowed.add(cleaned)
}
return allowed
}
export async function recordPeppolSubmission(
supabase: SupabaseClient,
params: { keyId: string; companyRef: string; provider: string; providerSubmissionId: string; idempotencyKey: string },
): Promise<void> {
const { error } = await supabase
.from('connector_peppol_submissions')
.upsert(
{
connector_key_id: params.keyId,
company_ref: params.companyRef,
provider: params.provider,
provider_submission_id: params.providerSubmissionId,
idempotency_key: params.idempotencyKey,
},
{ onConflict: 'provider,provider_submission_id', ignoreDuplicates: true },
)
if (error) throw new Error(`submission record failed: ${error.message}`)
}
/** The submission row for (key, company, provider submission id): both the key and the company must match. */
export async function findOwnedPeppolSubmission(
supabase: SupabaseClient,
params: { keyId: string; companyRef: string; provider: string; providerSubmissionId: string },
): Promise<{ id: string; company_ref: string } | null> {
const { data, error } = await supabase
.from('connector_peppol_submissions')
.select('id, company_ref')
.eq('connector_key_id', params.keyId)
.eq('company_ref', params.companyRef)
.eq('provider', params.provider)
.eq('provider_submission_id', params.providerSubmissionId)
.maybeSingle()
if (error) throw new Error(`submission read failed: ${error.message}`)
return (data as { id: string; company_ref: string } | null) ?? null
}
export interface PeppolUpstreamFailure {
/** Short, adapter-classified text (never a raw provider body). */
text: string
retryable: boolean
/** Adapter detail, capped; the instance surfaces it as PeppolTransportError.detail. */
hint: string | null
}
/**
* Summarize a transport failure for the connector response. The Qvalia
* adapter already classifies failures (network, auth, protocol, rejected,
* duplicate) into its own message text; only that classified text and its
* capped detail cross to the instance. Anything that is not a transport
* error is a hosted bug and is not summarized here (the caller rethrows).
*/
export function describePeppolUpstreamFailure(err: unknown): PeppolUpstreamFailure | null {
if (!isPeppolTransportError(err)) return null
return {
text: err.message.slice(0, 200),
retryable: err.retryable,
hint: err.detail ? err.detail.slice(0, 300) : null,
}
}
-88
View File
@@ -1,88 +0,0 @@
import crypto from 'node:crypto'
/**
* HMAC-signed connector state for the bank/SKV consent round-trip.
*
* The instance never registers a redirect URI with Enable Banking or
* Skatteverket: the consent redirect goes to OUR hosted callback (already
* registered), which then bounces the browser back to the instance. To do
* that safely the proxy replaces the upstream `state` with a token that
* carries where to return, the original instance state, and which key owns
* the flow, all signed so a tampered token is rejected. No storage: the token
* is self-contained and short-lived.
*
* Format: `ck1.<base64url(json)>.<base64url(hmac-sha256)>`.
*/
const VERSION = 'ck1'
const DEFAULT_TTL_MS = 15 * 60 * 1000
export interface ConnectorStatePayload {
/** connector_key id that owns this flow. */
kid: string
/** service: 'bank' | 'skv'. */
svc: 'bank' | 'skv'
/** Absolute return URL on the instance (the instance's own callback). */
ret: string
/** The instance's original state value, echoed back untouched. */
st: string
/** Instance company ref, for the ledger. */
cref: string
/** issued-at, ms. */
iat: number
}
function getSecret(): string {
const explicit = process.env.CONNECTOR_STATE_SECRET?.trim()
if (explicit) return explicit
// Fall back to a value derived from the service-role key so a deployment
// that forgot to set the dedicated secret still signs consistently. Never
// the raw key: a one-way derivation so the signing secret can't be reversed
// into the Supabase credential.
const svc = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!svc) throw new Error('CONNECTOR_STATE_SECRET (or SUPABASE_SERVICE_ROLE_KEY) is required to sign connector state')
return crypto.createHash('sha256').update(`connector-state:${svc}`).digest('hex')
}
function b64urlEncode(buf: Buffer): string {
return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}
function b64urlDecode(s: string): Buffer {
return Buffer.from(s.replace(/-/g, '+').replace(/_/g, '/'), 'base64')
}
export function signConnectorState(payload: Omit<ConnectorStatePayload, 'iat'>, now = Date.now()): string {
const body = b64urlEncode(Buffer.from(JSON.stringify({ ...payload, iat: now })))
const sig = crypto.createHmac('sha256', getSecret()).update(`${VERSION}.${body}`).digest()
return `${VERSION}.${body}.${b64urlEncode(sig)}`
}
export type VerifyStateResult =
| { ok: true; payload: ConnectorStatePayload }
| { ok: false; reason: 'malformed' | 'bad_signature' | 'expired' }
export function verifyConnectorState(token: string, now = Date.now(), ttlMs = DEFAULT_TTL_MS): VerifyStateResult {
const parts = token.split('.')
if (parts.length !== 3 || parts[0] !== VERSION) return { ok: false, reason: 'malformed' }
const [, body, sig] = parts
const expected = crypto.createHmac('sha256', getSecret()).update(`${VERSION}.${body}`).digest()
const given = b64urlDecode(sig)
if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) {
return { ok: false, reason: 'bad_signature' }
}
let payload: ConnectorStatePayload
try {
payload = JSON.parse(b64urlDecode(body).toString('utf8')) as ConnectorStatePayload
} catch {
return { ok: false, reason: 'malformed' }
}
if (typeof payload.iat !== 'number' || now - payload.iat > ttlMs || payload.iat > now + 60_000) {
return { ok: false, reason: 'expired' }
}
return { ok: true, payload }
}
/** True when a raw upstream `state` value is one of our signed connector states. */
export function isConnectorState(state: string | null | undefined): boolean {
return typeof state === 'string' && state.startsWith(`${VERSION}.`)
}
-77
View File
@@ -1,77 +0,0 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import type { ConnectorService } from './ledger'
/**
* Global upstream rate budget for the connector proxy.
*
* Enable Banking's quotas (Annex 1 §5: 20 rps / 300 rpm / 10 000 per hour) are
* shared by ALL of Arcim's traffic, hosted included. So connector traffic gets
* a ceiling well under those, reserved atomically in the DB (RPC
* connector_reserve_upstream) so two proxy requests can't both slip past. A
* self-hoster that hits the ceiling gets a 429 with Retry-After; hosted bank
* sync is never starved because the connector ceiling is a fraction of the
* provider quota.
*
* Configurable per service via env; the defaults sit around 30% of the EB
* per-minute quota.
*/
export type UpstreamService = ConnectorService
interface Budget {
minuteMax: number
hourMax: number
}
function intFromEnv(name: string, fallback: number): number {
const v = Number(process.env[name])
return Number.isFinite(v) && v > 0 ? Math.floor(v) : fallback
}
export function budgetFor(service: UpstreamService): Budget {
if (service === 'bank') {
return {
minuteMax: intFromEnv('CONNECT_BANK_RPM_BUDGET', 90), // ~30% of EB's 300/min
hourMax: intFromEnv('CONNECT_BANK_RPH_BUDGET', 3000), // ~30% of EB's 10 000/h
}
}
if (service === 'peppol') {
// Peppol is low-volume (invoices, not polling), so a modest ceiling well
// under Qvalia's limits is plenty; tune via env if a busy byrå needs more.
return {
minuteMax: intFromEnv('CONNECT_PEPPOL_RPM_BUDGET', 60),
hourMax: intFromEnv('CONNECT_PEPPOL_RPH_BUDGET', 1000),
}
}
return {
minuteMax: intFromEnv('CONNECT_SKV_RPM_BUDGET', 120),
hourMax: intFromEnv('CONNECT_SKV_RPH_BUDGET', 4000),
}
}
export type BudgetResult = { ok: true } | { ok: false; scope: 'minute' | 'hour'; retryAfterSec: number }
/**
* Reserve one upstream call. Returns ok:false with a Retry-After when the
* global budget for this service is exhausted. A DB error fails OPEN (ok:true):
* the budget is a protective cap, not an auth boundary, and blocking every
* connector call because the counter table hiccuped would be worse than a
* brief overshoot the provider itself also rate-limits.
*/
export async function reserveUpstream(
supabase: SupabaseClient,
service: UpstreamService,
): Promise<BudgetResult> {
const { minuteMax, hourMax } = budgetFor(service)
const { data, error } = await supabase.rpc('connector_reserve_upstream', {
p_service: service,
p_minute_max: minuteMax,
p_hour_max: hourMax,
})
if (error) return { ok: true }
const row = (data ?? {}) as { ok?: boolean; scope?: 'minute' | 'hour'; retry_after_sec?: number }
if (row.ok === false) {
return { ok: false, scope: row.scope ?? 'minute', retryAfterSec: row.retry_after_sec ?? 60 }
}
return { ok: true }
}
-140
View File
@@ -1,140 +0,0 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import { NextResponse, after } from 'next/server'
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
import { createLogger, type Logger } from '@/lib/logger'
import { CONNECTOR_KEY_HEADER, CONNECTOR_KEY_PREFIX } from '../contract'
import { validateConnectorKey, type ValidatedConnectorKey } from './keys'
/**
* Wrapper for the hosted connector endpoints (app/api/connect/*), the
* connector twin of lib/api/v1/with-api-v1.ts.
*
* 1. Extracts the key from `Authorization: Bearer gnubok_ck_...` or, for
* proxied calls where Authorization carries an upstream token, from
* `X-Connector-Key`.
* 2. Validates it through the atomic RPC (rate-limited): 401 unknown /
* revoked, 403 suspended, 429 over the per-minute limit.
* 3. Runs the handler with a service-role client and the validated key.
* 4. Records one connector_usage_events row (metering, never blocking).
*
* These routes are reached by self-hosted instances with a key, never by a
* browser session, so there is no cookie/MFA handling here; the proxy
* middleware already lets /api/* through for bearer callers.
*/
export interface ConnectorContext {
requestId: string
log: Logger
supabase: SupabaseClient
key: ValidatedConnectorKey
}
type ConnectorHandler = (request: Request, ctx: ConnectorContext) => Promise<NextResponse | Response>
export function extractConnectorKey(request: Request): string | null {
// A Bearer value is the connector credential only when it looks like one
// (gnubok_ck_ prefix); otherwise it is an UPSTREAM token on a proxied call
// and the connector key rides in X-Connector-Key. Hashing the upstream
// token instead would 401 every such request. A non-prefixed Bearer with
// no X-Connector-Key still falls through to the format check's 401.
const auth = request.headers.get('authorization')
const bearer = auth?.startsWith('Bearer ') ? auth.slice(7).trim() || null : null
if (bearer?.startsWith(CONNECTOR_KEY_PREFIX)) return bearer
const header = request.headers.get(CONNECTOR_KEY_HEADER)
if (header?.trim()) return header.trim()
return bearer
}
/**
* Opaque path segments (UUIDs, long hex, long base64url tokens) become ':id'
* before a path is persisted for metering. Literal route words (sessions,
* accounts, balances, aspsps, ...) survive, so the metric keys stay useful.
*/
// The 10+-digit rule covers Swedish identity numbers riding in SKV data-proxy
// paths (personnummer 10/12 digits, orgnr 10, redovisare12 16+orgnr): they are
// personal data of the instance's downstream clients and must never rest in
// metering. Period segments (YYYYMM, 6 digits) survive for metric granularity.
const OPAQUE_SEGMENT = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{16,}|[A-Za-z0-9_-]{20,}|\d{10,})$/i
export function redactEndpoint(pathname: string): string {
return pathname
.split('/')
// A percent-encoded segment is opaque too: URL.pathname does not decode,
// so an encoded handle would otherwise slip the pattern while the route
// decodes and uses it.
.map((segment) => (OPAQUE_SEGMENT.test(segment) || segment.includes('%') ? ':id' : segment))
.join('/')
}
export function withConnectorAuth(
operation: string,
handler: ConnectorHandler,
options: { service?: string } = {},
): (request: Request) => Promise<Response> {
const service = options.service ?? operation.split('.')[1] ?? operation
return async function wrapped(request: Request): Promise<Response> {
const requestId = `conn_${crypto.randomUUID()}`
const log = createLogger(`connect/${operation}`, { requestId, operation })
const supabase = createServiceClientNoCookies()
const presented = extractConnectorKey(request)
if (!presented) {
return NextResponse.json(
{ error: 'Missing connector key', code: 'CONNECTOR_KEY_MISSING' },
{ status: 401, headers: { 'X-Request-Id': requestId } },
)
}
const validation = await validateConnectorKey(presented, supabase)
if (!validation.ok) {
log.warn('connector auth rejected', { code: validation.code })
return NextResponse.json(
{ error: validation.error, code: validation.code },
{ status: validation.status, headers: { 'X-Request-Id': requestId } },
)
}
let response: Response
try {
response = await handler(request, { requestId, log, supabase, key: validation.key })
} catch (err) {
log.error('connector handler failed', err)
response = NextResponse.json(
{ error: 'Internal error', code: 'INTERNAL_ERROR' },
{ status: 500 },
)
}
response.headers.set('X-Request-Id', requestId)
// Metering: one row per request, never on the critical path. The path is
// REDACTED first: proxied paths carry the EB session id / account uid as
// segments, and the whole ledger design is that those handles never rest
// hosted-side (connector_connections stores sha256 only). Persisting the
// raw pathname would put the cleartext handle in connector_usage_events.
const endpoint = (() => {
try {
return redactEndpoint(new URL(request.url).pathname)
} catch {
return null
}
})()
const recordUsage = async (): Promise<void> => {
const { error: usageError } = await supabase.from('connector_usage_events').insert({
connector_key_id: validation.key.id,
service,
endpoint,
status_code: response.status,
})
if (usageError) log.warn('usage event not recorded', { err: usageError.message })
}
try {
// Off the response path: the caller should not wait on metering.
// Same pattern as lib/webhooks/dispatch-kick.ts.
after(() => recordUsage())
} catch {
// Outside a request scope (unit tests): record inline.
await recordUsage()
}
return response
}
}
@@ -1,56 +0,0 @@
import { describe, it, expect, afterEach, vi } from 'vitest'
import { getConnectorConfig, isConnectorConfigured } from '../config'
afterEach(() => vi.unstubAllEnvs())
describe('getConnectorConfig', () => {
it('is null without a key (hosted, or a self-host without a subscription)', () => {
vi.stubEnv('GNUBOK_CONNECTOR_KEY', '')
expect(getConnectorConfig()).toBeNull()
expect(isConnectorConfigured()).toBe(false)
})
it('defaults to the connector service origin and strips trailing slashes from an override', () => {
vi.stubEnv('GNUBOK_CONNECTOR_KEY', 'gnubok_ck_x')
vi.stubEnv('GNUBOK_CONNECT_URL', '')
expect(getConnectorConfig()).toEqual({ key: 'gnubok_ck_x', baseUrl: 'https://connect.accounted.se' })
vi.stubEnv('GNUBOK_CONNECT_URL', 'https://connect.example.se/')
expect(getConnectorConfig()?.baseUrl).toBe('https://connect.example.se')
})
it('rejects non-https and malformed GNUBOK_CONNECT_URL (fail closed: the key is never sent in plaintext)', () => {
vi.stubEnv('GNUBOK_CONNECTOR_KEY', 'gnubok_ck_x')
for (const bad of ['http://connect.example.se', 'ftp://connect.example.se', 'not a url', 'connect.example.se']) {
vi.stubEnv('GNUBOK_CONNECT_URL', bad)
expect(getConnectorConfig(), bad).toBeNull()
expect(isConnectorConfigured(), bad).toBe(false)
}
})
it('strips userinfo, query and fragment from the base URL (status echoes it back)', () => {
vi.stubEnv('GNUBOK_CONNECTOR_KEY', 'gnubok_ck_x')
for (const [dirty, clean] of [
['https://user:[email protected]', 'https://connect.example.se'],
['https://connect.example.se?token=secret', 'https://connect.example.se'],
['https://connect.example.se/base#fragment', 'https://connect.example.se/base'],
['https://user:[email protected]/base/?token=s#f', 'https://connect.example.se/base'],
]) {
vi.stubEnv('GNUBOK_CONNECT_URL', dirty)
expect(getConnectorConfig()?.baseUrl, dirty).toBe(clean)
}
})
it('keeps a clean override byte-identical (no surprise normalization)', () => {
vi.stubEnv('GNUBOK_CONNECTOR_KEY', 'gnubok_ck_x')
vi.stubEnv('GNUBOK_CONNECT_URL', 'https://connect.example.se/base')
expect(getConnectorConfig()?.baseUrl).toBe('https://connect.example.se/base')
})
it('allows plain http for loopback development hosts only', () => {
vi.stubEnv('GNUBOK_CONNECTOR_KEY', 'gnubok_ck_x')
for (const ok of ['http://localhost:3000', 'http://127.0.0.1:3000']) {
vi.stubEnv('GNUBOK_CONNECT_URL', ok)
expect(getConnectorConfig()?.baseUrl, ok).toBe(ok)
}
})
})
-254
View File
@@ -1,254 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import { connectorGrantExpiry, syncConnectorEntitlements, CONNECTOR_GRANT_TTL_MS } from '../sync'
/**
* A purpose-built Supabase mock: `companies` answers the paginated read,
* `capability_grants` records upserts and deletes (with their filters), so the
* grant arithmetic can be asserted exactly.
*/
function makeSupabase(companyIds: string[]) {
const upserts: Array<{ rows: unknown[]; opts: unknown }> = []
const deletes: Array<{ filters: Array<[string, ...unknown[]]> }> = []
let deleteCount = 0
const grantsChain = () => {
const deleteRecord: { filters: Array<[string, ...unknown[]]> } = { filters: [] }
const chain: Record<string, unknown> = {}
chain.upsert = (rows: unknown[], opts: unknown) => {
upserts.push({ rows, opts })
return Promise.resolve({ error: null })
}
chain.delete = () => {
deletes.push(deleteRecord)
const dchain: Record<string, unknown> = {
eq: (...a: unknown[]) => {
deleteRecord.filters.push(['eq', ...a])
return dchain
},
not: (...a: unknown[]) => {
deleteRecord.filters.push(['not', ...a])
return dchain
},
then: (resolve: (v: unknown) => void) => resolve({ error: null, count: deleteCount }),
}
return dchain
}
return chain
}
const companiesChain = () => {
let rangeFrom = 0
const chain: Record<string, unknown> = {
select: () => chain,
is: () => chain,
order: () => chain,
range: (from: number) => {
rangeFrom = from
return chain
},
then: (resolve: (v: unknown) => void) =>
resolve({ data: companyIds.slice(rangeFrom, rangeFrom + 1000).map((id) => ({ id })), error: null }),
}
return chain
}
const supabase = {
from: (table: string) => (table === 'companies' ? companiesChain() : grantsChain()),
} as unknown as SupabaseClient
return {
supabase,
upserts,
deletes,
setDeleteCount: (n: number) => {
deleteCount = n
},
}
}
const CONFIG = { key: 'gnubok_ck_test', baseUrl: 'https://app.gnubok.se' }
const NOW = new Date('2026-08-20T12:00:00.000Z')
const C1 = '11111111-1111-4111-8111-111111111111'
const C2 = '22222222-2222-4222-8222-222222222222'
function jsonResponse(status: number, body: unknown): Response {
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
}
beforeEach(() => vi.clearAllMocks())
describe('connectorGrantExpiry', () => {
it('is now + 72h without a period end, and the earlier of that and period_end + 3d otherwise', () => {
expect(connectorGrantExpiry(NOW, null)).toBe(new Date(NOW.getTime() + CONNECTOR_GRANT_TTL_MS).toISOString())
// period ends in 10 days: 72h wins
expect(connectorGrantExpiry(NOW, '2026-08-30T00:00:00.000Z')).toBe('2026-08-23T12:00:00.000Z')
// period ended yesterday: period_end + 3d wins (grace), earlier than 72h
expect(connectorGrantExpiry(NOW, '2026-08-19T12:00:00.000Z')).toBe('2026-08-22T12:00:00.000Z')
})
})
describe('syncConnectorEntitlements', () => {
it('is a no-op without a key', async () => {
const { supabase, upserts } = makeSupabase([C1])
const fetchImpl = vi.fn()
const result = await syncConnectorEntitlements(supabase, { config: null, fetchImpl })
expect(result.outcome).toBe('not_configured')
expect(fetchImpl).not.toHaveBeenCalled()
expect(upserts).toHaveLength(0)
})
it('reports the active company count with the key and writes one connector grant per company and scope', async () => {
const { supabase, upserts, deletes } = makeSupabase([C1, C2])
const fetchImpl = vi.fn().mockResolvedValue(
jsonResponse(200, {
data: {
status: 'active',
scopes: ['bank_sync', 'skatteverket', 'not_a_connector_scope'],
current_period_end: '2027-01-01T00:00:00.000Z',
org_number: '5561234567',
instance_url: 'https://bokforing.example.se',
server_time: NOW.toISOString(),
},
}),
)
const result = await syncConnectorEntitlements(supabase, {
config: CONFIG,
fetchImpl,
now: NOW,
instanceUrl: 'https://bokforing.example.se',
appVersion: '1.0.0',
})
expect(fetchImpl).toHaveBeenCalledTimes(1)
const [url, init] = fetchImpl.mock.calls[0] as [string, RequestInit]
expect(url).toBe('https://app.gnubok.se/api/connect/entitlements')
expect(init.method).toBe('POST')
expect((init.headers as Record<string, string>).Authorization).toBe('Bearer gnubok_ck_test')
expect(JSON.parse(String(init.body))).toEqual({
active_company_count: 2,
instance_url: 'https://bokforing.example.se',
app_version: '1.0.0',
})
expect(result).toMatchObject({ outcome: 'synced', companies: 2, grantsUpserted: 4, scopes: ['bank_sync', 'skatteverket'] })
expect(result.expiresAt).toBe('2026-08-23T12:00:00.000Z')
expect(upserts).toHaveLength(1)
expect(upserts[0].opts).toEqual({ onConflict: 'company_id,team_id,capability_key,source' })
expect(upserts[0].rows).toEqual(
expect.arrayContaining([
{ company_id: C1, team_id: null, capability_key: 'bank_sync', source: 'connector', expires_at: '2026-08-23T12:00:00.000Z' },
{ company_id: C2, team_id: null, capability_key: 'skatteverket', source: 'connector', expires_at: '2026-08-23T12:00:00.000Z' },
]),
)
// scopes no longer covered are dropped: delete source=connector NOT IN (kept)
expect(deletes).toHaveLength(1)
expect(deletes[0].filters).toEqual([
['eq', 'source', 'connector'],
['not', 'capability_key', 'in', '(bank_sync,skatteverket)'],
])
})
it('removes every connector grant on a 401/403 carrying a connector rejection code (freeze-and-retain)', async () => {
for (const [status, code] of [[401, 'CONNECTOR_KEY_INVALID'], [403, 'CONNECTOR_KEY_SUSPENDED'], [401, 'CONNECTOR_KEY_MISSING']] as const) {
const { supabase, upserts, deletes, setDeleteCount } = makeSupabase([C1])
setDeleteCount(4)
const result = await syncConnectorEntitlements(supabase, {
config: CONFIG,
fetchImpl: vi.fn().mockResolvedValue(jsonResponse(status, { error: 'rejected', code })),
now: NOW,
})
expect(result).toMatchObject({ outcome: 'revoked', httpStatus: status, grantsDeleted: 4 })
expect(upserts).toHaveLength(0)
expect(deletes[0].filters).toEqual([['eq', 'source', 'connector']])
}
})
it('keeps every grant on a 401/403 WITHOUT a connector rejection code (WAF challenge, edge protection, egress proxy)', async () => {
// A bare-status 401/403 can come from layers where the hosted app never
// ran. Only the hosted route's own rejection code proves revocation;
// anything else must not destroy the 72h offline cache.
const bodies: Array<[number, () => Response]> = [
[403, () => new Response('<html>Attack challenge</html>', { status: 403, headers: { 'content-type': 'text/html' } })],
[401, () => new Response('Authentication Required', { status: 401 })],
[401, () => jsonResponse(401, { error: 'edge auth', code: 'SOME_OTHER_CODE' })],
[403, () => jsonResponse(403, { message: 'forbidden by proxy' })],
]
for (const [status, make] of bodies) {
const { supabase, upserts, deletes } = makeSupabase([C1])
const result = await syncConnectorEntitlements(supabase, {
config: CONFIG,
fetchImpl: vi.fn().mockResolvedValue(make()),
now: NOW,
})
expect(result).toMatchObject({ outcome: 'server_error', httpStatus: status, grantsDeleted: 0 })
expect(upserts).toHaveLength(0)
expect(deletes).toHaveLength(0)
}
})
it('keeps grants on an UNKNOWN status or malformed current_period_end (contract drift lands in server_error, never delete)', async () => {
const shapes = [
{ status: 'past_due', scopes: ['bank_sync'], current_period_end: null, org_number: 'x', instance_url: null, server_time: 'x' },
{ status: 'active', scopes: ['bank_sync'], current_period_end: 'not-a-date', org_number: 'x', instance_url: null, server_time: 'x' },
{ status: 'active', scopes: [42], current_period_end: null, org_number: 'x', instance_url: null, server_time: 'x' },
]
for (const data of shapes) {
const { supabase, upserts, deletes } = makeSupabase([C1])
const result = await syncConnectorEntitlements(supabase, {
config: CONFIG,
fetchImpl: vi.fn().mockResolvedValue(jsonResponse(200, { data })),
now: NOW,
})
expect(result.outcome, JSON.stringify(data)).toBe('server_error')
expect(upserts).toHaveLength(0)
expect(deletes).toHaveLength(0)
}
})
it('removes every connector grant when the key is not active', async () => {
const { supabase, deletes } = makeSupabase([C1])
const result = await syncConnectorEntitlements(supabase, {
config: CONFIG,
fetchImpl: vi.fn().mockResolvedValue(
jsonResponse(200, { data: { status: 'suspended', scopes: ['bank_sync'], current_period_end: null, org_number: 'x', instance_url: null, server_time: 'x' } }),
),
now: NOW,
})
expect(result).toMatchObject({ outcome: 'revoked', status: 'suspended' })
expect(deletes).toHaveLength(1)
})
// The offline grace: a hosted outage must not touch the grants.
it('leaves grants alone on a network error, a 5xx and a 429', async () => {
const { supabase: s1, upserts: u1, deletes: d1 } = makeSupabase([C1])
const r1 = await syncConnectorEntitlements(s1, { config: CONFIG, fetchImpl: vi.fn().mockRejectedValue(new Error('ECONNREFUSED')), now: NOW })
expect(r1.outcome).toBe('network_error')
expect(u1).toHaveLength(0)
expect(d1).toHaveLength(0)
for (const status of [500, 503, 429]) {
const { supabase, upserts, deletes } = makeSupabase([C1])
const r = await syncConnectorEntitlements(supabase, { config: CONFIG, fetchImpl: vi.fn().mockResolvedValue(jsonResponse(status, {})), now: NOW })
expect(r).toMatchObject({ outcome: 'server_error', httpStatus: status })
expect(upserts).toHaveLength(0)
expect(deletes).toHaveLength(0)
}
})
it('treats an unreadable 200 payload as a server error, not a revocation', async () => {
const { supabase, deletes } = makeSupabase([C1])
const r = await syncConnectorEntitlements(supabase, { config: CONFIG, fetchImpl: vi.fn().mockResolvedValue(jsonResponse(200, { data: { nope: true } })), now: NOW })
expect(r.outcome).toBe('server_error')
expect(deletes).toHaveLength(0)
})
it('with an empty scope list writes nothing and drops every connector grant', async () => {
const { supabase, upserts, deletes } = makeSupabase([C1])
const r = await syncConnectorEntitlements(supabase, {
config: CONFIG,
fetchImpl: vi.fn().mockResolvedValue(jsonResponse(200, { data: { status: 'active', scopes: [], current_period_end: null, org_number: 'x', instance_url: null, server_time: 'x' } })),
now: NOW,
})
expect(r).toMatchObject({ outcome: 'synced', grantsUpserted: 0 })
expect(upserts).toHaveLength(0)
expect(deletes[0].filters).toEqual([['eq', 'source', 'connector']])
})
})
@@ -1,122 +0,0 @@
import { describe, it, expect, afterEach, vi } from 'vitest'
import {
bankConnectorMode,
peppolConnectorMode,
skatteverketConnectorMode,
hasOwnEnableBankingCredentials,
hasOwnPeppolCredentials,
hasOwnSkatteverketCredentials,
} from '../upstreams'
const ENV = ['GNUBOK_CONNECTOR_KEY', 'GNUBOK_CONNECT_URL', 'ENABLE_BANKING_PRIVATE_KEY', 'ENABLE_BANKING_APP_ID', 'ENABLE_BANKING_PRIVATE_KEY_PRODUCTION', 'ENABLE_BANKING_APP_ID_PRODUCTION', 'SKATTEVERKET_OAUTH2_CLIENT_ID', 'SKATTEVERKET_APIGW_CLIENT_ID', 'QVALIA_API_KEY', 'QVALIA_PARTNER_REG_NO', 'CONNECT_BANK_CANARY_COMPANIES', 'CONNECT_SKV_CANARY_COMPANIES'] as const
afterEach(() => vi.unstubAllEnvs())
function clear() {
for (const k of ENV) vi.stubEnv(k, '')
}
describe('connector-mode detection', () => {
it('is off when no connector key is set (hosted, or a self-host without a subscription)', () => {
clear()
vi.stubEnv('ENABLE_BANKING_PRIVATE_KEY', 'pk')
expect(bankConnectorMode()).toBeNull()
expect(skatteverketConnectorMode()).toBeNull()
})
// The load-bearing guard: an instance (or hosted) that has its OWN
// credentials never routes through the proxy, even with a key present.
it('is off for an upstream the instance has its own credentials for', () => {
clear()
vi.stubEnv('GNUBOK_CONNECTOR_KEY', 'gnubok_ck_x')
vi.stubEnv('ENABLE_BANKING_APP_ID', 'app-id')
vi.stubEnv('SKATTEVERKET_APIGW_CLIENT_ID', 'gw')
expect(hasOwnEnableBankingCredentials()).toBe(true)
expect(hasOwnSkatteverketCredentials()).toBe(true)
expect(bankConnectorMode()).toBeNull()
expect(skatteverketConnectorMode()).toBeNull()
})
it('routes to the hosted proxy when a key is set and no own credentials exist', () => {
clear()
vi.stubEnv('GNUBOK_CONNECTOR_KEY', 'gnubok_ck_x')
expect(bankConnectorMode()).toEqual({ baseUrl: 'https://connect.accounted.se/api/connect/bank', key: 'gnubok_ck_x' })
expect(skatteverketConnectorMode()).toEqual({ baseUrl: 'https://connect.accounted.se/api/connect/skv', key: 'gnubok_ck_x' })
})
it('honours GNUBOK_CONNECT_URL and strips a trailing slash', () => {
clear()
vi.stubEnv('GNUBOK_CONNECTOR_KEY', 'gnubok_ck_x')
vi.stubEnv('GNUBOK_CONNECT_URL', 'https://connect.example.se/')
expect(bankConnectorMode()?.baseUrl).toBe('https://connect.example.se/api/connect/bank')
})
it('treats the _PRODUCTION EB variants as own credentials', () => {
clear()
vi.stubEnv('GNUBOK_CONNECTOR_KEY', 'gnubok_ck_x')
vi.stubEnv('ENABLE_BANKING_PRIVATE_KEY_PRODUCTION', 'pk')
expect(bankConnectorMode()).toBeNull()
expect(skatteverketConnectorMode()).not.toBeNull()
})
})
describe('peppol connector mode', () => {
it('is off without a key and off with own Qvalia keys, on otherwise', () => {
clear()
expect(peppolConnectorMode()).toBeNull()
vi.stubEnv('GNUBOK_CONNECTOR_KEY', 'gnubok_ck_x')
expect(peppolConnectorMode()).toEqual({ baseUrl: 'https://connect.accounted.se/api/connect/peppol', key: 'gnubok_ck_x' })
vi.stubEnv('QVALIA_PARTNER_REG_NO', '5560000000')
expect(hasOwnPeppolCredentials()).toBe(true)
expect(peppolConnectorMode()).toBeNull()
})
})
describe('bank canary companies', () => {
it('routes only the listed companies through the connector while own credentials exist', () => {
clear()
vi.stubEnv('GNUBOK_CONNECTOR_KEY', 'gnubok_ck_x')
vi.stubEnv('ENABLE_BANKING_APP_ID', 'app-id')
vi.stubEnv('ENABLE_BANKING_PRIVATE_KEY', 'pk')
vi.stubEnv('CONNECT_BANK_CANARY_COMPANIES', 'c-1, c-2')
expect(bankConnectorMode()).toBeNull()
expect(bankConnectorMode('c-9')).toBeNull()
expect(bankConnectorMode('c-1')).toEqual({ baseUrl: 'https://connect.accounted.se/api/connect/bank', key: 'gnubok_ck_x' })
expect(bankConnectorMode('c-2')).not.toBeNull()
})
it('ignores the canary list without a connector key', () => {
clear()
vi.stubEnv('ENABLE_BANKING_APP_ID', 'app-id')
vi.stubEnv('CONNECT_BANK_CANARY_COMPANIES', 'c-1')
expect(bankConnectorMode('c-1')).toBeNull()
})
})
describe('skatteverket canary companies', () => {
it('routes only the listed companies through the connector while own credentials exist', () => {
clear()
vi.stubEnv('GNUBOK_CONNECTOR_KEY', 'gnubok_ck_x')
vi.stubEnv('SKATTEVERKET_OAUTH2_CLIENT_ID', 'client')
vi.stubEnv('SKATTEVERKET_APIGW_CLIENT_ID', 'gw')
vi.stubEnv('CONNECT_SKV_CANARY_COMPANIES', 'c-1, c-2')
expect(skatteverketConnectorMode()).toBeNull()
expect(skatteverketConnectorMode('c-9')).toBeNull()
expect(skatteverketConnectorMode('c-1')).toEqual({ baseUrl: 'https://connect.accounted.se/api/connect/skv', key: 'gnubok_ck_x' })
expect(skatteverketConnectorMode('c-2')).not.toBeNull()
})
it('does not let the bank list leak into Skatteverket routing', () => {
clear()
vi.stubEnv('GNUBOK_CONNECTOR_KEY', 'gnubok_ck_x')
vi.stubEnv('SKATTEVERKET_OAUTH2_CLIENT_ID', 'client')
vi.stubEnv('CONNECT_BANK_CANARY_COMPANIES', 'c-1')
expect(skatteverketConnectorMode('c-1')).toBeNull()
})
it('ignores the canary list without a connector key', () => {
clear()
vi.stubEnv('SKATTEVERKET_OAUTH2_CLIENT_ID', 'client')
vi.stubEnv('CONNECT_SKV_CANARY_COMPANIES', 'c-1')
expect(skatteverketConnectorMode('c-1')).toBeNull()
})
})
-65
View File
@@ -1,65 +0,0 @@
import { DEFAULT_CONNECT_BASE_URL } from '../contract'
import { createLogger } from '@/lib/logger'
const log = createLogger('connect/config')
/**
* Instance-side connector configuration (a self-hosted deployment).
*
* GNUBOK_CONNECTOR_KEY the `gnubok_ck_...` key issued for this instance
* GNUBOK_CONNECT_URL hosted origin, default https://app.gnubok.se
*
* Unset on hosted and on a self-host without a subscription: then the
* connector sync is a no-op and the connector capabilities stay gated.
*
* GNUBOK_CONNECT_URL must be https: the hourly sync sends the long-lived
* connector key as a Bearer header to this origin, so an http:// typo would
* ship the credential in plaintext. Plain http is allowed only for loopback
* hosts (local development against a dev server). An invalid or non-https
* URL disables the connector entirely (fail closed, nothing is sent).
*
* The returned baseUrl is rebuilt as origin + path: userinfo, query and
* fragment are stripped. They have no meaning in a base URL that gets paths
* appended to it, and /api/connector/status echoes baseUrl back to the
* operator, so anything secret-shaped pasted into the URL must not survive.
*/
export interface ConnectorConfig {
key: string
baseUrl: string
}
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
export function getConnectorConfig(): ConnectorConfig | null {
const key = process.env.GNUBOK_CONNECTOR_KEY?.trim()
if (!key) return null
const raw = (process.env.GNUBOK_CONNECT_URL?.trim() || DEFAULT_CONNECT_BASE_URL).replace(/\/+$/, '')
let url: URL
try {
url = new URL(raw)
} catch {
log.warn('GNUBOK_CONNECT_URL is not a valid URL; connector disabled', { value: raw })
return null
}
const loopback = LOOPBACK_HOSTS.has(url.hostname) || LOOPBACK_HOSTS.has(`[${url.hostname}]`)
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) {
log.warn('GNUBOK_CONNECT_URL must be https (http only for loopback); connector disabled', {
protocol: url.protocol,
host: url.hostname,
})
return null
}
const baseUrl = `${url.origin}${url.pathname.replace(/\/+$/, '')}`
if (baseUrl !== raw) {
// Log only the surviving value: the dropped parts are exactly what an
// operator might have pasted a credential into.
log.warn('GNUBOK_CONNECT_URL normalized to origin + path (userinfo/query/fragment stripped)', {
baseUrl,
})
}
return { key, baseUrl }
}
export function isConnectorConfigured(): boolean {
return getConnectorConfig() !== null
}
@@ -1,30 +0,0 @@
/**
* Cooldown for the operator-triggered connector sync (POST /api/connector/sync).
* Every run POSTs the instance's company count to the hosted entitlements
* endpoint, so a click storm in the settings panel must not turn into a
* request storm against the hosted service. Module-level state is enough:
* self-hosted runs as one long-lived process, and the hourly cron is
* unaffected (it never goes through this gate).
*/
export const MANUAL_SYNC_COOLDOWN_MS = 60_000
let inFlight = false
let lastStartedAt = 0
/** Claims the sync slot; false while a sync runs or the cooldown holds. */
export function tryBeginManualSync(now: number = Date.now()): boolean {
if (inFlight || now - lastStartedAt < MANUAL_SYNC_COOLDOWN_MS) return false
inFlight = true
lastStartedAt = now
return true
}
export function endManualSync(): void {
inFlight = false
}
/** Test hook: clears the in-flight flag and the cooldown window. */
export function resetManualSyncThrottle(): void {
inFlight = false
lastStartedAt = 0
}
-236
View File
@@ -1,236 +0,0 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import { CONNECTOR_CAPABILITIES } from '@/lib/entitlements/keys'
import { createLogger } from '@/lib/logger'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import {
CONNECTOR_ENTITLEMENTS_PATH,
type ConnectorEntitlements,
type ConnectorSyncReport,
} from '../contract'
import { getConnectorConfig, type ConnectorConfig } from './config'
const log = createLogger('connector-sync')
/**
* Grant rows ARE the offline cache. Each sync re-stamps the connector grants
* to expire at min(now + 72h, period_end + 3d): the hosted service only has
* to be reachable once in three days, and a lapsed subscription freezes the
* connector capabilities within days even if the sync keeps running. Uses
* the existing expiry check in lib/entitlements, zero new cache code.
*/
export const CONNECTOR_GRANT_TTL_MS = 72 * 60 * 60 * 1000
export const CONNECTOR_PERIOD_GRACE_MS = 3 * 24 * 60 * 60 * 1000
const UPSERT_CHUNK = 500
export type ConnectorSyncOutcome =
| 'not_configured'
| 'synced'
| 'revoked'
| 'network_error'
| 'server_error'
export interface ConnectorSyncResult {
outcome: ConnectorSyncOutcome
companies: number
grantsUpserted: number
grantsDeleted: number
status?: string
httpStatus?: number
scopes?: string[]
expiresAt?: string
message?: string
}
export interface ConnectorSyncOptions {
fetchImpl?: typeof fetch
now?: Date
config?: ConnectorConfig | null
instanceUrl?: string | null
appVersion?: string | null
}
export function connectorGrantExpiry(now: Date, currentPeriodEnd: string | null): string {
const ttl = now.getTime() + CONNECTOR_GRANT_TTL_MS
if (!currentPeriodEnd) return new Date(ttl).toISOString()
const periodGrace = new Date(currentPeriodEnd).getTime() + CONNECTOR_PERIOD_GRACE_MS
return new Date(Math.min(ttl, periodGrace)).toISOString()
}
async function deleteConnectorGrants(supabase: SupabaseClient, keepKeys: string[] | null): Promise<number> {
let query = supabase.from('capability_grants').delete({ count: 'exact' }).eq('source', 'connector')
if (keepKeys && keepKeys.length > 0) {
query = query.not('capability_key', 'in', `(${keepKeys.join(',')})`)
}
const { error, count } = await query
if (error) throw new Error(`Failed to delete connector grants: ${error.message}`)
return count ?? 0
}
/**
* One sync run: report the active company count to the hosted service, then
* translate the answer into source='connector' capability grants for every
* company on this instance.
*
* 200 active -> upsert grants for scopes, drop grants for scopes no
* longer covered (synced)
* 200 non-active -> delete all connector grants (freeze-and-retain) (revoked)
* 401 / 403 -> delete all connector grants (revoked)
* network error,
* 429, 5xx, other -> leave grants alone, they expire on their own (network_error / server_error)
*/
export async function syncConnectorEntitlements(
supabase: SupabaseClient,
options: ConnectorSyncOptions = {},
): Promise<ConnectorSyncResult> {
const config = options.config === undefined ? getConnectorConfig() : options.config
if (!config) return { outcome: 'not_configured', companies: 0, grantsUpserted: 0, grantsDeleted: 0 }
const now = options.now ?? new Date()
const fetchImpl = options.fetchImpl ?? fetch
const companies = await fetchAllRows<{ id: string }>(({ from, to }) =>
supabase
.from('companies')
.select('id')
.is('archived_at', null)
.order('id', { ascending: true })
.range(from, to),
)
const companyIds = companies.map((c) => c.id)
const report: ConnectorSyncReport = {
active_company_count: companyIds.length,
...(options.instanceUrl ? { instance_url: options.instanceUrl } : {}),
...(options.appVersion ? { app_version: options.appVersion } : {}),
}
let response: Response
try {
response = await fetchImpl(`${config.baseUrl}${CONNECTOR_ENTITLEMENTS_PATH}`, {
method: 'POST',
headers: {
Authorization: `Bearer ${config.key}`,
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify(report),
})
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
log.warn('connector sync: hosted service unreachable, keeping existing grants', { message })
return { outcome: 'network_error', companies: companyIds.length, grantsUpserted: 0, grantsDeleted: 0, message }
}
if (response.status === 401 || response.status === 403) {
// Delete the grant cache ONLY on a genuine connector rejection, proven by
// the hosted route's own JSON body code (with-connector-auth always sends
// one). A bare-status 401/403 also comes from layers where the app never
// ran: a Vercel WAF challenge page, edge deployment protection, an egress
// proxy at the self-host. Trusting the status alone let any of those wipe
// a paying instance's 72h offline grace within the hour: the same failure
// class as the RPC-error-to-401 mapping, one layer up. Anything without a
// known rejection code keeps the grants and expires naturally.
let rejectionCode: string | null = null
try {
const body = (await response.clone().json()) as { code?: string }
if (typeof body.code === 'string') rejectionCode = body.code
} catch {
// Non-JSON body (challenge/error page): not a connector rejection.
}
const isConnectorRejection =
rejectionCode === 'CONNECTOR_KEY_MISSING' ||
rejectionCode === 'CONNECTOR_KEY_INVALID' ||
rejectionCode === 'CONNECTOR_KEY_SUSPENDED'
if (isConnectorRejection) {
const grantsDeleted = await deleteConnectorGrants(supabase, null)
log.warn('connector sync: key rejected by hosted service, connector grants removed', {
httpStatus: response.status,
code: rejectionCode,
grantsDeleted,
})
return { outcome: 'revoked', companies: companyIds.length, grantsUpserted: 0, grantsDeleted, httpStatus: response.status }
}
log.warn('connector sync: 401/403 without a connector rejection code (edge/proxy?), keeping existing grants', {
httpStatus: response.status,
code: rejectionCode,
})
return { outcome: 'server_error', companies: companyIds.length, grantsUpserted: 0, grantsDeleted: 0, httpStatus: response.status }
}
if (!response.ok) {
log.warn('connector sync: hosted service error, keeping existing grants', { httpStatus: response.status })
return { outcome: 'server_error', companies: companyIds.length, grantsUpserted: 0, grantsDeleted: 0, httpStatus: response.status }
}
let entitlements: ConnectorEntitlements
try {
const body = (await response.json()) as { data?: ConnectorEntitlements }
// Full shape validation, not just presence: an UNKNOWN status string must
// land in keep-grants (server_error), not fall through to the
// "status !== 'active'" delete below (contract drift or a tampering
// middlebox must never wipe the cache), and a malformed
// current_period_end would make connectorGrantExpiry throw mid-write.
if (
!body.data ||
!['active', 'suspended', 'revoked'].includes(body.data.status as string) ||
!Array.isArray(body.data.scopes) ||
!body.data.scopes.every((s) => typeof s === 'string') ||
!(
body.data.current_period_end === null ||
body.data.current_period_end === undefined ||
(typeof body.data.current_period_end === 'string' &&
Number.isFinite(new Date(body.data.current_period_end).getTime()))
)
) {
throw new Error('unexpected entitlements payload')
}
entitlements = body.data
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
log.warn('connector sync: unreadable entitlements payload, keeping existing grants', { message })
return { outcome: 'server_error', companies: companyIds.length, grantsUpserted: 0, grantsDeleted: 0, httpStatus: response.status, message }
}
if (entitlements.status !== 'active') {
const grantsDeleted = await deleteConnectorGrants(supabase, null)
log.warn('connector sync: key not active, connector grants removed', { status: entitlements.status, grantsDeleted })
return { outcome: 'revoked', companies: companyIds.length, grantsUpserted: 0, grantsDeleted, status: entitlements.status }
}
const scopes = entitlements.scopes.filter((s) => (CONNECTOR_CAPABILITIES as readonly string[]).includes(s))
const expiresAt = connectorGrantExpiry(now, entitlements.current_period_end)
let grantsUpserted = 0
if (scopes.length > 0 && companyIds.length > 0) {
const rows = companyIds.flatMap((companyId) =>
scopes.map((capabilityKey) => ({
company_id: companyId,
team_id: null,
capability_key: capabilityKey,
source: 'connector',
expires_at: expiresAt,
})),
)
for (let i = 0; i < rows.length; i += UPSERT_CHUNK) {
const chunk = rows.slice(i, i + UPSERT_CHUNK)
const { error } = await supabase
.from('capability_grants')
.upsert(chunk, { onConflict: 'company_id,team_id,capability_key,source' })
if (error) throw new Error(`Failed to upsert connector grants: ${error.message}`)
grantsUpserted += chunk.length
}
}
// Scopes the subscription no longer covers (or none at all): drop them.
const grantsDeleted = await deleteConnectorGrants(supabase, scopes.length > 0 ? scopes : null)
log.info('connector sync complete', { companies: companyIds.length, scopes, grantsUpserted, grantsDeleted, expiresAt })
return {
outcome: 'synced',
companies: companyIds.length,
grantsUpserted,
grantsDeleted,
status: entitlements.status,
scopes,
expiresAt,
httpStatus: response.status,
}
}
-86
View File
@@ -1,86 +0,0 @@
import { getConnectorConfig } from './config'
import {
hasOwnEnableBankingCredentials,
hasOwnPeppolCredentials,
hasOwnSkatteverketCredentials,
} from '@/lib/entitlements/own-credentials'
/**
* Instance-side connector routing for the bank and Skatteverket upstreams.
*
* An upstream is in "connector mode" when this instance has a connector key
* AND no own credentials for that upstream. Hosted always has its own
* credentials, so hosted is never in connector mode: the check is what keeps
* hosted byte-identical. A self-host that pastes GNUBOK_CONNECTOR_KEY and
* leaves ENABLE_BANKING_PRIVATE_KEY / SKATTEVERKET_OAUTH2_CLIENT_ID unset gets
* routed through the hosted proxy instead.
*
* The own-credentials checks live in lib/entitlements/own-credentials.ts:
* they were forward-ported into the entitlement partition (PR #1747) so the
* gate and this routing seam can never disagree about what "own credentials"
* means. Re-exported here for the instance-side callers.
*/
export const CONNECTOR_COMPANY_HEADER = 'X-Connector-Company'
export const CONNECTOR_UPSTREAM_AUTH_HEADER = 'X-Connector-Upstream-Authorization'
export const CONNECTOR_UPSTREAM_CONTENT_TYPE_HEADER = 'X-Connector-Upstream-Content-Type'
export { hasOwnEnableBankingCredentials, hasOwnPeppolCredentials, hasOwnSkatteverketCredentials }
export interface ConnectorUpstream {
/** Base URL to send upstream requests to (the hosted proxy). */
baseUrl: string
/** The connector key, sent as Authorization: Bearer for proxy auth. */
key: string
}
/**
* Company ids that use the connector for an upstream even though this
* installation has its own credentials for it: the canary switch for moving
* an installation upstream by upstream (hosted Accounted moves its bank sync
* and its Skatteverket traffic to Connect a few companies at a time before
* dropping its own keys). Comma-separated. Ignored without a connector key.
*/
type CanaryEnv = 'CONNECT_BANK_CANARY_COMPANIES' | 'CONNECT_SKV_CANARY_COMPANIES'
function canaryCompanies(envName: CanaryEnv): Set<string> {
const raw = process.env[envName]?.trim()
if (!raw) return new Set()
return new Set(raw.split(',').map((v) => v.trim()).filter(Boolean))
}
function isCanary(envName: CanaryEnv, companyId: string | undefined): boolean {
return Boolean(companyId && canaryCompanies(envName).has(companyId))
}
export function bankConnectorMode(companyId?: string): ConnectorUpstream | null {
const cfg = getConnectorConfig()
if (!cfg) return null
if (hasOwnEnableBankingCredentials() && !isCanary('CONNECT_BANK_CANARY_COMPANIES', companyId)) return null
return { baseUrl: `${cfg.baseUrl}/api/connect/bank`, key: cfg.key }
}
/**
* Skatteverket data calls for a company. Callers without a company (OAuth
* start and token exchange, environment reporting) pass nothing and get the
* plain rule: own credentials win. The canary applies to user-token data
* reads and writes only, which is what carries a company id.
*/
export function skatteverketConnectorMode(companyId?: string): ConnectorUpstream | null {
const cfg = getConnectorConfig()
if (!cfg) return null
if (hasOwnSkatteverketCredentials() && !isCanary('CONNECT_SKV_CANARY_COMPANIES', companyId)) return null
return { baseUrl: `${cfg.baseUrl}/api/connect/skv`, key: cfg.key }
}
/**
* Peppol through Arcim's contracted access point. Same rule as the other
* upstreams: an instance with its own Qvalia partner keys runs Peppol itself
* and is never routed here.
*/
export function peppolConnectorMode(): ConnectorUpstream | null {
if (hasOwnPeppolCredentials()) return null
const cfg = getConnectorConfig()
if (!cfg) return null
return { baseUrl: `${cfg.baseUrl}/api/connect/peppol`, key: cfg.key }
}
@@ -1,80 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
const fetchWithTimeout = vi.fn()
vi.mock('@/lib/http/fetch-with-timeout', () => ({
fetchWithTimeout: (...a: unknown[]) => fetchWithTimeout(...a),
OAUTH_TIMEOUT_MS: 10_000,
SKATTEVERKET_EXCHANGE_TIMEOUT_MS: 8_000,
}))
import {
buildSkvAuthorizeUrl,
exchangeSkvCode,
refreshSkvToken,
SKV_API_BASES,
skvGatewayHeaders,
} from '../skatteverket-oauth'
const ENV = ['SKATTEVERKET_OAUTH_BASE_URL', 'SKATTEVERKET_OAUTH2_CLIENT_ID', 'SKATTEVERKET_OAUTH2_CLIENT_SECRET', 'SKATTEVERKET_APIGW_CLIENT_ID', 'SKATTEVERKET_APIGW_CLIENT_SECRET'] as const
beforeEach(() => {
vi.clearAllMocks()
vi.stubEnv('SKATTEVERKET_OAUTH2_CLIENT_ID', 'oauth-client')
vi.stubEnv('SKATTEVERKET_OAUTH2_CLIENT_SECRET', 'oauth-secret')
vi.stubEnv('SKATTEVERKET_APIGW_CLIENT_ID', 'gw-client')
vi.stubEnv('SKATTEVERKET_APIGW_CLIENT_SECRET', 'gw-secret')
})
afterEach(() => vi.unstubAllEnvs())
function tokenResponse(body: Record<string, unknown>, ok = true, status = 200) {
return { ok, status, text: async () => JSON.stringify(body), json: async () => body }
}
describe('buildSkvAuthorizeUrl', () => {
it('carries the registered client id, the connector state, PKCE and the default scopes', () => {
const u = new URL(buildSkvAuthorizeUrl('https://app.gnubok.se/cb', 'ck1.signed', { codeChallenge: 'chal' }))
expect(u.searchParams.get('client_id')).toBe('oauth-client')
expect(u.searchParams.get('redirect_uri')).toBe('https://app.gnubok.se/cb')
expect(u.searchParams.get('state')).toBe('ck1.signed')
expect(u.searchParams.get('code_challenge')).toBe('chal')
expect(u.searchParams.get('code_challenge_method')).toBe('S256')
expect(u.searchParams.get('scope')).toContain('agd')
expect(u.searchParams.get('scope')).toContain('agdredovisningperiod')
})
})
describe('token exchanges send the client secret and return tokens verbatim', () => {
it('authorization_code', async () => {
fetchWithTimeout.mockResolvedValue(tokenResponse({ access_token: 'at', refresh_token: 'rt', expires_in: 3600, scope: 's' }))
const t = await exchangeSkvCode('the-code', 'https://app.gnubok.se/cb', 'verifier')
expect(t).toEqual({ access_token: 'at', refresh_token: 'rt', expires_in: 3600, scope: 's' })
const body = fetchWithTimeout.mock.calls[0][1].body as string
expect(body).toContain('grant_type=authorization_code')
expect(body).toContain('client_secret=oauth-secret')
expect(body).toContain('code_verifier=verifier')
})
it('refresh_token', async () => {
fetchWithTimeout.mockResolvedValue(tokenResponse({ access_token: 'at2', refresh_token: 'rt2', expires_in: 3600 }))
const t = await refreshSkvToken('rt')
expect(t.access_token).toBe('at2')
expect(fetchWithTimeout.mock.calls[0][1].body).toContain('grant_type=refresh_token')
})
it('throws on a non-ok token response', async () => {
fetchWithTimeout.mockResolvedValue(tokenResponse({ error: 'invalid_grant' }, false, 400))
await expect(exchangeSkvCode('c', 'https://x/cb')).rejects.toThrow(/token exchange failed \(400\)/)
})
})
describe('data API allowlist + gateway headers', () => {
it('exposes exactly the four backing services', () => {
expect(Object.keys(SKV_API_BASES).sort()).toEqual(['agd-inlamning', 'agd-period', 'moms', 'skattekonto'])
})
it('adds Arcim gateway client credentials + a correlation id', () => {
const h = skvGatewayHeaders()
expect(h.Client_Id).toBe('gw-client')
expect(h.Client_Secret).toBe('gw-secret')
expect(h.skv_client_correlation_id).toMatch(/[0-9a-f-]{36}/)
})
})
-117
View File
@@ -1,117 +0,0 @@
/**
* JWT generation for Enable Banking API authentication
*
* Enable Banking requires JWT tokens signed with RS256 using your private key.
* The JWT is included in the Authorization header for all API calls.
*/
import * as crypto from 'crypto'
// Prefer _PRODUCTION variants when available (Vercel production deploys)
const APP_ID = process.env.ENABLE_BANKING_APP_ID_PRODUCTION || process.env.ENABLE_BANKING_APP_ID
const PRIVATE_KEY_RAW = process.env.ENABLE_BANKING_PRIVATE_KEY_PRODUCTION || process.env.ENABLE_BANKING_PRIVATE_KEY
interface JWTHeader {
typ: string
alg: string
kid: string
}
interface JWTPayload {
iss: string
aud: string
iat: number
exp: number
}
function base64UrlEncode(data: Buffer | string): string {
const str = typeof data === 'string' ? data : data.toString('base64')
return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}
function getPrivateKey(): string {
if (!PRIVATE_KEY_RAW) {
throw new Error('ENABLE_BANKING_PRIVATE_KEY environment variable is not set')
}
// Try decoding as base64-encoded PEM (sandbox format: base64 wrapping a PEM string)
const decoded = Buffer.from(PRIVATE_KEY_RAW, 'base64').toString('utf-8')
if (decoded.startsWith('-----BEGIN')) {
return decoded
}
// Otherwise treat as raw base64 DER key material: wrap in PEM headers
const lines = PRIVATE_KEY_RAW.match(/.{1,64}/g) || []
return `-----BEGIN PRIVATE KEY-----\n${lines.join('\n')}\n-----END PRIVATE KEY-----`
}
/**
* Generate a JWT token for Enable Banking API authentication
*
* @param expiresInSeconds - Token validity in seconds (default: 3600 = 1 hour)
* @returns Signed JWT token
*/
export function generateJWT(expiresInSeconds: number = 3600): string {
if (!APP_ID) {
throw new Error('ENABLE_BANKING_APP_ID environment variable is not set')
}
const now = Math.floor(Date.now() / 1000)
const header: JWTHeader = {
typ: 'JWT',
alg: 'RS256',
kid: APP_ID
}
const payload: JWTPayload = {
iss: 'enablebanking.com',
aud: 'api.enablebanking.com',
iat: now,
exp: now + expiresInSeconds
}
// Encode header and payload
const headerBase64 = base64UrlEncode(Buffer.from(JSON.stringify(header)))
const payloadBase64 = base64UrlEncode(Buffer.from(JSON.stringify(payload)))
// Create signature
const signatureInput = `${headerBase64}.${payloadBase64}`
const privateKey = getPrivateKey()
const sign = crypto.createSign('RSA-SHA256')
sign.update(signatureInput)
sign.end()
const signature = sign.sign(privateKey)
const signatureBase64 = base64UrlEncode(signature)
return `${headerBase64}.${payloadBase64}.${signatureBase64}`
}
// JWT token cache
let cachedToken: string | null = null
let cachedTokenExpiry: number = 0
/**
* Get the Authorization header value for Enable Banking API.
* Caches JWT tokens and reuses them until 60s before expiry.
*/
export function getAuthorizationHeader(): string {
const now = Math.floor(Date.now() / 1000)
if (cachedToken && now < cachedTokenExpiry - 60) {
return `Bearer ${cachedToken}`
}
const expiresInSeconds = 3600
const token = generateJWT(expiresInSeconds)
cachedToken = token
cachedTokenExpiry = now + expiresInSeconds
return `Bearer ${token}`
}
/** @internal Reset token cache: for testing only */
export function _resetTokenCache(): void {
cachedToken = null
cachedTokenExpiry = 0
}
-178
View File
@@ -1,178 +0,0 @@
import crypto from 'node:crypto'
import { fetchWithTimeout, OAUTH_TIMEOUT_MS, SKATTEVERKET_EXCHANGE_TIMEOUT_MS } from '@/lib/http/fetch-with-timeout'
/**
* Skatteverket OAuth2 (`per`/BankID flow) helpers for the hosted connector
* broker. The instance-side extension has its own copy (it runs its own flow
* on hosted); this module is the CORE copy the connector proxy uses, so core
* does not import from @/extensions/. Same endpoints and client credentials
* (SKV registers ONE integrator = Arcim), the difference is only who calls:
* here the hosted proxy exchanges the code/refresh on behalf of a self-hosted
* instance and returns the tokens for the instance to store.
*/
const DEFAULT_OAUTH_BASE_URL = 'https://peroauth2.test.skatteverket.se/oauth2/v1/per'
// AGI needs both agd and agdredovisningperiod; skattekonto needs ska (do not
// "clean up"): the exact set is documented in the extension's oauth.ts.
const DEFAULT_SCOPES = 'momsdeklaration inkforetag skahmst skattekonto ska agd agdredovisningperiod'
/**
* Every SKV base URL must be https (http only for loopback dev): the OAuth
* exchange carries Arcim's client secret and the data calls carry the
* gateway Client_Secret, so a plaintext override would ship credentials
* unencrypted. Throws so a bad env fails the request, never the build.
*/
function httpsOnly(raw: string, name: string): string {
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(`${name} must be https: Skatteverket credentials ride in these requests`)
}
return raw
}
export function skvOauthBaseUrl(): string {
return httpsOnly(process.env.SKATTEVERKET_OAUTH_BASE_URL || DEFAULT_OAUTH_BASE_URL, 'SKATTEVERKET_OAUTH_BASE_URL')
}
export function skvDefaultScopes(): string {
return DEFAULT_SCOPES
}
function clientId(): string {
const v = process.env.SKATTEVERKET_OAUTH2_CLIENT_ID
if (!v) throw new Error('SKATTEVERKET_OAUTH2_CLIENT_ID is required')
return v
}
function clientSecret(): string {
const v = process.env.SKATTEVERKET_OAUTH2_CLIENT_SECRET
if (!v) throw new Error('SKATTEVERKET_OAUTH2_CLIENT_SECRET is required')
return v
}
export function buildSkvAuthorizeUrl(
redirectUri: string,
state: string,
options?: { scope?: string; codeChallenge?: string },
): string {
const params = new URLSearchParams({
client_id: clientId(),
response_type: 'code',
state,
redirect_uri: redirectUri,
scope: options?.scope || DEFAULT_SCOPES,
})
if (options?.codeChallenge) {
params.set('code_challenge', options.codeChallenge)
params.set('code_challenge_method', 'S256')
}
return `${skvOauthBaseUrl()}/authorize?${params.toString()}`
}
export interface SkvTokenResponse {
access_token: string
refresh_token: string | null
expires_in: number
scope: string
}
/** Raw token exchange, returned verbatim to the instance (it stores them). */
export async function exchangeSkvCode(code: string, redirectUri: string, codeVerifier?: string): Promise<SkvTokenResponse> {
const body = new URLSearchParams({
grant_type: 'authorization_code',
client_id: clientId(),
client_secret: clientSecret(),
redirect_uri: redirectUri,
code,
})
if (codeVerifier) body.set('code_verifier', codeVerifier)
return postToken(body, SKATTEVERKET_EXCHANGE_TIMEOUT_MS, 'Skatteverket token exchange')
}
/**
* SKV's terminal dead-refresh-token dialects, matched against the error
* message postToken throws (which embeds status + body). The same set the
* instance-side extension classifies as SESSION_EXPIRED on the direct path:
* 404 id_not_found / "refresh token is not found", 400 "Refresh Token status
* is expired", and OAuth2's standard 400 invalid_grant. `per`-flow refresh
* tokens live 65 minutes, so this is the DOMINANT refresh outcome, not an
* edge case: the broker must distinguish it from transient failures or every
* connector instance loses its reconnect flow (skeptic refutation on PR6b-2).
* Config-shaped 400s (invalid_client, invalid_scope) deliberately do NOT
* match: a reconnect cannot fix those.
*/
export function isSkvDeadRefreshTokenError(message: string): boolean {
return (
(/\b404\b/.test(message) && /id_not_found|refresh token is not found/i.test(message)) ||
(/\b400\b/.test(message) &&
(/refresh token status is expired/i.test(message) ||
/"error"\s*:\s*"invalid_grant"/i.test(message)))
)
}
export async function refreshSkvToken(refreshToken: string): Promise<SkvTokenResponse> {
const body = new URLSearchParams({
grant_type: 'refresh_token',
client_id: clientId(),
client_secret: clientSecret(),
refresh_token: refreshToken,
})
return postToken(body, OAUTH_TIMEOUT_MS, 'Skatteverket token refresh')
}
async function postToken(body: URLSearchParams, timeoutMs: number, description: string): Promise<SkvTokenResponse> {
const response = await fetchWithTimeout(
`${skvOauthBaseUrl()}/token`,
// redirect 'error': a 307/308 would resend client_secret + code/refresh
// token to the redirect target.
{ method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }, body: body.toString(), redirect: 'error' },
{ timeoutMs, description },
)
if (!response.ok) {
const text = await response.text()
throw new Error(`${description} failed (${response.status}): ${text}`)
}
const data = (await response.json()) as { access_token: string; refresh_token?: string; expires_in?: number; scope?: string }
return {
access_token: data.access_token,
refresh_token: data.refresh_token ?? null,
expires_in: data.expires_in ?? 3600,
scope: data.scope ?? DEFAULT_SCOPES,
}
}
export function generatePkcePair(): { verifier: string; challenge: string } {
const verifier = crypto.randomBytes(64).toString('base64url')
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url')
return { verifier, challenge }
}
/**
* The Skatteverket data-API base URLs, keyed by the short service segment the
* connector proxy exposes. One integrator, several backing APIs; the instance
* addresses them as /api/connect/skv/api/<service>/<path>.
*/
export const SKV_API_BASES: Record<string, () => string> = {
moms: () => httpsOnly(process.env.SKATTEVERKET_API_BASE_URL || 'https://api.test.skatteverket.se/momsdeklaration/v1', 'SKATTEVERKET_API_BASE_URL'),
skattekonto: () => httpsOnly(process.env.SKATTEVERKET_SKATTEKONTO_API_BASE_URL || 'https://api.test.skatteverket.se/beskattning/skattekonto/v2', 'SKATTEVERKET_SKATTEKONTO_API_BASE_URL'),
'agd-inlamning': () => httpsOnly(process.env.SKATTEVERKET_AGD_INLAMNING_API_BASE_URL || 'https://api.test.skatteverket.se/arbetsgivardeklaration/inlamning/v1', 'SKATTEVERKET_AGD_INLAMNING_API_BASE_URL'),
'agd-period': () => httpsOnly(process.env.SKATTEVERKET_AGD_PERIOD_API_BASE_URL || 'https://api.test.skatteverket.se/arbetsgivardeklaration/hanteraredovisningsperiod/v1', 'SKATTEVERKET_AGD_PERIOD_API_BASE_URL'),
}
function apigwClientId(): string {
const v = process.env.SKATTEVERKET_APIGW_CLIENT_ID
if (!v) throw new Error('SKATTEVERKET_APIGW_CLIENT_ID is required')
return v
}
function apigwClientSecret(): string {
const v = process.env.SKATTEVERKET_APIGW_CLIENT_SECRET
if (!v) throw new Error('SKATTEVERKET_APIGW_CLIENT_SECRET is required')
return v
}
/** The API-gateway headers Arcim's registered client must add to every SKV data call. */
export function skvGatewayHeaders(): Record<string, string> {
return {
Client_Id: apigwClientId(),
Client_Secret: apigwClientSecret(),
skv_client_correlation_id: crypto.randomUUID(),
}
}