Files
accounted/extensions/general/tic/__tests__/bankid-complete.test.ts
T
Jakob WennbergandClaude Opus 4.7 4131db2894 chore: MCP intent-tools, BankID enrichment table, multi-tenant fixes (#402)
* chore: MCP intent-tools, BankID enrichment table, multi-tenant fixes

MCP server gains six intent-shaped tools that collapse multi-call
agent flows into one: vat_close_check, query_journal, auto_match_period,
create_supplier_invoice_from_inbox, audit_package, year_end_readiness.
Tools wired into TOOL_SCOPE_MAP and OPERATION_RISK_TIERS as appropriate
(create_supplier_invoice_from_inbox at medium tier — reversible until
approve, but stages a leverantörsskuld).

BankID enrichment now persists to a dedicated bankid_enrichment table
keyed by user_id. extension_data has been company-scoped (NOT NULL
company_id) since the multi-tenant refactor, so every BankID signup has
silently been failing the enrichment upsert. Select-company picker reads
from the new table.

delete_last_voucher (BFNAR 2013:2) needs to clear
document_attachments.journal_entry_id before deleting the entry, but the
new document immutability trigger blocks that UPDATE. Added the same
gnubok.allow_delete transaction-scoped bypass pattern used by the
journal-entry/line/retention triggers. pg-real tests cover the happy
path, the unauthorized direct UPDATE, and the swap-to-different-entry
attempt under the bypass flag.

fiscal_periods.no_overlapping_fiscal_periods exclusion was scoped to
user_id from before multi-tenant — rebound to company_id so the same
user can have overlapping fiscal years across companies they own/are
member of.

Also adds scripts/seed-demo-account.ts for end-to-end demo seeding
(two companies, full FY2025, active FY2026 with mixed state).

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

* fix(pr-402): address review feedback

Migrations
- Drop 20260506140000_document_journal_entry_immutability_delete_bypass.sql:
  redundant with 20260506140000_document_journal_entry_immutability_bypass.sql
  that landed on main while this branch was open. Both share the same
  gnubok.allow_delete pattern; main's version is what the DB actually has.
- Rename 20260506150000_bankid_enrichment_table.sql →
  20260506160000_bankid_enrichment_table.sql to clear the timestamp clash
  with 20260506150000_protect_document_journal_link.sql on main (Supabase
  branch preview was failing on schema_migrations PK collision).

Tests
- Drop the swap-under-flag test from delete-last-voucher.pg.test.ts:
  main's bypass returns NEW unconditionally when gnubok.allow_delete='true',
  so the swap is permitted. Drop the duplicate happy-path test (already
  covered by 'clears journal_entry_id on attached documents and deletes
  the voucher'). Keep the unauthorized-direct-UPDATE test.
- Add bankid-enrichment.pg.test.ts covering the SELECT RLS policy:
  user reads own row, cannot read another user's row, INSERT denied for
  authenticated.

gnubok_query_journal
- amount_min/amount_max is applied post-fetch (PostgREST can't OR
  abs(debit) and abs(credit) cleanly), but PostgREST's count is computed
  pre-filter. Reporting that as total_lines mislead agents into
  paginating a tail that was already filtered out. When the amount
  filter is applied, anchor total_lines and truncated to the filtered
  set and surface db_matched_pre_amount_filter +
  amount_filter_applied_post_fetch separately.
- Escape `_` in the free-text LIKE filter so a search for "2_441"
  doesn't match "2X441".

VAT close check
- Reverse-charge blocker no longer fires on ruta 30 (seller-side
  domestic omvänd skattskyldighet) — the seller books no VAT, the buyer
  does, so missing ruta 48 is expected. Now scoped to ruta 31/32 (EU
  acquisition) where the buyer must book both calculated output (2615)
  and matching ingående moms (2645).
- High-value receipt threshold no longer reads journal_entries.total_amount
  (column doesn't exist; check silently never fired). Sums debits across
  the entry's lines, which equals the gross for ordinary purchase entries
  — comparing a gross figure against the BFL/ML 4 000 SEK threshold per
  ML 17 kap 26–28 §.

seed-demo-account.ts
- Require an explicit email argument; refuse to run with the previously
  hardcoded fallback that would silently target a real user. Ensure
  email is non-undefined for downstream typing.
- Type the supabase fiscal_periods insert result locally so tsc no longer
  reports 'fp implicitly any' from the loose untyped client.

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

* fix(test): adjust fiscal-period-start-day pg test for per-company overlap

The pg-real failure on PR #402 was a latent bug surfaced by this branch's
fiscal_periods exclusion constraint flip from user_id to company_id
(migration 20260506140100). The test was inserting periods that overlapped
seedCompany's default 2026-01-01..2026-12-31 period; the previous
constraint slipped past it because the test's INSERT didn't set user_id
(NULL escapes the WITH = match), so two same-company overlapping periods
silently coexisted.

Now that the constraint correctly fires per company, pick years that
don't overlap with the seeded 2026 period. The trigger's behavior under
test (allow mid-month start when no earlier period exists, allow
back-dated SIE imports, reject mid-month start when an earlier period
exists) is unchanged.

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

* fix(vat-close-check): correct reverse-charge/import blocker rutor

Rutor 30/31/32 are the buyer's calculated utgående moms on reverse-
charge purchases (domestic byggtjänster/electronics → 2614 → ruta 30;
EU goods → 2624 → ruta 31; EU services → 2634 → ruta 32). The buyer
must also book matching ingående moms (2647 inhemskt / 2645 utlandet
→ ruta 48). The previous fix removed ruta 30 on the basis that it was
seller-side; that's incorrect — domestic-RC sellers book no VAT at
all (they report only beskattningsunderlag on ruta 41), so 2614 only
sees buyer-side entries. Restore ruta 30.

Also extend the check to import rutor 60/61/62 (non-EU import VAT
declared via momsdeklaration since 2015 — 2615/2625/2635). Same
mechanic: importer books output VAT on these rutor and deducts the
input side via ruta 48. SaaS-from-AWS / OpenAI / Vercel companies hit
this path; without including 60/61/62 the blocker would silently miss
their misbookings.

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

* fix(mcp): expose ruta 60/61/62 (import VAT) on the local VatReportResult

The vat-close-check fix referenced vatReport.rutor.ruta60/61/62 but the
MCP server's local VatReportResult type only carries ruta 05-49. Build
broke on tsc.

Extend the MCP server's slim VAT report to also project import VAT —
2615 → ruta 60 (25%), 2625 → ruta 61 (12%), 2635 → ruta 62 (6%) — and
fold those into ruta 49 (att betala/återfå). Mirrors the BAS-to-Ruta
mapping in lib/reports/vat-declaration.ts. Output schema and required
list updated accordingly.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 16:41:36 +02:00

339 lines
13 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
vi.mock('../lib/bankid-client', () => ({
startBankIdAuth: vi.fn(),
pollBankIdSession: vi.fn(),
collectBankIdResult: vi.fn(),
cancelBankIdSession: vi.fn(),
requestEnrichment: vi.fn().mockResolvedValue({ status: 'failed', completedTypes: [] }),
fetchEnrichmentData: vi.fn(),
}))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: vi.fn(),
createClient: vi.fn(),
}))
import { collectBankIdResult, requestEnrichment, fetchEnrichmentData } from '../lib/bankid-client'
import { createServiceClient } from '@/lib/supabase/server'
import { ticExtension } from '../index'
const TEST_KEY = 'a'.repeat(64)
function findCompleteHandler() {
const route = ticExtension.apiRoutes!.find(
(r) => r.method === 'POST' && r.path === '/bankid/complete'
)
if (!route) throw new Error('POST /bankid/complete route not found in ticExtension.apiRoutes')
return route.handler
}
function makeSession(overrides: Partial<{ status: string; user: unknown }> = {}) {
return {
sessionId: 'test-session',
status: 'complete',
user: {
personalNumber: '199001011234',
givenName: 'Anna',
surname: 'Andersson',
name: 'Anna Andersson',
},
...overrides,
} as unknown as Awaited<ReturnType<typeof collectBankIdResult>>
}
type QueuedResult = { data?: unknown; error?: unknown }
function mockServiceClient(fromResults: QueuedResult[]) {
const queue = [...fromResults]
const chain = (): unknown => {
const result = queue.shift() ?? { data: null, error: null }
const handler: ProxyHandler<object> = {
get(_t, prop) {
if (prop === 'then') return (resolve: (v: unknown) => void) => resolve(result)
return () => chain2(result)
},
}
return new Proxy({}, handler)
}
const chain2 = (result: QueuedResult): unknown => {
const handler: ProxyHandler<object> = {
get(_t, prop) {
if (prop === 'then') return (resolve: (v: unknown) => void) => resolve(result)
return () => chain2(result)
},
}
return new Proxy({}, handler)
}
const admin = {
createUser: vi.fn().mockResolvedValue({ data: { user: { id: 'new-user-uuid' } }, error: null }),
updateUserById: vi.fn().mockResolvedValue({ data: {}, error: null }),
generateLink: vi.fn().mockResolvedValue({
data: { properties: { hashed_token: 'magic-token-hash' } },
error: null,
}),
getUserById: vi.fn().mockResolvedValue({
data: { user: { id: 'existing-user', email: 'existing@example.com' } },
}),
}
const client = {
from: vi.fn().mockImplementation(() => chain()),
auth: { admin },
}
vi.mocked(createServiceClient).mockReturnValue(client as unknown as ReturnType<typeof createServiceClient>)
return { admin, client }
}
beforeEach(() => {
vi.clearAllMocks()
vi.stubEnv('BANKID_ENCRYPTION_KEY', TEST_KEY)
})
afterEach(() => {
vi.unstubAllEnvs()
})
describe('POST /bankid/complete', () => {
describe('signup mode — account_exists regression (CWE-287)', () => {
it('returns 409 account_exists and performs NO side effects when email is already registered', async () => {
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
const { admin, client } = mockServiceClient([
{ data: null }, // bankid_identities pnr lookup → not linked
{ data: { id: 'victim-user-uuid' } }, // profiles email lookup → EXISTS
])
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
method: 'POST',
body: { sessionId: 'test-session', mode: 'signup', email: 'victim@example.com' },
})
const { status, body } = await parseJsonResponse<{ error?: string; data?: unknown }>(
await findCompleteHandler()(req)
)
expect(status).toBe(409)
expect(body.error).toBe('account_exists')
expect(body.data).toBeUndefined()
// Critical: none of the account-mutation or session-issuance calls ran.
expect(admin.createUser).not.toHaveBeenCalled()
expect(admin.updateUserById).not.toHaveBeenCalled()
expect(admin.generateLink).not.toHaveBeenCalled()
// No insert into bankid_identities. Only two from() calls should have happened
// (the pnr lookup and the profile lookup), neither of which is an insert.
const fromCalls = vi.mocked(client.from).mock.calls
expect(fromCalls.map((c) => c[0])).toEqual(['bankid_identities', 'profiles'])
})
})
describe('signup mode — happy path', () => {
it('creates a new user, marks bankid_linked, and returns the magic link tokenHash', async () => {
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
const { admin } = mockServiceClient([
{ data: null }, // pnr lookup → not linked
{ data: null }, // email lookup → not taken
{ error: null }, // bankid_identities insert OK
])
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; type?: string; isNewUser?: boolean }
}>(await findCompleteHandler()(req))
expect(status).toBe(200)
expect(body.data?.tokenHash).toBe('magic-token-hash')
expect(body.data?.type).toBe('magiclink')
expect(body.data?.isNewUser).toBe(true)
expect(admin.createUser).toHaveBeenCalledWith(
expect.objectContaining({ email: 'fresh@example.com', email_confirm: true })
)
expect(admin.updateUserById).toHaveBeenCalledWith(
'new-user-uuid',
expect.objectContaining({ app_metadata: { bankid_linked: true } })
)
})
})
describe('signup mode — pnr already linked', () => {
it('returns 409 already_linked before email lookup', async () => {
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
const { admin, client } = mockServiceClient([
{ data: { user_id: 'some-other-user' } }, // pnr lookup → LINKED
])
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
method: 'POST',
body: { sessionId: 'test-session', mode: 'signup', email: 'x@example.com' },
})
const { status, body } = await parseJsonResponse<{ error?: string }>(
await findCompleteHandler()(req)
)
expect(status).toBe(409)
expect(body.error).toBe('already_linked')
expect(admin.createUser).not.toHaveBeenCalled()
// Only the pnr lookup ran — no profiles query.
expect(vi.mocked(client.from).mock.calls.map((c) => c[0])).toEqual(['bankid_identities'])
})
})
describe('login mode', () => {
it('returns 404 no_account when the BankID pnr is not linked to any user', async () => {
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
const { admin } = mockServiceClient([
{ data: null }, // pnr lookup → not linked
])
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
method: 'POST',
body: { sessionId: 'test-session', mode: 'login' },
})
const { status, body } = await parseJsonResponse<{ error?: string }>(
await findCompleteHandler()(req)
)
expect(status).toBe(404)
expect(body.error).toBe('no_account')
expect(admin.generateLink).not.toHaveBeenCalled()
})
})
describe('enrichment — SPAR + CompanyRoles', () => {
it('requests both SPAR and CompanyRoles, fetches data, and persists only companyRoles (no PII) to bankid_enrichment', 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 bankid_enrichment 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 === 'bankid_enrichment') {
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 row must contain company_roles + enriched_at_utc 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 [Record<string, unknown>]
expect(persistedRow).toEqual({
user_id: expect.any(String),
company_roles: expect.any(Array),
enriched_at_utc: '2026-05-06T11:30:00Z',
})
expect(persistedRow).not.toHaveProperty('spar')
expect(persistedRow).not.toHaveProperty('personalNumber')
expect(persistedRow).not.toHaveProperty('name')
})
})
describe('input validation', () => {
it('returns 400 session_invalid when BankID session is not complete', async () => {
vi.mocked(collectBankIdResult).mockResolvedValue(
makeSession({ status: 'pending', user: undefined })
)
mockServiceClient([])
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
method: 'POST',
body: { sessionId: 'test-session', mode: 'signup', email: 'x@example.com' },
})
const { status, body } = await parseJsonResponse<{ error?: string }>(
await findCompleteHandler()(req)
)
expect(status).toBe(400)
expect(body.error).toBe('session_invalid')
})
it('returns 400 when email is missing in signup mode', async () => {
mockServiceClient([])
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
method: 'POST',
body: { sessionId: 'test-session', mode: 'signup' },
})
const { status } = await parseJsonResponse(await findCompleteHandler()(req))
expect(status).toBe(400)
// collectBankIdResult should never be called — validation happens first.
expect(collectBankIdResult).not.toHaveBeenCalled()
})
})
})