* 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>
136 lines
4.8 KiB
TypeScript
136 lines
4.8 KiB
TypeScript
import crypto from 'crypto'
|
|
|
|
/**
|
|
* Configuration for the system (organization certificate) auth flow.
|
|
*
|
|
* Unlike the personal BankID flow, the system flow authenticates Accounted
|
|
* itself with an organisationscertifikat via the OAuth2 Client Credentials
|
|
* Grant: one token for the whole tenant, no per-user session, no 65-minute
|
|
* refresh treadmill. Companies authorize it once by granting Accounted's org
|
|
* number a behorighet ("Juridiskt lasombud", "Momsdeklaration, ombud") in
|
|
* Skatteverket's Ombud och behorigheter e-service.
|
|
*
|
|
* The exact token-endpoint mechanics (mTLS vs private_key_jwt, scope names)
|
|
* are pending Skatteverket's CCG documentation: everything here is behind
|
|
* SKATTEVERKET_SYSTEM_AUTH_MODE (default 'off') and the transport seam in
|
|
* transport.ts, so the mechanism can be finalized without touching callers.
|
|
*
|
|
* Modes:
|
|
* off : system auth never used (default; behavior identical to before)
|
|
* shadow : crons log whether a verified grant exists but keep using user
|
|
* tokens (rollout confidence signal, zero behavior change)
|
|
* on : background reads prefer system credentials for companies with a
|
|
* verified grant; user tokens remain the fallback
|
|
*/
|
|
|
|
export type SystemAuthMode = 'off' | 'shadow' | 'on'
|
|
export type SystemAuthMechanism = 'mtls' | 'private_key_jwt' | 'stub'
|
|
|
|
export function getSystemAuthMode(): SystemAuthMode {
|
|
const raw = (process.env.SKATTEVERKET_SYSTEM_AUTH_MODE ?? 'off').toLowerCase()
|
|
return raw === 'on' || raw === 'shadow' ? raw : 'off'
|
|
}
|
|
|
|
export function getSystemAuthMechanism(): SystemAuthMechanism {
|
|
const raw = (process.env.SKATTEVERKET_SYSTEM_AUTH_MECHANISM ?? '').toLowerCase()
|
|
if (raw === 'mtls' || raw === 'private_key_jwt' || raw === 'stub') return raw
|
|
return 'mtls'
|
|
}
|
|
|
|
export function getSystemTokenUrl(): string | null {
|
|
return process.env.SKATTEVERKET_SYSTEM_OAUTH_TOKEN_URL ?? null
|
|
}
|
|
|
|
export function getSystemClientId(): string | null {
|
|
return process.env.SKATTEVERKET_SYSTEM_CLIENT_ID ?? null
|
|
}
|
|
|
|
/**
|
|
* Default scopes for the system token. `obr` is Ombudshantering (confirmed
|
|
* by Skatteverket 2026-09-01 when they added it to application id
|
|
* arcimtechnologyab_gnubok_1); the other names are pending SKV's org-flow
|
|
* docs. Override via env when they land.
|
|
*/
|
|
export function getSystemScopes(): string[] {
|
|
const raw = process.env.SKATTEVERKET_SYSTEM_SCOPES ?? 'skattekonto agd:lasa momsdeklaration obr'
|
|
return raw.split(/\s+/).filter(Boolean)
|
|
}
|
|
|
|
/** Accounted's own org number: what the end company grants behorighet to. */
|
|
export function getOmbudOrgNumber(): string | null {
|
|
return process.env.SKATTEVERKET_OMBUD_ORG_NUMBER ?? null
|
|
}
|
|
|
|
/**
|
|
* PEM material arrives base64-wrapped: env var UIs (Vercel included) mangle
|
|
* raw newlines, so the PEM is base64-encoded once more for transport.
|
|
*/
|
|
function decodePemEnv(name: string): string | null {
|
|
const raw = process.env[name]
|
|
if (!raw) return null
|
|
try {
|
|
const decoded = Buffer.from(raw, 'base64').toString('utf8')
|
|
return decoded.includes('-----BEGIN') ? decoded : null
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
export function getSystemCertPem(): string | null {
|
|
return decodePemEnv('SKATTEVERKET_SYSTEM_CERT_PEM_B64')
|
|
}
|
|
|
|
export function getSystemKeyPem(): string | null {
|
|
return decodePemEnv('SKATTEVERKET_SYSTEM_KEY_PEM_B64')
|
|
}
|
|
|
|
export function getSystemKeyPassphrase(): string | null {
|
|
return process.env.SKATTEVERKET_SYSTEM_KEY_PASSPHRASE ?? null
|
|
}
|
|
|
|
export function getSystemCaPem(): string | null {
|
|
return decodePemEnv('SKATTEVERKET_SYSTEM_CA_PEM_B64')
|
|
}
|
|
|
|
/**
|
|
* True when enough configuration exists for the system flow to mint tokens.
|
|
* The stub mechanism needs no certificate (tests and local development).
|
|
*/
|
|
export function isSystemAuthConfigured(): boolean {
|
|
if (getSystemAuthMode() === 'off') return false
|
|
if (getSystemAuthMechanism() === 'stub') return true
|
|
return Boolean(getSystemTokenUrl() && getSystemCertPem() && getSystemKeyPem())
|
|
}
|
|
|
|
export interface SystemCertInfo {
|
|
subject: string
|
|
notAfter: string
|
|
daysUntilExpiry: number
|
|
expiresSoon: boolean
|
|
}
|
|
|
|
const CERT_EXPIRY_WARNING_DAYS = 30
|
|
|
|
/**
|
|
* Parse the configured certificate for expiry surfacing in the status
|
|
* endpoint. Returns null when no certificate is configured or it cannot be
|
|
* parsed (a parse failure will surface at token minting anyway).
|
|
*/
|
|
export function getSystemCertInfo(): SystemCertInfo | null {
|
|
const pem = getSystemCertPem()
|
|
if (!pem) return null
|
|
try {
|
|
const cert = new crypto.X509Certificate(pem)
|
|
const notAfterMs = new Date(cert.validTo).getTime()
|
|
const daysUntilExpiry = Math.floor((notAfterMs - Date.now()) / (24 * 60 * 60 * 1000))
|
|
return {
|
|
subject: cert.subject,
|
|
notAfter: new Date(notAfterMs).toISOString(),
|
|
daysUntilExpiry,
|
|
expiresSoon: daysUntilExpiry <= CERT_EXPIRY_WARNING_DAYS,
|
|
}
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|