feat(connect): Skatteverket broker + data proxy for self-hosted instances (tokens stay on the instance) (#1757)
* feat(entitlements): partition the self-host bypass so connector capabilities fall through to grants; capability_grants.source accepts 'connector' Sovereign plan WS3 PR3: ships dark, nothing changes for hosted. - lib/entitlements/keys.ts: CONNECTOR_CAPABILITIES = bank_sync, skatteverket, org_lookup, migration (services Accounted operates that a self-hosted instance cannot provide itself) + isConnectorCapability(). Separate from PAID_CAPABILITIES and outside the trial-seed trigger on purpose: a hosted company can never hold a connector grant. - lib/entitlements/has-capability.ts: isPaywallBypassed() -> isBypassedFor(key). Hosted: byte-identical (dev / DISABLE_PAYWALL bypass, FORCE_PAYWALL wins, else the grant lookup). Self-host: local capabilities always on (FORCE_PAYWALL included, as the existing test demands); connector capabilities behave like hosted, i.e. dev bypass, FORCE_PAYWALL, else the grant lookup where the connector sync will write source='connector' rows. getCompanyEntitlements on a self-host: local paid keys + active connector keys, state 'paid' with an active connector grant else 'none' (never the hosted trial copy). - Migration 20260820122000: capability_grants.source CHECK gains 'connector', found through pg_constraint (the CHECK was declared inline and auto-named; Postgres stores IN as = ANY, matched accordingly). pg-real test: connector accepted, unknown source rejected, upsert on the (scope, key, source) identity, trial seed writes no connector rows. - Tests: self-hosted connector matrix (local all-on without DB, connector gated by grant/expiry, dev bypass all-on, FORCE_PAYWALL gates connector keys only, bulk resolution, entitlements shape); two pre-existing tests that asserted the old "self-host holds connector keys" contract updated to the new one. Verified: full unit suite green, pg-real suite for lib/entitlements green against a local supabase/postgres with every migration applied, lint ratchet, guards. Deferred to the instance-wiring PR: adding the connector extensions to the self-host Docker preset (dead-end upsells until a key can be issued). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor(entitlements): fold the self-host branch into the existing grants query One .or(scopeFilter), not two: the duplicated helper pushed the no-phantom-columns unresolvable-expression count to 380/379. Behaviour is unchanged; the self-host matrix tests still pass. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(connect): hosted connector-key registry + validate RPC + entitlements endpoint; instance sync writes connector grants hourly Sovereign plan WS3 PR4 ("key infra enabling manual sales"), stacked on the entitlement partition (#1747). Nothing is purchasable yet; this is the plumbing both ends need before the first manually issued key. Hosted side: - Migration 20260820123000: connector_keys (SHA-256 key_hash, prefix, org_number, pinned instance_url, scopes, status, Stripe ids, current_period_end, per-minute rate limit, active_company_count, last_seen/synced) and connector_usage_events (per-request metering, separate from metered_events whose company_id references hosted companies). RLS on, NO policies: service role only. RPC validate_and_increment_connector_key copies the api_keys pattern (FOR UPDATE, minute window, suspended reported not counted, revoked = no row) and is REVOKEd from PUBLIC/anon/authenticated, GRANTed to service_role. pg-real test covers validate/count, unknown+revoked, suspended, rate limit, execute privileges per role, RLS invisibility, usage cascade. - lib/connect/contract.ts (shared wire types), lib/connect/hosted/keys.ts (generate/hash/validate -> 401/403/429 mapping), with-connector-auth.ts (Bearer or X-Connector-Key, one usage row per request, 500 envelope on handler throw), /api/connect/entitlements GET + POST (records active_company_count, pins instance_url on first report, never moves a pinned one), scripts/issue-connector-key.ts (dry run unless --confirm, prints the key once + the .env lines). Instance side: - lib/connect/instance/config.ts (GNUBOK_CONNECTOR_KEY, GNUBOK_CONNECT_URL default https://app.gnubok.se), sync.ts: reports the active company count and writes source='connector' grants for every company x covered scope, expires_at = min(now+72h, period_end+3d); 401/403 or a non-active status deletes them (freeze-and-retain); network/5xx/429 leave them alone. /api/connector/sync/cron (hourly) runs it; not_configured without a key. - Crontab generator gains EXTRA_JOBS (variant-only jobs not in vercel.json, with reasons) + drift tests; docker/crontab.self-hosted regenerated with the hourly sync. Docs (SELF-HOSTING connector section, env templates), DECISIONS. Tests: 52 new unit tests (keys, auth wrapper, route, config, sync outcomes and grant arithmetic, cron route, crontab EXTRA_JOBS) + 7 pg-real tests run locally against supabase/postgres with every migration applied. no-phantom-columns ceiling +1 with a reason (the bulk grant upsert). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(connect): Enable Banking proxy for self-hosted instances, with a secret-free ownership ledger and a global rate budget Sovereign plan WS3 PR5a, stacked on the connector-key infra (#1748). A self-hosted instance with a `bank_sync`-scoped connector key can now connect a bank through Arcim's PSD2 credentials; the bank session id and all transaction data stay in the instance's own database (founder decision: tokens on the instance, proxy stateless). - Migration 20260820124000: `connector_connections` (secret-free ledger: sha256 of the EB session id + account uids, service-role only), `connector_upstream_counters` + RPC `connector_reserve_upstream` (global budget under EB Annex 1 §5's 300/min, shared with hosted), and `connector_keys.limits` jsonb; validate RPC v2 returns limits. All RPCs REVOKEd from PUBLIC/anon/authenticated, GRANTed service_role. pg-real covers all of it. - EB JWT minting moved to lib/connect/upstreams/enable-banking-jwt.ts (core must not import @/extensions/); the extension re-exports it, tests unchanged. - lib/connect/hosted/{state,ledger,upstream-budget}.ts: HMAC-signed connector state (15-min TTL) so the consent redirect can use OUR registered EB callback and bounce back to the instance, no per-instance redirect URI at EB; the callback route gains that connector branch. - app/api/connect/bank/[...path]: path allowlist (aspsps, auth, sessions, accounts/{uid}/{balances,transactions}), never open passthrough. POST /auth enforces the per-company connection quota + rewrites redirect/state; reads/deletes verify ledger ownership; every upstream call takes the global budget (429 + Retry-After when exhausted). - issue-connector-key.ts: scopes default bank_sync,skatteverket (TIC out of v1), --bank/skv-connections-per-company + --sync-min-interval. - Docs (SELF-HOSTING: bank connector live), DECISIONS. Verified: 52 connect unit tests + 13 pg-real (run locally against supabase/postgres with all migrations) + EB extension suite (225, jwt relocation intact); full unit suite 15 979 green; tsc, guards, lint clean. Not in this PR: SKV broker (PR5b) and instance wiring (PR6). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(connect): Skatteverket broker + data proxy for self-hosted instances (tokens stay on the instance) Sovereign plan WS3 PR5b, stacked on the bank proxy (#1751). A self-hosted instance with a `skatteverket`-scoped connector key can now run the BankID consent, file VAT/AGI and sync skattekonto through Arcim's registered Skatteverket client; the SKV tokens are returned to the instance and stored (encrypted) there. - lib/connect/upstreams/skatteverket-oauth.ts: core-side SKV OAuth + data helpers (authorize URL, code/refresh exchange with Arcim's client secret, the four backing-API base URLs, the API-gateway Client_Id/Client_Secret headers). Core can't import @/extensions/, so this duplicates the extension's endpoints/scope set (one integrator = Arcim), mirroring the EB JWT relocation. - app/api/connect/skv/oauth/authorize-url: builds the authorize URL against OUR registered redirect_uri + a signed connector state, per-company SKV connection quota, pending ledger row. - app/api/connect/skv/oauth/token: exchanges/refreshes and RETURNS the tokens to the instance; the ledger keeps only sha256(access_token) + sha256(refresh_token). - app/api/connect/skv/api/[...path]: allowlist over moms / skattekonto / agd-inlamning / agd-period. The instance sends the user's SKV Bearer (as X-Connector-Upstream-Authorization) + X-Connector-Key; the proxy checks the token hash against the ledger, adds Arcim's gateway credentials (never exposed to the instance), forwards. Same per-key + global budget as bank. - The Skatteverket extension /callback gains the connector branch (isConnectorState -> 302 back to the instance; code never exchanged there). - Docs (SELF-HOSTING: SKV connector live) + DECISIONS. Tests: SKV oauth lib, authorize-url, token, data proxy, callback connector branch (all green; 74 connect + 425 connect/SKV). tsc, guards, lint clean; no-phantom-columns held at 380 (literal update branches). Not in this PR: instance-side wiring (PR6). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(connect): SKV broker review+skeptic batch: state-bound exchange, owned-only refresh, identity-number redaction, quota reservation, https-only bases, docs dedupe Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UzNkSsR18pLFitJdYn8QEb * docs(self-host): restore the instance-wiring qualifier in the connector section Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UzNkSsR18pLFitJdYn8QEb * fix(connect): PR #1757 review batch 2: redirect 'error' on credential fetches, mandatory ledger writes before token return, MD037 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UzNkSsR18pLFitJdYn8QEb * fix(connect): reject encoded path separators in SKV data-proxy segments (traversal guard) The WHATWG parser normalizes raw dot segments before the route runs; what survives is an encoded separator inside a segment (a%2Fb, ..%2Fx, a%5Cb), which would escape the allowlisted service base once the upstream fetch re-normalizes. splitPath now decodes each segment and rejects dot segments and separator-bearing values. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UzNkSsR18pLFitJdYn8QEb --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: Emil <emilmattsson14@gmail.com>
This commit is contained in:
co-authored by
Claude Fable 5
Jakob Wennberg
Emil
parent
5131ee9085
commit
37e50c272d
@@ -122,6 +122,27 @@ export async function findPendingByState(
|
||||
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,
|
||||
|
||||
@@ -50,7 +50,11 @@ export function extractConnectorKey(request: Request): string | null {
|
||||
* before a path is persisted for metering. Literal route words (sessions,
|
||||
* accounts, balances, aspsps, ...) survive, so the metric keys stay useful.
|
||||
*/
|
||||
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,})$/i
|
||||
// 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
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
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}/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,157 @@
|
||||
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')
|
||||
}
|
||||
|
||||
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(),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user