* feat(skatteverket): ombudsregister grant verification, honest session expiry, daily ombud sync
Users reported the Skatteverket connection "just disappearing" with no
banner, needing BankID again every time. Two causes, both fixed here:
1. SKV's per-flow refresh token lives 65 minutes. /status and the
skv_disconnected notice called any stored refresh token "refreshable",
so a days-dead session reported healthy and the reconnect banner never
fired until a submission failed live. lib/skatteverket/session-lifetime
now decides refreshability (expires_at + 5 min, refresh cap) for both
surfaces; the settings panel states the one-hour session lifetime.
2. The durable fix is the ombud (system certificate) path, dormant since
July behind SKATTEVERKET_SYSTEM_AUTH_MODE. Skatteverket added scope
`obr` (Ombudshantering v2) to our application id on 2026-09-01, so grant
verification can now ask the ombudsregister instead of classifying 403s
from the read services:
- lib/ombud-client.ts: GET /ombud/autentisieratOmbud, GET /roller,
POST .../djuplank/utseombud, on the system identity, per the public
tjanstebeskrivning v2.0 (mirrored in dev_docs/skatteverket/ombudshantering).
Role codes are env-pinned (SKATTEVERKET_OMBUD_ROLL_LASOMBUD/_MOMS) or
matched on rollbeskrivning text; a deep link never mints with a
guessed code.
- grant-probe.ts: register first, read-service probes only as fallback.
- New daily cron /api/extensions/skatteverket/ombud/sync/cron (30 3 * * *):
one register call discovers every company that granted us, creates or
downgrades connection rows by org number, runs from shadow mode on,
and never mass-revokes on an empty register.
- POST /system-connection/deeplink + "Utse {app} som ombud" button:
the company lands in SKV's e-service with roles pre-selected.
- Default system scopes include `obr`; skvRequestWithAuth gains an
`accept` option (Ombudshantering requires the Accept header).
Still inert in prod until the org certificate and avtal land; the cron and
verify routes no-op while system auth is off or unconfigured.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HkLnhWnxt5wWB9j3vfMmxu
* fix(skatteverket): skeptic round on ombud sync, register 404 fallback, opt-in-only rows, mass-downgrade guard
Cron touches only existing connection rows (a tenant's own Verifiera or
deep-link opt-in; the deeplink route now records a pending row), so an
org-number twin never gets auto-verified, and rows the tenant revoked
locally stay revoked. A register 404 throws by default (spec: wrong URI)
and is empty only for the cron, which guards it. Decisions are planned
before any upsert; a run that would fully deny >= 3 rows and > 50% of the
granted ones applies no downgrade. Grants that classify as neither
behörighet are 'error', not 'denied'. Literal select in listConnections for
the phantom-column scanner. window.open without 'noopener' so the
pre-opened tab exists; opener nulled by hand. Deeplink route test added.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HkLnhWnxt5wWB9j3vfMmxu
* fix(skatteverket): CodeRabbit round: exact role labels, paginate connections, deny never-listed rows, fail deeplink without opt-in row
Role descriptions match the whole label so 'Momsdeklaration,
deklarationsombud' is never read as the narrow moms role. listConnections
pages through fetchAllRows on (created_at, id). A pending row the register
never lists is written once as denied instead of staying 'Inte verifierad'.
The deeplink route returns 500 when the opt-in row cannot be stored, and the
panel navigates in-tab when the pre-opened tab was blocked.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HkLnhWnxt5wWB9j3vfMmxu
* fix(skatteverket): fence ombud grants on contested org numbers; cron honours unrecognised role codes
An org number claimed by more than one live company is contested: verify
and deep link answer 409 ORG_NUMBER_CONTESTED and the nightly sync changes
nothing on it, so a tenant that typed a victim's public org number cannot
inherit the victim's grant. The sync also skips huvudmän whose register
roles classify as neither behörighet (pinning problem, never a denial),
mirroring probeViaOmbudsregister.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HkLnhWnxt5wWB9j3vfMmxu
* fix(skatteverket): validate the ombud deep link host; withdraw grants on contested org numbers
The register's djuplank must be an https skatteverket.se URL before it is
returned or navigated to (the settings page follows it). The nightly sync
now withdraws a grant already recorded on an org number that more than one
live company claims, instead of only refusing new ones.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HkLnhWnxt5wWB9j3vfMmxu
---------
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
156 lines
6.0 KiB
TypeScript
156 lines
6.0 KiB
TypeScript
/**
|
|
* System (CCG) auth: config parsing and the token provider's cache
|
|
* semantics. The stub transport stands in for the real mechanism, which is
|
|
* pending Skatteverket's org-flow documentation.
|
|
*/
|
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
|
|
|
const mockFetchToken = vi.fn()
|
|
vi.mock('../lib/system-auth/transport', async (importOriginal) => {
|
|
const actual = (await importOriginal()) as Record<string, unknown>
|
|
return {
|
|
...actual,
|
|
getSystemAuthTransport: () => ({ fetchToken: (...a: unknown[]) => mockFetchToken(...a) }),
|
|
}
|
|
})
|
|
|
|
import {
|
|
getSystemAuthMode,
|
|
getSystemAuthMechanism,
|
|
getSystemScopes,
|
|
isSystemAuthConfigured,
|
|
getSystemCertInfo,
|
|
} from '../lib/system-auth/config'
|
|
import {
|
|
getSystemAccessToken,
|
|
invalidateSystemToken,
|
|
SystemAuthUnavailableError,
|
|
__resetSystemTokenCacheForTests,
|
|
} from '../lib/system-auth/token-provider'
|
|
|
|
const ENV_KEYS = [
|
|
'SKATTEVERKET_SYSTEM_AUTH_MODE',
|
|
'SKATTEVERKET_SYSTEM_AUTH_MECHANISM',
|
|
'SKATTEVERKET_SYSTEM_OAUTH_TOKEN_URL',
|
|
'SKATTEVERKET_SYSTEM_CERT_PEM_B64',
|
|
'SKATTEVERKET_SYSTEM_KEY_PEM_B64',
|
|
'SKATTEVERKET_SYSTEM_SCOPES',
|
|
]
|
|
let savedEnv: Record<string, string | undefined>
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
__resetSystemTokenCacheForTests()
|
|
savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]))
|
|
for (const k of ENV_KEYS) delete process.env[k]
|
|
})
|
|
|
|
afterEach(() => {
|
|
for (const k of ENV_KEYS) {
|
|
if (savedEnv[k] === undefined) delete process.env[k]
|
|
else process.env[k] = savedEnv[k]
|
|
}
|
|
})
|
|
|
|
describe('system-auth config', () => {
|
|
it('defaults to mode off and mechanism mtls', () => {
|
|
expect(getSystemAuthMode()).toBe('off')
|
|
expect(getSystemAuthMechanism()).toBe('mtls')
|
|
})
|
|
|
|
it('parses valid modes and rejects garbage', () => {
|
|
process.env.SKATTEVERKET_SYSTEM_AUTH_MODE = 'shadow'
|
|
expect(getSystemAuthMode()).toBe('shadow')
|
|
process.env.SKATTEVERKET_SYSTEM_AUTH_MODE = 'ON'
|
|
expect(getSystemAuthMode()).toBe('on')
|
|
process.env.SKATTEVERKET_SYSTEM_AUTH_MODE = 'banana'
|
|
expect(getSystemAuthMode()).toBe('off')
|
|
})
|
|
|
|
it('is unconfigured in mode off and configured with stub + on', () => {
|
|
expect(isSystemAuthConfigured()).toBe(false)
|
|
process.env.SKATTEVERKET_SYSTEM_AUTH_MODE = 'on'
|
|
process.env.SKATTEVERKET_SYSTEM_AUTH_MECHANISM = 'stub'
|
|
expect(isSystemAuthConfigured()).toBe(true)
|
|
})
|
|
|
|
it('mtls requires token url + cert + key', () => {
|
|
process.env.SKATTEVERKET_SYSTEM_AUTH_MODE = 'on'
|
|
process.env.SKATTEVERKET_SYSTEM_AUTH_MECHANISM = 'mtls'
|
|
expect(isSystemAuthConfigured()).toBe(false)
|
|
process.env.SKATTEVERKET_SYSTEM_OAUTH_TOKEN_URL = 'https://oauth2.test.skatteverket.se/token'
|
|
process.env.SKATTEVERKET_SYSTEM_CERT_PEM_B64 = Buffer.from('-----BEGIN CERTIFICATE-----\nx\n-----END CERTIFICATE-----').toString('base64')
|
|
process.env.SKATTEVERKET_SYSTEM_KEY_PEM_B64 = Buffer.from('-----BEGIN PRIVATE KEY-----\nx\n-----END PRIVATE KEY-----').toString('base64')
|
|
expect(isSystemAuthConfigured()).toBe(true)
|
|
})
|
|
|
|
it('parses scopes from env with a sensible default', () => {
|
|
expect(getSystemScopes()).toEqual(['skattekonto', 'agd:lasa', 'momsdeklaration', 'obr'])
|
|
process.env.SKATTEVERKET_SYSTEM_SCOPES = 'a b'
|
|
expect(getSystemScopes()).toEqual(['a', 'b'])
|
|
})
|
|
|
|
it('returns null cert info when the PEM cannot be parsed', () => {
|
|
process.env.SKATTEVERKET_SYSTEM_CERT_PEM_B64 = Buffer.from('-----BEGIN CERTIFICATE-----\ngarbage\n-----END CERTIFICATE-----').toString('base64')
|
|
expect(getSystemCertInfo()).toBeNull()
|
|
})
|
|
})
|
|
|
|
describe('system token provider', () => {
|
|
beforeEach(() => {
|
|
process.env.SKATTEVERKET_SYSTEM_AUTH_MODE = 'on'
|
|
process.env.SKATTEVERKET_SYSTEM_AUTH_MECHANISM = 'stub'
|
|
})
|
|
|
|
it('throws SystemAuthUnavailableError when unconfigured', async () => {
|
|
process.env.SKATTEVERKET_SYSTEM_AUTH_MODE = 'off'
|
|
await expect(getSystemAccessToken()).rejects.toBeInstanceOf(SystemAuthUnavailableError)
|
|
expect(mockFetchToken).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('mints once and serves from cache until invalidated', async () => {
|
|
mockFetchToken.mockResolvedValue({ accessToken: 'tok-1', expiresAt: Date.now() + 3600_000 })
|
|
|
|
expect(await getSystemAccessToken()).toBe('tok-1')
|
|
expect(await getSystemAccessToken()).toBe('tok-1')
|
|
expect(mockFetchToken).toHaveBeenCalledTimes(1)
|
|
|
|
invalidateSystemToken()
|
|
mockFetchToken.mockResolvedValue({ accessToken: 'tok-2', expiresAt: Date.now() + 3600_000 })
|
|
expect(await getSystemAccessToken()).toBe('tok-2')
|
|
expect(mockFetchToken).toHaveBeenCalledTimes(2)
|
|
})
|
|
|
|
it('re-mints when the cached token is within the refresh margin', async () => {
|
|
// Expires in 60s: inside the 5-minute refresh-ahead margin.
|
|
mockFetchToken.mockResolvedValueOnce({ accessToken: 'short', expiresAt: Date.now() + 60_000 })
|
|
expect(await getSystemAccessToken()).toBe('short')
|
|
mockFetchToken.mockResolvedValueOnce({ accessToken: 'fresh', expiresAt: Date.now() + 3600_000 })
|
|
expect(await getSystemAccessToken()).toBe('fresh')
|
|
expect(mockFetchToken).toHaveBeenCalledTimes(2)
|
|
})
|
|
|
|
it('coalesces concurrent mints into one transport call', async () => {
|
|
let release: (v: { accessToken: string; expiresAt: number }) => void = () => {}
|
|
mockFetchToken.mockImplementationOnce(
|
|
() => new Promise((resolve) => { release = resolve })
|
|
)
|
|
|
|
const first = getSystemAccessToken()
|
|
const second = getSystemAccessToken()
|
|
release({ accessToken: 'tok-x', expiresAt: Date.now() + 3600_000 })
|
|
|
|
expect(await first).toBe('tok-x')
|
|
expect(await second).toBe('tok-x')
|
|
expect(mockFetchToken).toHaveBeenCalledTimes(1)
|
|
})
|
|
|
|
it('wraps transport failures in SystemAuthUnavailableError and does not cache them', async () => {
|
|
mockFetchToken.mockRejectedValueOnce(new Error('handshake failed'))
|
|
await expect(getSystemAccessToken()).rejects.toBeInstanceOf(SystemAuthUnavailableError)
|
|
|
|
mockFetchToken.mockResolvedValueOnce({ accessToken: 'recovered', expiresAt: Date.now() + 3600_000 })
|
|
expect(await getSystemAccessToken()).toBe('recovered')
|
|
})
|
|
})
|