chore: post-bankid redirect, recapt feedback, TIC SPAR enrichment (#400)

* chore: post-bankid redirect, recapt feedback, TIC SPAR enrichment

- BankID login + register now redirect to /select-company so the picker
  shows freshly enriched CompanyRoles from the current session.
- New lib/support/submit-feedback util prefers window.recapt feedback
  widget when present, falls back to /api/support/contact. SupportLink
  uses it and hides itself in sandbox companies via new isSandbox flag
  on CompanyContext (+ useCompanyOptional hook).
- TIC enrichment re-requests SPAR alongside CompanyRoles now that both
  types are enabled on the tenant; enrichment shape logged PII-free
  (booleans/counts only). Tests cover the SPAR+CompanyRoles path.
- Skatteverket api-client: 15s AbortSignal timeout on outbound requests.
- Swedish compliance review CI: bump REVIEW_MODEL to claude-opus-4-7.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: keep compliance review model on sonnet-4-6

Reverts the opus-4-7 bump from the previous commit per request.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(tic): don't persist SPAR PII to extension_data

The previous commit started requesting SPAR alongside CompanyRoles and
wrote the full enrichment payload (incl. personnummer, full name, home
address, birth date, gender) verbatim to extension_data.value — a plain
JSON column. Personnummer is already hashed + encrypted in
bankid_identities, so the extension_data row was an unencrypted PII
duplicate exposed to anyone with read access to the table.

No consumer (middleware, /select-company, createCompanyFromTicRole)
reads any SPAR field today; they only read companyRoles. Persist a
sanitized blob of { companyRoles, enrichedAtUtc } instead. SPAR is
still requested from TIC (and its shape logged PII-free) so enrichment
completes; if address pre-fill ships later, those fields should be
encrypted before storage.

Also drop the dead `null` branch from SubmitFeedbackResult.channel —
every code path returns 'recapt' or 'email'.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-05-06 13:43:06 +02:00
committed by GitHub
co-authored by Claude Opus 4.7
parent 5725c25bf1
commit b9a2ce522b
11 changed files with 321 additions and 53 deletions
@@ -172,6 +172,7 @@ export async function skvRequest(
method,
headers,
body: serializedBody,
signal: AbortSignal.timeout(15_000),
})
// Handle Skatteverket-specific auth/throttle errors uniformly so callers
@@ -15,7 +15,7 @@ vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(),
}))
import { collectBankIdResult } from '../lib/bankid-client'
import { collectBankIdResult, requestEnrichment, fetchEnrichmentData } from '../lib/bankid-client'
import { createServiceClient } from '@/lib/supabase/server'
import { ticExtension } from '../index'
@@ -208,6 +208,102 @@ describe('POST /bankid/complete', () => {
})
})
describe('enrichment — SPAR + CompanyRoles', () => {
it('requests both SPAR and CompanyRoles, fetches data, and persists only companyRoles (no PII) to extension_data', async () => {
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
vi.mocked(requestEnrichment).mockResolvedValueOnce({
enrichmentId: 'enr-1',
sessionId: 'test-session',
status: 'Completed',
requestedTypes: ['SPAR', 'CompanyRoles'],
completedTypes: ['SPAR', 'CompanyRoles'],
secureUrl: '/api/v1/enrichment/data/abc',
secureUrlExpiresAtUtc: '2026-05-06T12:00:00Z',
})
vi.mocked(fetchEnrichmentData).mockResolvedValueOnce({
personalNumber: '199001011234',
name: 'Anna Andersson',
enrichedAtUtc: '2026-05-06T11:30:00Z',
spar: {
Person_IdNummer: '199001011234',
Person_PersonIdTyp: 'PERSONNR',
Skydd_Sekretessmarkering: false,
Skydd_SkyddadFolkbokforing: false,
Namn_Fornamn: 'Anna',
Namn_Efternamn: 'Andersson',
PersonDetaljer_Kon: 'K',
PersonDetaljer_Fodelsedatum: '1990-01-01',
Folkbokforingsadress_SvenskAdress_Utdelningsadress1: 'Storgatan 1',
Folkbokforingsadress_SvenskAdress_PostNr: '11122',
Folkbokforingsadress_SvenskAdress_Postort: 'Stockholm',
},
companyRoles: [
{
companyId: 12345,
companyRegistrationNumber: '5566778899',
legalName: 'Exempel AB',
legalEntityType: 'AB',
positionTypes: ['LED'],
positionDescriptions: ['Styrelseledamot'],
positionStart: '2020-01-15',
positionEnd: null,
companyStatus: 'Aktivt',
},
],
})
const { client } = mockServiceClient([
{ data: null }, // pnr lookup → not linked
{ data: null }, // email lookup → not taken
{ error: null }, // bankid_identities insert OK
])
// Intercept the extension_data upsert so we can assert the persisted shape
// contains no SPAR / personnummer / name. Other tables fall through to the
// queued chain.
const upsertSpy = vi.fn().mockResolvedValue({ error: null })
const origFrom = client.from as unknown as ReturnType<typeof vi.fn>
const queuedFrom = origFrom.getMockImplementation() as (table: string) => unknown
origFrom.mockImplementation((table: string) => {
if (table === 'extension_data') {
return { upsert: upsertSpy }
}
return queuedFrom(table)
})
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
method: 'POST',
body: { sessionId: 'test-session', mode: 'signup', email: 'fresh@example.com' },
})
const { status, body } = await parseJsonResponse<{
data?: { tokenHash?: string; isNewUser?: boolean }
}>(await findCompleteHandler()(req))
expect(status).toBe(200)
expect(body.data?.isNewUser).toBe(true)
expect(vi.mocked(requestEnrichment)).toHaveBeenCalledWith(
'test-session',
['SPAR', 'CompanyRoles']
)
expect(vi.mocked(fetchEnrichmentData)).toHaveBeenCalledWith('/api/v1/enrichment/data/abc')
// Persisted blob must contain companyRoles + enrichedAtUtc only.
// SPAR (personnummer / name / address / birth date) must NOT be stored,
// even when TIC returns it — those fields live in bankid_identities (encrypted).
expect(upsertSpy).toHaveBeenCalledTimes(1)
const [persistedRow] = upsertSpy.mock.calls[0] as [
{ key: string; value: Record<string, unknown> },
]
expect(persistedRow.key).toBe('bankid_enrichment')
expect(persistedRow.value).toEqual({
companyRoles: expect.any(Array),
enrichedAtUtc: '2026-05-06T11:30:00Z',
})
expect(persistedRow.value).not.toHaveProperty('spar')
expect(persistedRow.value).not.toHaveProperty('personalNumber')
expect(persistedRow.value).not.toHaveProperty('name')
})
})
describe('input validation', () => {
it('returns 400 session_invalid when BankID session is not complete', async () => {
vi.mocked(collectBankIdResult).mockResolvedValue(
+34 -22
View File
@@ -30,14 +30,20 @@ import crypto from 'crypto'
const log = createLogger('tic/bankid')
/**
* Request CompanyRoles enrichment for a completed BankID session and cache
* the result in `extension_data` so /select-company can pre-fill the picker.
* Request SPAR + CompanyRoles enrichment for a completed BankID session and
* cache the CompanyRoles slice in `extension_data` for the
* /select-company picker.
*
* SPAR (personnummer, address, name, birth date) is requested so TIC will
* complete the enrichment, but is intentionally NOT persisted: personnummer
* is already hashed + encrypted in `bankid_identities`, names live there too,
* and no UI currently consumes the address. Storing the SPAR blob in
* `extension_data.value` (a plain JSON column) would expose national-ID-level
* PII to anyone with read access. If/when address pre-fill is built, encrypt
* the relevant fields the same way `encryptPersonalNumber` does for pnr.
*
* Non-blocking: any failure is logged and swallowed — BankID auth must still
* succeed even if enrichment is down.
*
* Only types currently enabled on the TIC tenant are requested — see the
* block comment inside the function. If Address (formerly SPAR) is enabled
* later, add it here to restore address pre-fill in the manual wizard.
*/
async function fetchAndStoreEnrichment(
sessionId: string,
@@ -45,19 +51,15 @@ async function fetchAndStoreEnrichment(
supabase: SupabaseClient,
): Promise<void> {
try {
// IMPORTANT: only request types that are actually enabled on the TIC
// tenant. Requesting an unknown/disabled type (e.g. 'SPAR', which TIC
// has renamed to 'Address' and which our tenant currently has off)
// makes TIC reject the whole enrichment with
// `error: 'Session not completed'` — a misleading error that took a
// round of debugging to trace. Verified via GET /api/v1/enrichment/types:
// { type: 'CompanyRoles', enabled: true } ← we want this
// { type: 'Address', enabled: false } ← formerly SPAR, off
// Both 'SPAR' and 'CompanyRoles' are enabled on our TIC tenant as of
// 2026-05-06 (TIC ticket re. enrichment). Verify with:
// curl -H "X-Api-Key: $KEY" https://id.tic.io/api/v1/enrichment/types
//
// If 'Address' gets enabled later, add it here (and wire up the
// address pre-fill in WelcomeOnboarding and createCompanyFromTicRole
// — both already look for a `.spar` field that TIC may have renamed).
const enrichment = await requestEnrichment(sessionId, ['CompanyRoles'])
// If a requested type is disabled on the tenant, TIC rejects the WHOLE
// enrichment with body field `error: 'Session not completed'` (HTTP 200,
// not a real HTTP error). The message is misleading — it does NOT mean
// the BankID session is incomplete. The hint mapping below catches it.
const enrichment = await requestEnrichment(sessionId, ['SPAR', 'CompanyRoles'])
log.info('enrichment request returned', {
status: enrichment.status,
requestedTypes: enrichment.requestedTypes,
@@ -102,10 +104,10 @@ async function fetchAndStoreEnrichment(
const enrichmentData = await fetchEnrichmentData(enrichment.secureUrl)
// Log a PII-free snapshot so we can debug the role filter in production.
// Raw personnummer/names are deliberately omitted. `spar`/`address` not
// logged — we don't request those types currently (see block comment
// on requestEnrichment above), so they'd always be absent.
// Raw personnummer / names / address values are deliberately omitted —
// only flat booleans and counts.
const firstRole = enrichmentData.companyRoles?.[0]
const spar = enrichmentData.spar
log.info('enrichment data shape', {
companyCount: enrichmentData.companyRoles?.length ?? 0,
firstRoleStatuses: firstRole
@@ -116,15 +118,25 @@ async function fetchAndStoreEnrichment(
legalEntityType: firstRole.legalEntityType,
}
: null,
hasSpar: !!spar,
sparHasAddress: !!spar?.Folkbokforingsadress_SvenskAdress_Utdelningsadress1,
sparHasProtection: !!(spar?.Skydd_Sekretessmarkering || spar?.Skydd_SkyddadFolkbokforing),
})
// Persist only what consumers actually read. See block comment on
// fetchAndStoreEnrichment for why SPAR + personnummer + name are excluded.
const persistedValue = {
companyRoles: enrichmentData.companyRoles ?? [],
enrichedAtUtc: enrichmentData.enrichedAtUtc,
}
await supabase
.from('extension_data')
.upsert({
user_id: userId,
extension_id: 'tic',
key: 'bankid_enrichment',
value: enrichmentData,
value: persistedValue,
}, { onConflict: 'user_id,extension_id,key' })
} catch (enrichError) {
log.warn('enrichment failed (non-blocking)', enrichError)