Files
accounted/extensions/general/skatteverket/__tests__/deeplink-route.test.ts
T
MattssonandClaude Fable 5.1 8b09b06e14 feat(skatteverket): ombudsregister grant verification, honest session expiry, daily ombud sync (#2130)
* 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>
2026-09-01 23:42:23 +02:00

196 lines
8.0 KiB
TypeScript

/**
* POST /system-connection/deeplink: gating (capability, role, system-auth
* mode), org-number derivation server-side, the opt-in row it records, and
* the OmbudApiError -> 502 mapping.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
const mockRequireCapability = vi.fn()
vi.mock('@/lib/entitlements/has-capability', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>
return { ...actual, requireCapability: (...a: unknown[]) => mockRequireCapability(...a) }
})
const mockCreateDeepLink = vi.fn()
vi.mock('../lib/ombud-client', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>
return { ...actual, createUtseOmbudDeepLink: (...a: unknown[]) => mockCreateDeepLink(...a) }
})
const mockRecordProbeResult = vi.fn()
const mockContested = vi.fn(async (_orgNumber: string) => false)
vi.mock('../lib/connection-store', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>
return {
...actual,
recordProbeResult: (...a: unknown[]) => mockRecordProbeResult(...a),
isOrgNumberContested: (orgNumber: string) => mockContested(orgNumber),
}
})
const mockWriteAudit = vi.fn()
vi.mock('../lib/audit', () => ({ writeSkatteverketAudit: (...a: unknown[]) => mockWriteAudit(...a) }))
import { skatteverketExtension } from '../index'
import { OmbudApiError } from '../lib/ombud-client'
import type { ExtensionContext } from '@/lib/extensions/types'
const ENV_KEYS = ['SKATTEVERKET_SYSTEM_AUTH_MODE', 'SKATTEVERKET_SYSTEM_AUTH_MECHANISM']
let savedEnv: Record<string, string | undefined>
function findRoute() {
const route = skatteverketExtension.apiRoutes?.find(
(r) => r.method === 'POST' && r.path === '/system-connection/deeplink'
)
if (!route) throw new Error('deeplink route not registered')
return route
}
/** Supabase stub: company_members role lookup, then company_settings org number. */
function makeContext(opts: { role?: string; orgNumber?: string | null } = {}): ExtensionContext {
const role = opts.role ?? 'owner'
const orgNumber = opts.orgNumber === undefined ? '556000-0000' : opts.orgNumber
const from = vi.fn((table: string) => {
const chain: Record<string, unknown> = {}
const self = () => chain
for (const m of ['select', 'eq', 'order', 'limit']) chain[m] = vi.fn(self)
if (table === 'company_members') {
chain.single = vi.fn(async () => ({ data: { role }, error: null }))
chain.maybeSingle = vi.fn(async () => ({ data: { role }, error: null }))
} else if (table === 'company_settings') {
chain.single = vi.fn(async () => ({
data: orgNumber ? { org_number: orgNumber, entity_type: 'aktiebolag' } : { org_number: null, entity_type: 'aktiebolag' },
error: null,
}))
chain.maybeSingle = chain.single
} else {
chain.single = vi.fn(async () => ({ data: null, error: null }))
chain.maybeSingle = chain.single
}
return chain
})
return {
userId: 'user-1',
companyId: 'company-1',
extensionId: 'skatteverket',
requestId: 'req_test',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
supabase: { from } as any,
emit: vi.fn().mockResolvedValue(undefined),
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), child: vi.fn() },
settings: {
get: vi.fn().mockResolvedValue(null),
set: vi.fn().mockResolvedValue(undefined),
clear: vi.fn().mockResolvedValue(undefined),
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any
}
const request = () =>
new Request('http://localhost/api/extensions/ext/skatteverket/system-connection/deeplink', { method: 'POST' })
beforeEach(() => {
vi.clearAllMocks()
savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]))
process.env.SKATTEVERKET_SYSTEM_AUTH_MODE = 'on'
process.env.SKATTEVERKET_SYSTEM_AUTH_MECHANISM = 'stub'
mockRequireCapability.mockResolvedValue(null)
mockRecordProbeResult.mockResolvedValue({ id: 'conn-1', status: 'pending' })
mockContested.mockResolvedValue(false)
mockWriteAudit.mockResolvedValue(undefined)
mockCreateDeepLink.mockResolvedValue({
djuplank: 'https://sso.skatteverket.se/ombud?x=1',
roller: { lasombud: 'JLO', moms_ombud: 'MOMS' },
expiresOn: '2026-09-22',
})
vi.spyOn(console, 'warn').mockImplementation(() => {})
})
afterEach(() => {
for (const k of ENV_KEYS) {
if (savedEnv[k] === undefined) delete process.env[k]
else process.env[k] = savedEnv[k]
}
})
describe('POST /system-connection/deeplink', () => {
it('500 without an extension context', async () => {
const res = await findRoute().handler(request())
expect(res.status).toBe(500)
})
it('refuses when the capability gate blocks', async () => {
const { NextResponse } = await import('next/server')
mockRequireCapability.mockResolvedValue(NextResponse.json({ error: 'capability_blocked' }, { status: 403 }))
const res = await findRoute().handler(request(), makeContext())
expect(res.status).toBe(403)
expect(mockCreateDeepLink).not.toHaveBeenCalled()
})
it('refuses a viewer (AGI write role required)', async () => {
const res = await findRoute().handler(request(), makeContext({ role: 'viewer' }))
expect(res.status).toBe(403)
expect(mockCreateDeepLink).not.toHaveBeenCalled()
})
it('503 while system auth is off', async () => {
process.env.SKATTEVERKET_SYSTEM_AUTH_MODE = 'off'
const res = await findRoute().handler(request(), makeContext())
expect(res.status).toBe(503)
})
it('400 when the company has no org number', async () => {
const res = await findRoute().handler(request(), makeContext({ orgNumber: null }))
expect(res.status).toBe(400)
expect(mockCreateDeepLink).not.toHaveBeenCalled()
})
it('mints the link for the company\'s own 12-digit org number, records the opt-in row, audits', async () => {
const res = await findRoute().handler(request(), makeContext())
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
data: {
djuplank: 'https://sso.skatteverket.se/ombud?x=1',
roller: { lasombud: 'JLO', moms_ombud: 'MOMS' },
expires_on: '2026-09-22',
},
})
expect(mockCreateDeepLink).toHaveBeenCalledWith('165560000000', ['lasombud', 'moms_ombud'])
expect(mockRecordProbeResult).toHaveBeenCalledWith(
expect.objectContaining({ companyId: 'company-1', orgNumber: '165560000000', createdBy: 'user-1', error: null })
)
// No grant state is asserted by minting a link.
expect(mockRecordProbeResult.mock.calls[0][0]).not.toHaveProperty('lasombud')
expect(mockWriteAudit).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ endpoint: 'system-connection/deeplink', agRegistreradId: '165560000000', outcome: 'ok' })
)
})
it('409 ORG_NUMBER_CONTESTED when another live company claims the same org number: no link, no row', async () => {
mockContested.mockResolvedValue(true)
const res = await findRoute().handler(request(), makeContext())
expect(res.status).toBe(409)
expect(await res.json()).toMatchObject({ code: 'ORG_NUMBER_CONTESTED' })
expect(mockContested).toHaveBeenCalledWith('165560000000')
expect(mockCreateDeepLink).not.toHaveBeenCalled()
expect(mockRecordProbeResult).not.toHaveBeenCalled()
})
it('500 when the opt-in row cannot be stored: the link is not handed out', async () => {
mockRecordProbeResult.mockResolvedValue(null)
const res = await findRoute().handler(request(), makeContext())
expect(res.status).toBe(500)
expect(mockWriteAudit).not.toHaveBeenCalled()
})
it('502 with the error code when the register refuses or the role codes are unresolved', async () => {
mockCreateDeepLink.mockRejectedValue(new OmbudApiError('Rollkod saknas', 'OBR_ROLE_UNRESOLVED'))
const res = await findRoute().handler(request(), makeContext())
expect(res.status).toBe(502)
expect(await res.json()).toMatchObject({ code: 'OBR_ROLE_UNRESOLVED' })
expect(mockRecordProbeResult).not.toHaveBeenCalled()
})
})