Check/salary bankid api (#892)
* fix(bankid): harden login/signup flow — polling, signup rollback, metadata merge, enrichment lookup - middleware: read BankID enrichment from the bankid_enrichment table (the extension_data path has been dead since the multi-tenant refactor), so company-less BankID users land on /select-company instead of the manual wizard - BankIdAuth: hard 6-min poll deadline; every failed poll counts toward the give-up limit; guard overlapping ticks so completion runs exactly once (a double /complete regenerated the magic link and invalidated the first, failing logins intermittently); retry clicks wait out the start cooldown instead of silently no-oping; Swedish messages for 429/unknown start errors - bankid/complete: all-or-nothing signup — delete the created user when the identity insert, app_metadata update, or magic-link generation fails, so a retry starts clean instead of hitting account_exists with an unusable account - bankid/unlink: read-merge-write app_metadata so has_password survives unlink (BankID-only users could otherwise strand themselves with no login method) - login: BankID "create account" CTA now links to /register instead of dismissing the notice; sv.json: fix missing å/ä/ö in settings_bankid strings Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: move secondary guides into docs/, delete dead root files Move DOCKER.md, SELF-HOSTING.md, WHITELABEL.md and extensions.md (renamed EXTENSIONS.md) into a new docs/ folder and update all path references (README, setup.sh, .dockerignore image rules, docker-publish workflow comment, _example-branding, lib/branding/service.ts). Delete two dead root files: customer.json (stray API-test payload) and findings.md (point-in-time swarm audit export, criticals already filed). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Signed-off-by: Emil <emilmattsson14@gmail.com> * fix(api): security & correctness hardening + withRouteContext MFA migration across API routes Audit of ~100 app/api routes. Highlights: Security - agent/conversations: list leaked colleagues' titles + message previews (company-scoped RLS, no user filter) -> user-scoped - calendar/feed PUT: raw body into .update() allowed feed_token fixation on a public unauthenticated URL -> strict schema, content toggles only - bokslutsdispositioner: unbounded schablonintaktRate could inflate the IL 30 kap 25% periodiseringsfond cap base -> bounded - agent profile/composer/onboarding: viewers could rewrite the agent profile while sibling /verify blocked them -> role-gated Correctness - account-totals / listAssets: unbounded queries silently truncated at 1000 rows (under-counted money; skipped assets at year-end depreciation) -> fetchAllRows with stable order (+3 more pagination fixes) - voucher-gaps: swallowed detect_voucher_gaps RPC errors (BFNAR gap view could show "no gaps" when the check never ran) -> surfaced - 5 phantom-success writes (OK on zero matched rows) fixed - assets K3 component-sum validated against stale acquisition_cost -> fixed - invite silent email-send failure -> response carries email_sent; deadlines/calendar cast-then-check JSON crashes -> Zod Convention - ~44 legacy routes converted to withRouteContext (MFA); added Zod validation, corrected status codes, console.* -> lib/logger Response shapes preserved for existing callers. ~110 new tests. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(bookkeeping): save a booking as a reusable template from Bokför direkt Add a "Spara som mall" action to the manual booking dialog so users can capture a kontering they just worked out as a booking template — right where they figured out how something should be booked. - derive amount-parameterised template lines from the concrete booking (settlement = the non-VAT leg nearest the total, 26xx = a VAT line with its rate snapped to the nearest standard rate, the rest = business ratios; line labels come from the loaded BAS chart) - extract the shared TemplateForm out of BookingTemplatesPanel so the booking dialog reuses the same editor, live preview and convertibility hints instead of duplicating them - save via the existing POST /api/settings/booking-templates endpoint Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(bokslut): render arsredovisning RR/BR at ÅRL post level — no kontonummer Bolagsverket rejected a user's filed årsredovisning with "Balansräkning och resultaträkning ska inte innehålla kontonummer": the PDF built every statement row as per-account "1930 Företagskonto" lines while the iXBRL filing path already aggregated to statutory posts, so the two artifacts diverged. The PDF statements now derive from the same K2 risbs mapping the iXBRL document uses (mapTrialBalancesToK2), via a new statement-rows.ts that emits post-level rows in uppställningsform order for both the K2 and K3 templates. Also fixed along the way: - Jämförelseår column (ÅRL 3:5 §) — previous-year trial balances now load and render; the old PDF had no comparatives at all. - mapping.warnings (unmapped accounts, RR ≠ 2099, obalans, reclass nudges) flow into ArsredovisningData.warnings so the wizard flags a non-fileable document before download. - Flerårsöversikt current/previous year overridden with the mapper's strict-3000–3799 Nettoomsattning, mirroring build-input's duplicate-fact rule, so the FB table ties to the RR. - FB eget kapital-table is post-level and drops obeskattade reserver (never eget kapital); K3 equity-changes statement uses real prior-year opening balances with derived utdelning/nyemission residuals that tie the roll-forward exactly to booked UB. - build-input dedupes warnings now that the PDF path runs the same mapping. Regression test asserts no RR/BR label ever contains a four-digit account number again. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(reports): diagnose untransferred prior-year results behind balance-sheet differens Prod incident (97 kr): a multi-year SIE migration lacked one year's omforing av arets resultat; the residual corrupted every later derived opening balance and Balansrakningen showed a bare "Differens: 97 kr" with no explanation. Continuity checking cannot catch this failure mode (prior-year UB and derived IB match per-account by construction) - the invariant that actually breaks is per-year P&L = 0 for all non-latest years. - lib/reports/imbalance-diagnosis.ts: shared detector (findUntransferredResults + buildImbalanceDiagnosis) - Balansrakning/Balansrapport attach imbalance_diagnosis when unbalanced, naming the exact culprit years; rendered in web views + PDF; MCP gnubok_get_balance_sheet inherits the field via spread - SIE import: parse-time warning when a completed year's vouchers leave a P&L residual, plus a post-import DB walk surfacing culprits as warnings and structured details.untransferredResults; the Arcim migration workspace previously dropped result.warnings entirely and now renders them - opening-balance/correct: pre-flight the company lock date and return 409 OB_COMPANY_LOCK_DATE (retryable: false, lock date interpolated in the client message) instead of the retryable 500 that invited blind retries; catch-path maps a raced trigger rejection to the same code Diagnosis runs only on unbalanced paths (zero cost when healthy) and never fails the report or the import. No migration, nothing persisted. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix: production error remediation — FX rates, deadlines, log levels, correction relink Batch of fixes for recurring Vercel runtime errors: - Riksbanken FX rates: persistent read-through cache (exchange_rates table), one retry honoring Retry-After on 429/5xx, bounded ingest concurrency, and an honest fallback — most recent cached observation or null, never a hardcoded rate silently booked into amount_sek. Unrated transactions stay repairable via refresh-exchange-rate. - Tax deadline regeneration inserts replacement rows before deleting the superseded set, so a failed insert no longer wipes a company's deadlines (the 23502 user_id regression did exactly that). Migration makes deadlines.user_id nullable for system-generated rows. - Route wrappers + errorResponse log 4xx outcomes at warn so only genuine 5xx reach Vercel's runtime-error clustering; client-supplied /api/log telemetry demoted to warn as well. - application/json documents (raw PSD2 responses archived per BFL) validate as parseable JSON with object/array root instead of always failing the magic-byte check. - correctEntry surfaces document-relink failures to callers, and the BFL document-immutability trigger now allows relinking underlag from a reversed entry to its correction (migration + pg test). - Middleware clears stale session cookies on /api requests too, using scope 'local' so cleanup doesn't re-trigger the failed token refresh. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(skatteverket): persist token health and stop retrying dead consents Terminal auth errors (SESSION_EXPIRED, REFRESH_EXHAUSTED, MISSING_SCOPE, TOKEN_CORRUPTED) mark the token row needs_reconsent with the error code and timestamp — SKV per-flow refresh tokens live 65 minutes, so once expired nothing recovers without a fresh BankID consent. The AGI kvittens and skattekonto sync crons skip flagged connections instead of failing every night, and the settings panel prompts for re-consent proactively. A successful reconnect resets the row to active. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(banking): allocate distinct BAS ledger slots for PSD2 mirror accounts A bank returning N same-currency accounts used to map them all onto the currency default (1930/1932/1933/1934), tripping the UNIQUE (company_id, ledger_account) constraint per-account — swallowed errors left accounts silently unmirrored. allocatePsd2LedgerAccount now hands out the currency default first, then free 1931–1959 sub-account slots, skipping slots held by any existing row. - Callback persists allocations to accounts_data so the picker pre-fills reality; reconnect reuses previously mirrored ledgers instead of re-deriving (a user remap to 1935 survives). - Selection save resolves effective ledgers up front and rejects duplicates or cross-connection conflicts with a 400 instead of silently skipping the mirror. - Bank error codes + psu_type are forwarded to the settings page for every OAuth error, keying the Handelsbanken corporate fullmakt guidance. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(agent): stage exact journal lines on categorization previews Categorization previews only carried debit/credit accounts, the GROSS amount, and separate VAT rows — read together that looks like an unbalanced 'gross on cost account + VAT debit' entry, and it misled both users and agents into rejecting correct proposals. The MCP preview and the pending-operation PATCH now materialize the exact lines the commit executor will post (net cost line, VAT line, gross bank line, SEK) via buildTransactionEntryLines, and PATCH re-derives them from the new mapping instead of spreading stale staged lines. ApprovalCard and /pending render the verifikat lines, falling back to the legacy summary only for operations staged before this fix. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(bookkeeping): prune unused imported accounts from the chart SIE imports routinely bring in hundreds of accounts that were never used and clutter the kontoplan. New account_usage_counts RPC (one grouped query instead of a count per account) backs GET /api/bookkeeping/accounts/usage, and POST /api/bookkeeping/accounts/prune deletes zero-usage accounts — dry-run first, then an explicit account list capped at 2000. Accounts with journal lines are skipped, never deleted. The chart manager shows a usage column and a prune dialog grouping custom accounts vs unused BAS-seeded ones. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(api): carry dimensions through v1 invoice and supplier-invoice surfaces Credit-note creation now copies default_dimensions and per-line dimensions from the original, so the reversing journal entry nets against the same dimension cells instead of dropping them. List/detail responses expose the dimension fields, and the OpenAPI spec snapshot follows. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * perf: batch serial Supabase round-trips on hot dashboard paths Every dashboard render pays the layout's query chain, so serialized awaits are direct wall-clock: the layout, chat conversation, invoice detail, supplier detail, select-company, and agent-onboarding pages now run their independent lookups in parallel batches, and getCompanyCapabilities folds its disabled-config read into the same round-trip. JournalEntryList hydrates the saved fiscal-year scope optimistically instead of serializing the first entries fetch behind the fiscal-periods request. The supplier detail page filters invoices server-side via a new supplier_id query param instead of fetching the whole company ledger, and the invoice editor (with its framer-motion dependency) lazy-loads so it stops shipping with the invoice list bundle. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(salary): one-click runs, payslip delivery, payments settings, run cockpit Salary P1 batch, driving the 20-click flow toward 3 clicks: - One-click 'Starta lönekörning': POST /api/salary/runs accepts an empty body and resolves defaults server-side — period follows the latest non-corrected run, payment date from the new salary_pay_day setting, series from the per-source-type map. The separate /salary/runs/new page is gone. - Run detail page rebuilt as a step-railed cockpit (progress rail, KPI cards, employee ledger, journal preview) on a deliberately wider canvas; components extracted to components/salary/run/. - Payslip delivery: tokenized public payslip pages (/payslip/[token], backed by salary_payslip_links) plus per-employee email send with PDF — employees need no account, and the middleware exempts the route from auth redirects. - Payments settings: salary pay day, default bank, and pain.001 vs Bankgirot Lön format with per-bank upload instructions and an LB sunset warning (banks retire LB during 2026). - AGI panel: full submission status flows (stale drafts, signing links, kvittens polling, error reports); tax payment panel with skattekonto shortcut and mark-as-paid. - Salary calendar bulk editing, employee benefits/tax-card polish, municipality tax-table lookup improvements. messages/sv+en also carry the strings for the account-prune, skatteverket-reconsent, and banking surfaces committed just before this. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * chore: adopt Next 16 proxy.ts convention + repo housekeeping - Rename middleware.ts to proxy.ts with the proxy() export (Next 16 renamed the middleware convention; behavior unchanged). - Exclude dev_docs/ from tsconfig so stray snippets in planning docs don't break the build type-check. - Ratchet antipatterns-baseline down (raw-route-auth 165 → 119) to lock in the withRouteContext migration from 5cfd2b76. - template-library uses roundOre() instead of inline rounding. - database.md: drop account_balances from the key-tables list. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(bookkeeping): robust service-role detection in correction document relink relink_documents_to_correction() keyed its service-role branch on auth.role(), which reads the singular request.jwt.claim.role GUC that PostgREST v10+ and the pg-real harness no longer populate. Genuine service-role callers (pending-ops executor / MCP approve) landed in the auth gate and could not relink underlag. Read the role from the request.jwt.claims JSON directly, mirroring the canonical link_voucher_rpcs_tenant_guard convention. Validated on staging. Also: harden the salary run page's error paths (res.json().catch) against non-JSON error bodies, and roll back the pg-real service-role case in finally so an aborted transaction cannot poison a pooled connection for the next test. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(documents): restore journal_entry_line_id link durability (BFL 7 kap) Migration 20260704103000 rewrote enforce_document_journal_entry_immutability to guard journal_entry_id but left journal_entry_line_id to the metadata trigger, which exempts draft-linked docs -- and the entry-level trigger only fired on UPDATE OF journal_entry_id, so a line-id-only UPDATE never invoked it at all. That let a set journal_entry_line_id be cleared to NULL, breaking the "link durable from first set" invariant (document-immutability.pg regression). Widen the trigger to fire on journal_entry_line_id too and guard it with the same uuid-durability rule as journal_entry_id (setting NULL -> uuid stays allowed; clearing/re-pointing a set value is blocked, status-independent). The correction-relink GUC path, which legitimately clears line_id when moving underlag to the posted correction, stays exempt. Validated on staging. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Signed-off-by: Emil <emilmattsson14@gmail.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
ec27228a8e
commit
2c2743eb79
@@ -17,7 +17,7 @@ Then:
|
||||
```
|
||||
5. Run `npm run setup:extensions && npm run dev`.
|
||||
|
||||
See `WHITELABEL.md` at the repo root for the full fork checklist (env vars, sync workflow, what NOT to change).
|
||||
See `docs/WHITELABEL.md` for the full fork checklist (env vars, sync workflow, what NOT to change).
|
||||
|
||||
## Why a separate extension instead of just env vars?
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { registerBrandingService } from '@/lib/branding/service'
|
||||
|
||||
// Register the whitelabel branding values immediately when this extension is loaded.
|
||||
// Edit the values below to match your brand. Any field omitted falls back to the
|
||||
// Accounted default (and to whatever you've set via env vars). See WHITELABEL.md.
|
||||
// Accounted default (and to whatever you've set via env vars). See docs/WHITELABEL.md.
|
||||
registerBrandingService({
|
||||
// appName: 'YourBrand',
|
||||
// appDescription: 'Bokföring & redovisning',
|
||||
|
||||
@@ -14,6 +14,6 @@
|
||||
"dataPattern": "core",
|
||||
"readsCoreTables": [],
|
||||
"description": "Copy-paste starter for a whitelabel fork. Disabled by default.",
|
||||
"longDescription": "Template extension for forks that want to rebrand the app. Copy this folder, rename it, edit index.ts with your brand values, drop your logo into assets/, and enable it in extensions.config.json. See WHITELABEL.md for the full fork checklist."
|
||||
"longDescription": "Template extension for forks that want to rebrand the app. Copy this folder, rename it, edit index.ts with your brand values, drop your logo into assets/, and enable it in extensions.config.json. See docs/WHITELABEL.md for the full fork checklist."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,17 @@ vi.mock('../lib/sync', () => ({
|
||||
syncAccountTransactions: vi.fn(),
|
||||
}))
|
||||
|
||||
// Mock the cash-accounts service (dynamically imported by the route) so the
|
||||
// mirror + allocation passes are deterministic and observable.
|
||||
const { mockUpsertFromPsd2, mockAllocate } = vi.hoisted(() => ({
|
||||
mockUpsertFromPsd2: vi.fn(),
|
||||
mockAllocate: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/cash-accounts/service', () => ({
|
||||
upsertFromPsd2: (...args: unknown[]) => mockUpsertFromPsd2(...args),
|
||||
allocatePsd2LedgerAccount: (...args: unknown[]) => mockAllocate(...args),
|
||||
}))
|
||||
|
||||
import { enableBankingExtension } from '../index'
|
||||
import { syncAccountTransactions } from '../lib/sync'
|
||||
import type { ExtensionContext } from '@/lib/extensions/types'
|
||||
@@ -39,6 +50,12 @@ interface SupabaseStub {
|
||||
updateErrorByCall?: Array<{ message: string } | null>
|
||||
/** BAS account numbers that exist in the company's chart_of_accounts (PR 2 ledger validation). */
|
||||
chartAccountNumbers?: string[]
|
||||
/** Existing cash_accounts rows for the company (ledger collision validation). */
|
||||
cashAccountRows?: Array<{
|
||||
external_uid: string | null
|
||||
bank_connection_id: string | null
|
||||
ledger_account: string
|
||||
}>
|
||||
/** Last update payload (may be overwritten by a follow-up metadata update). */
|
||||
capturedUpdate?: Record<string, unknown>
|
||||
/** All update payloads in order: first is the status flip, second the initial-sync metadata. */
|
||||
@@ -67,6 +84,14 @@ function buildSupabase(stub: SupabaseStub) {
|
||||
}),
|
||||
}
|
||||
}
|
||||
// Company-wide cash_accounts read for ledger collision validation:
|
||||
// select().eq() awaited as a thenable.
|
||||
if (table === 'cash_accounts') {
|
||||
return {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn(() => Promise.resolve({ data: stub.cashAccountRows ?? [], error: null })),
|
||||
}
|
||||
}
|
||||
return {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
@@ -121,9 +146,37 @@ function makeRequest(body: unknown): Request {
|
||||
})
|
||||
}
|
||||
|
||||
const ALLOCATOR_DEFAULTS: Record<string, string> = {
|
||||
SEK: '1930',
|
||||
EUR: '1932',
|
||||
USD: '1933',
|
||||
GBP: '1934',
|
||||
}
|
||||
|
||||
describe('PATCH /accounts (enable-banking)', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockUpsertFromPsd2.mockResolvedValue(undefined)
|
||||
// Allocator stand-in mirroring the real behavior: currency default first,
|
||||
// then the next free 1931–1959 slot (skipping other currency defaults).
|
||||
mockAllocate.mockImplementation(
|
||||
async (
|
||||
_supabase: unknown,
|
||||
_companyId: unknown,
|
||||
_userId: unknown,
|
||||
input: { currency: string; exclude?: ReadonlySet<string> },
|
||||
) => {
|
||||
const preferred = ALLOCATOR_DEFAULTS[input.currency.toUpperCase()] ?? '1930'
|
||||
const exclude = input.exclude ?? new Set<string>()
|
||||
if (!exclude.has(preferred)) return preferred
|
||||
const reserved = new Set(Object.values(ALLOCATOR_DEFAULTS))
|
||||
for (let n = 1931; n <= 1959; n++) {
|
||||
const candidate = String(n)
|
||||
if (!reserved.has(candidate) && !exclude.has(candidate)) return candidate
|
||||
}
|
||||
return null
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
@@ -759,7 +812,11 @@ describe('PATCH /accounts (enable-banking)', () => {
|
||||
expect(written.find(a => a.uid === 'acc-2')?.ledger_account).toBe('1932')
|
||||
})
|
||||
|
||||
it('clears ledger_account when account_mappings entry sets it to null', async () => {
|
||||
it('re-allocates ledger_account when account_mappings entry sets it to null', async () => {
|
||||
// Explicit null means "reset to auto". accounts_data must always mirror
|
||||
// the effective cash_accounts assignment, so the cleared account gets a
|
||||
// fresh allocation instead of an undefined that silently falls back to
|
||||
// 1930 at mirror time.
|
||||
mockedSync.mockResolvedValue({ imported: 0, duplicates: 0, errors: 0 })
|
||||
|
||||
const stub: SupabaseStub = {
|
||||
@@ -786,8 +843,137 @@ describe('PATCH /accounts (enable-banking)', () => {
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockAllocate).toHaveBeenCalledTimes(1)
|
||||
const written = stub.capturedUpdates?.[0]?.accounts_data as StoredAccount[]
|
||||
expect(written.find(a => a.uid === 'acc-1')?.ledger_account).toBeUndefined()
|
||||
expect(written.find(a => a.uid === 'acc-1')?.ledger_account).toBe('1930')
|
||||
})
|
||||
|
||||
it('returns 400 when two accounts map to the same ledger_account', async () => {
|
||||
const stub: SupabaseStub = {
|
||||
authUser: { id: 'user-1' },
|
||||
chartAccountNumbers: ['1930'],
|
||||
connectionRow: {
|
||||
id: 'conn-1',
|
||||
status: 'pending_selection',
|
||||
accounts_data: [
|
||||
{ uid: 'acc-1', currency: 'SEK', enabled: true },
|
||||
{ uid: 'acc-2', currency: 'SEK', enabled: true },
|
||||
],
|
||||
},
|
||||
}
|
||||
const supabase = buildSupabase(stub)
|
||||
const ctx = makeContext(supabase)
|
||||
|
||||
const res = await accountsRoute.handler(
|
||||
makeRequest({
|
||||
connection_id: 'conn-1',
|
||||
enabled_uids: ['acc-1', 'acc-2'],
|
||||
account_mappings: [
|
||||
{ uid: 'acc-1', ledger_account: '1930' },
|
||||
{ uid: 'acc-2', ledger_account: '1930' },
|
||||
],
|
||||
}),
|
||||
ctx
|
||||
)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error).toMatch(/samma konto/i)
|
||||
expect(body.duplicate_accounts).toEqual(['1930'])
|
||||
// Nothing written — the collision is rejected before any update.
|
||||
expect(stub.capturedUpdates).toBeUndefined()
|
||||
expect(mockUpsertFromPsd2).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 when a mapping targets a ledger held by another connection', async () => {
|
||||
const stub: SupabaseStub = {
|
||||
authUser: { id: 'user-1' },
|
||||
chartAccountNumbers: ['1935'],
|
||||
cashAccountRows: [
|
||||
{ external_uid: 'other-acc', bank_connection_id: 'conn-OTHER', ledger_account: '1935' },
|
||||
],
|
||||
connectionRow: {
|
||||
id: 'conn-1',
|
||||
status: 'pending_selection',
|
||||
accounts_data: [{ uid: 'acc-1', currency: 'SEK', enabled: true }],
|
||||
},
|
||||
}
|
||||
const supabase = buildSupabase(stub)
|
||||
const ctx = makeContext(supabase)
|
||||
|
||||
const res = await accountsRoute.handler(
|
||||
makeRequest({
|
||||
connection_id: 'conn-1',
|
||||
enabled_uids: ['acc-1'],
|
||||
account_mappings: [{ uid: 'acc-1', ledger_account: '1935' }],
|
||||
}),
|
||||
ctx
|
||||
)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error).toMatch(/annan bankanslutning/i)
|
||||
expect(body.conflicting_accounts).toEqual(['1935'])
|
||||
})
|
||||
|
||||
it('allocates distinct ledgers for legacy accounts with no mapping at all', async () => {
|
||||
mockedSync.mockResolvedValue({ imported: 0, duplicates: 0, errors: 0 })
|
||||
|
||||
const stub: SupabaseStub = {
|
||||
authUser: { id: 'user-1' },
|
||||
connectionRow: {
|
||||
id: 'conn-1',
|
||||
status: 'pending_selection',
|
||||
accounts_data: [
|
||||
{ uid: 'acc-1', currency: 'SEK', enabled: true },
|
||||
{ uid: 'acc-2', currency: 'SEK', enabled: true },
|
||||
],
|
||||
},
|
||||
}
|
||||
const supabase = buildSupabase(stub)
|
||||
const ctx = makeContext(supabase)
|
||||
|
||||
const res = await accountsRoute.handler(
|
||||
makeRequest({ connection_id: 'conn-1', enabled_uids: ['acc-1', 'acc-2'] }),
|
||||
ctx
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const written = stub.capturedUpdates?.[0]?.accounts_data as StoredAccount[]
|
||||
expect(written.find(a => a.uid === 'acc-1')?.ledger_account).toBe('1930')
|
||||
expect(written.find(a => a.uid === 'acc-2')?.ledger_account).toBe('1931')
|
||||
// The mirror received the same distinct assignments.
|
||||
const mirrorLedgers = mockUpsertFromPsd2.mock.calls.map(
|
||||
(c) => (c[2] as { ledger_account: string }).ledger_account,
|
||||
)
|
||||
expect(mirrorLedgers.sort()).toEqual(['1930', '1931'])
|
||||
})
|
||||
|
||||
it('preserves the mirrored cash_accounts ledger for accounts without a stored value', async () => {
|
||||
const stub: SupabaseStub = {
|
||||
authUser: { id: 'user-1' },
|
||||
cashAccountRows: [
|
||||
{ external_uid: 'acc-1', bank_connection_id: 'conn-1', ledger_account: '1940' },
|
||||
],
|
||||
connectionRow: {
|
||||
id: 'conn-1',
|
||||
status: 'active',
|
||||
accounts_data: [{ uid: 'acc-1', currency: 'SEK', enabled: true }],
|
||||
},
|
||||
}
|
||||
const supabase = buildSupabase(stub)
|
||||
const ctx = makeContext(supabase)
|
||||
|
||||
const res = await accountsRoute.handler(
|
||||
makeRequest({ connection_id: 'conn-1', enabled_uids: ['acc-1'] }),
|
||||
ctx
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
// No allocation — the existing mirrored assignment wins.
|
||||
expect(mockAllocate).not.toHaveBeenCalled()
|
||||
const written = stub.capturedUpdates?.[0]?.accounts_data as StoredAccount[]
|
||||
expect(written.find(a => a.uid === 'acc-1')?.ledger_account).toBe('1940')
|
||||
})
|
||||
|
||||
it('rejects account_mappings that is not an array', async () => {
|
||||
|
||||
@@ -109,12 +109,19 @@ export function AccountPickerDialog({
|
||||
setCustomDate('')
|
||||
|
||||
// Pre-populate ledger picks from existing StoredAccount values, falling
|
||||
// back to currency-based suggestions for accounts the user hasn't mapped yet.
|
||||
// back to currency-based suggestions for accounts the user hasn't mapped
|
||||
// yet. The currency default is suggested at most once — two SEK accounts
|
||||
// both pre-filled with 1930 would collide on the UNIQUE
|
||||
// (company_id, ledger_account) constraint at save; the second account is
|
||||
// left blank so the user picks a distinct slot.
|
||||
const initialLedger: Record<string, string> = {}
|
||||
const suggested = new Set<string>()
|
||||
for (const a of accounts) {
|
||||
const fromStored = a.ledger_account
|
||||
const fromDefault = CURRENCY_DEFAULTS[a.currency] ?? ''
|
||||
initialLedger[a.uid] = fromStored ?? fromDefault
|
||||
const pick = fromStored ?? (suggested.has(fromDefault) ? '' : fromDefault)
|
||||
if (pick) suggested.add(pick)
|
||||
initialLedger[a.uid] = pick
|
||||
}
|
||||
setLedgerByUid(initialLedger)
|
||||
}
|
||||
|
||||
@@ -817,6 +817,106 @@ export const enableBankingExtension: Extension = {
|
||||
}
|
||||
})
|
||||
|
||||
// Resolve the effective mirror ledger for every account up front and
|
||||
// reject collisions with a 400 — the mirror pass below writes into
|
||||
// cash_accounts, whose UNIQUE (company_id, ledger_account) constraint
|
||||
// would otherwise fail per-account and get swallowed, leaving accounts
|
||||
// silently unmirrored.
|
||||
const { allocatePsd2LedgerAccount, upsertFromPsd2 } = await import(
|
||||
'@/lib/cash-accounts/service'
|
||||
)
|
||||
|
||||
const { data: companyCashRows } = await supabase
|
||||
.from('cash_accounts')
|
||||
.select('external_uid, bank_connection_id, ledger_account')
|
||||
.eq('company_id', companyId)
|
||||
const cashRows = (companyCashRows ?? []) as Array<{
|
||||
external_uid: string | null
|
||||
bank_connection_id: string | null
|
||||
ledger_account: string
|
||||
}>
|
||||
const existingLedgerByUid = new Map(
|
||||
cashRows
|
||||
.filter(r => r.bank_connection_id === connection.id && r.external_uid)
|
||||
.map(r => [r.external_uid as string, r.ledger_account])
|
||||
)
|
||||
// Slots held by OTHER connections' PSD2 accounts — an explicit mapping
|
||||
// onto one of those would violate the unique constraint. Manual rows
|
||||
// are not foreign: upsertFromPsd2 promotes them in place.
|
||||
const foreignConnectedLedgers = new Set(
|
||||
cashRows
|
||||
.filter(r => r.bank_connection_id !== null && r.bank_connection_id !== connection.id)
|
||||
.map(r => r.ledger_account)
|
||||
)
|
||||
|
||||
const effectiveLedgerByUid = new Map<string, string>()
|
||||
const usedLedgers = new Set<string>()
|
||||
const duplicateLedgers = new Set<string>()
|
||||
const conflictingLedgers = new Set<string>()
|
||||
|
||||
// First pass: accounts with an explicit or previously mirrored ledger.
|
||||
for (const a of updatedAccounts) {
|
||||
const ledger = a.ledger_account ?? existingLedgerByUid.get(a.uid)
|
||||
if (!ledger) continue
|
||||
if (usedLedgers.has(ledger)) duplicateLedgers.add(ledger)
|
||||
if (foreignConnectedLedgers.has(ledger) && existingLedgerByUid.get(a.uid) !== ledger) {
|
||||
conflictingLedgers.add(ledger)
|
||||
}
|
||||
usedLedgers.add(ledger)
|
||||
effectiveLedgerByUid.set(a.uid, ledger)
|
||||
}
|
||||
|
||||
if (duplicateLedgers.size > 0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Flera bankkonton kan inte bokföras på samma konto. Välj olika bokföringskonton.',
|
||||
duplicate_accounts: [...duplicateLedgers],
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
if (conflictingLedgers.size > 0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Bokföringskontot används redan av ett bankkonto från en annan bankanslutning.',
|
||||
conflicting_accounts: [...conflictingLedgers],
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Second pass: allocate a free slot for accounts with no ledger at all
|
||||
// (legacy connections mirrored before allocation existed, or mappings
|
||||
// explicitly cleared). Allocation failure must never block selection
|
||||
// save — fall back to the pre-allocator behavior (1930) and let the
|
||||
// mirror pass surface any collision per-account, as before.
|
||||
for (const a of updatedAccounts) {
|
||||
if (effectiveLedgerByUid.has(a.uid)) continue
|
||||
let allocated: string | null = null
|
||||
try {
|
||||
allocated = await allocatePsd2LedgerAccount(supabase, companyId, user.id, {
|
||||
currency: a.currency,
|
||||
accountName: a.name,
|
||||
exclude: usedLedgers,
|
||||
})
|
||||
} catch (allocErr) {
|
||||
log.warn('[enable-banking] ledger allocation failed on selection save', {
|
||||
connectionId: connection.id,
|
||||
uid: a.uid,
|
||||
error: allocErr instanceof Error ? allocErr.message : String(allocErr),
|
||||
})
|
||||
}
|
||||
const ledger = allocated ?? '1930'
|
||||
usedLedgers.add(ledger)
|
||||
effectiveLedgerByUid.set(a.uid, ledger)
|
||||
}
|
||||
|
||||
// accounts_data mirrors the resolved assignment so the picker
|
||||
// pre-fills reality on the next open.
|
||||
for (const a of updatedAccounts) {
|
||||
a.ledger_account = effectiveLedgerByUid.get(a.uid)
|
||||
}
|
||||
|
||||
// State machine: only transition pending_selection → active. Once
|
||||
// active, the status field is omitted from the update so the same
|
||||
// endpoint can be reused to change account selection without
|
||||
@@ -847,7 +947,6 @@ export const enableBankingExtension: Extension = {
|
||||
// and reconciliation pick up the new enabled state + ledger mapping
|
||||
// without reading the JSONB column.
|
||||
{
|
||||
const { upsertFromPsd2 } = await import('@/lib/cash-accounts/service')
|
||||
for (const a of updatedAccounts) {
|
||||
try {
|
||||
await upsertFromPsd2(supabase, companyId, {
|
||||
|
||||
@@ -40,6 +40,12 @@ vi.mock('@/lib/bookkeeping/category-mapping', () => ({
|
||||
|
||||
vi.mock('@/lib/bookkeeping/transaction-entries', () => ({
|
||||
createTransactionJournalEntry: vi.fn().mockResolvedValue({ id: 'je-123' }),
|
||||
// Coherent with the mocked mapping above: 373.75 gross = 299 net + 74.75 moms.
|
||||
buildTransactionEntryLines: vi.fn().mockReturnValue([
|
||||
{ account_number: '2641', debit_amount: 74.75, credit_amount: 0, line_description: 'Ingående moms 25%' },
|
||||
{ account_number: '6110', debit_amount: 299, credit_amount: 0, line_description: 'Kostnad' },
|
||||
{ account_number: '1930', debit_amount: 0, credit_amount: 373.75, line_description: 'Bank' },
|
||||
]),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/events/bus', () => ({
|
||||
|
||||
@@ -10,7 +10,7 @@ import { createLogger } from '@/lib/logger'
|
||||
import { roundOre, sumOre } from '@/lib/money'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { buildMappingResultFromCategory } from '@/lib/bookkeeping/category-mapping'
|
||||
import { createTransactionJournalEntry } from '@/lib/bookkeeping/transaction-entries'
|
||||
import { buildTransactionEntryLines, createTransactionJournalEntry } from '@/lib/bookkeeping/transaction-entries'
|
||||
import { upsertCounterpartyTemplate, findCounterpartyTemplatesBatch, formatCounterpartyName } from '@/lib/bookkeeping/counterparty-templates'
|
||||
import { formatVoucherLabel } from '@/lib/transactions/link-journal-entry'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
@@ -537,6 +537,9 @@ async function categorizeTransactionCore(
|
||||
amount: number
|
||||
currency: string
|
||||
vat_lines?: Array<{ account_number: string; debit_amount: number; credit_amount: number; description: string }>
|
||||
// The exact journal lines the commit executor will post (net cost line,
|
||||
// VAT line, gross bank line) — always in SEK, matching the booked entry.
|
||||
lines?: Array<{ account_number: string; debit_amount: number; credit_amount: number; description: string }>
|
||||
message?: string
|
||||
transaction?: Transaction
|
||||
underlag?: {
|
||||
@@ -656,6 +659,12 @@ async function categorizeTransactionCore(
|
||||
|
||||
// Preview mode: return what would happen without executing
|
||||
if (!confirm) {
|
||||
// Materialize the exact lines the commit executor will post — including
|
||||
// the gross→net split on the cost line. Historically the preview only
|
||||
// carried { debit/credit account, gross amount, vat_lines }, which reads
|
||||
// as an unbalanced "gross on cost account + VAT debit" entry and misled
|
||||
// both users and agents into rejecting correct proposals.
|
||||
const entryLines = buildTransactionEntryLines(transaction as Transaction, mappingResult)
|
||||
return {
|
||||
preview: true,
|
||||
category,
|
||||
@@ -663,6 +672,12 @@ async function categorizeTransactionCore(
|
||||
credit_account: mappingResult.credit_account,
|
||||
amount: Math.abs(transaction.amount),
|
||||
currency: transaction.currency,
|
||||
lines: entryLines.map(l => ({
|
||||
account_number: l.account_number,
|
||||
debit_amount: l.debit_amount,
|
||||
credit_amount: l.credit_amount,
|
||||
description: l.line_description ?? '',
|
||||
})),
|
||||
vat_lines: mappingResult.vat_lines.map(v => ({
|
||||
account_number: v.account_number,
|
||||
debit_amount: v.debit_amount,
|
||||
@@ -2864,7 +2879,7 @@ export const tools: McpTool[] = [
|
||||
{
|
||||
name: 'gnubok_categorize_transaction',
|
||||
title: 'Categorize Bank Transaction',
|
||||
description: 'Categorize a bank transaction. Stages the journal entry; commit via gnubok_approve_pending_operation. vat_amount overrides computed moms; reverse_charge is rejected when the underlag shows the seller charged VAT. Optional dimensions tag the business lines.',
|
||||
description: 'Categorize a bank transaction. Stages the verifikat — cost line booked NET of moms, bank line gross; preview.lines shows the exact entry. Commit via gnubok_approve_pending_operation. vat_amount overrides computed moms; reverse_charge rejected when the underlag shows seller VAT.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
@@ -2984,6 +2999,11 @@ export const tools: McpTool[] = [
|
||||
credit_account: result.credit_account,
|
||||
amount: result.amount,
|
||||
currency: result.currency,
|
||||
// Exact journal lines the approval will post (net cost line, VAT
|
||||
// line, gross bank line, SEK). The summary fields above pair the
|
||||
// GROSS amount with the cost account — read alone they misled
|
||||
// users and agents into seeing an unbalanced entry.
|
||||
lines: result.lines ?? [],
|
||||
vat_lines: result.vat_lines || [],
|
||||
category: result.category,
|
||||
underlag: result.underlag ?? null,
|
||||
|
||||
@@ -156,3 +156,61 @@ describe('SkatteverketAuthError', () => {
|
||||
expect(b.code).toBe('RATE_LIMITED')
|
||||
})
|
||||
})
|
||||
|
||||
describe('refresh-token 404 classification', () => {
|
||||
// SKV's per-flow refresh tokens live 65 minutes, so daily crons always find
|
||||
// a dead token and get 404 id_not_found. That must surface as the
|
||||
// SESSION_EXPIRED SkatteverketAuthError (which cron quiet-buckets and the
|
||||
// UI reconnect flow understand), not as a raw Error that error-logs every
|
||||
// night. Unique userIds per test: the module-level refresh coalescing map
|
||||
// is keyed by userId.
|
||||
const expiredTokens = {
|
||||
access_token: 'stale',
|
||||
refresh_token: 'dead-refresh',
|
||||
expires_at: Date.now() - 60_000,
|
||||
refresh_count: 1,
|
||||
scope: 'momsdeklaration',
|
||||
}
|
||||
|
||||
it('classifies 404 id_not_found as SESSION_EXPIRED', async () => {
|
||||
const { getTokens } = await import('../lib/token-store')
|
||||
const { refreshAccessToken } = await import('../lib/oauth')
|
||||
// getValidToken reads once, refreshTokenForUser re-reads — queue both.
|
||||
vi.mocked(getTokens)
|
||||
.mockResolvedValueOnce(expiredTokens)
|
||||
.mockResolvedValueOnce(expiredTokens)
|
||||
vi.mocked(refreshAccessToken).mockRejectedValueOnce(
|
||||
new Error(
|
||||
'Skatteverket token refresh failed (404): {\n "error":"id_not_found",\n "error_description":"The refresh token is not found"\n}\n',
|
||||
),
|
||||
)
|
||||
|
||||
try {
|
||||
await skvRequest(fakeSupabase, 'user-404', 'GET', '/x')
|
||||
expect.fail('expected throw')
|
||||
} catch (e) {
|
||||
expect(e).toBeInstanceOf(SkatteverketAuthError)
|
||||
expect((e as SkatteverketAuthError).code).toBe('SESSION_EXPIRED')
|
||||
expect((e as SkatteverketAuthError).message).toMatch(/Sessionen har gått ut/)
|
||||
}
|
||||
})
|
||||
|
||||
it('re-throws other refresh failures untouched', async () => {
|
||||
const { getTokens } = await import('../lib/token-store')
|
||||
const { refreshAccessToken } = await import('../lib/oauth')
|
||||
vi.mocked(getTokens)
|
||||
.mockResolvedValueOnce(expiredTokens)
|
||||
.mockResolvedValueOnce(expiredTokens)
|
||||
vi.mocked(refreshAccessToken).mockRejectedValueOnce(
|
||||
new Error('Skatteverket token refresh failed (500): upstream unavailable'),
|
||||
)
|
||||
|
||||
try {
|
||||
await skvRequest(fakeSupabase, 'user-500', 'GET', '/x')
|
||||
expect.fail('expected throw')
|
||||
} catch (e) {
|
||||
expect(e).not.toBeInstanceOf(SkatteverketAuthError)
|
||||
expect((e as Error).message).toMatch(/500/)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
} from '@/lib/salary/agi/kontrollera-schemas'
|
||||
import { TimeoutError } from '@/lib/http/fetch-with-timeout'
|
||||
import { buildAuthorizeUrl, exchangeCodeForTokens, generatePkcePair } from './lib/oauth'
|
||||
import { storeTokens, getTokens, deleteTokens } from './lib/token-store'
|
||||
import { storeTokens, getTokens, deleteTokens, getTokenHealth } from './lib/token-store'
|
||||
import { skvRequest, SkatteverketAuthError, getSkatteverketEnvironment } from './lib/api-client'
|
||||
import { writeSkatteverketAudit } from './lib/audit'
|
||||
import { skvAuthCodeToStructured } from './lib/error-map'
|
||||
@@ -403,10 +403,17 @@ export const skatteverketExtension: Extension = {
|
||||
const expired = tokens.expires_at < Date.now()
|
||||
const canRefresh = tokens.refresh_token !== null && tokens.refresh_count < 10
|
||||
|
||||
// Persisted health, written by the crons when they hit a terminal
|
||||
// auth state. Lets the settings panel prompt for re-consent
|
||||
// proactively instead of only after a live failure.
|
||||
const health = await getTokenHealth(ctx.supabase, ctx.userId)
|
||||
|
||||
return NextResponse.json({
|
||||
connected: true,
|
||||
expired,
|
||||
canRefresh,
|
||||
needsReconsent: health?.status === 'needs_reconsent',
|
||||
lastErrorCode: health?.last_error_code ?? null,
|
||||
scope: tokens.scope,
|
||||
expiresAt: new Date(tokens.expires_at).toISOString(),
|
||||
environment,
|
||||
|
||||
@@ -164,7 +164,24 @@ async function refreshTokenForUser(
|
||||
)
|
||||
}
|
||||
|
||||
const refreshed = await refreshAccessToken(tokens.refresh_token, tokens.refresh_count)
|
||||
let refreshed
|
||||
try {
|
||||
refreshed = await refreshAccessToken(tokens.refresh_token, tokens.refresh_count)
|
||||
} catch (err) {
|
||||
// SKV's `per`-flow refresh tokens live 65 minutes. Any daily cron (or a
|
||||
// user returning the next day) therefore always finds a dead token and
|
||||
// gets 404 id_not_found back — that's ordinary session expiry, not a
|
||||
// runtime error. Classify it so the crons' quiet buckets and the UI's
|
||||
// reconnect flow catch it instead of a raw Error escaping to the logs.
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
if (/\b404\b/.test(message) && /id_not_found|refresh token is not found/i.test(message)) {
|
||||
throw new SkatteverketAuthError(
|
||||
'Sessionen har gått ut. Logga in med BankID igen.',
|
||||
'SESSION_EXPIRED'
|
||||
)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
const updatedTokens: SkatteverketTokens = {
|
||||
...refreshed,
|
||||
scope: tokens.scope,
|
||||
@@ -256,8 +273,10 @@ export async function skvRequest(
|
||||
// Diagnostic detail (headers, body) belongs in server-side logs only,
|
||||
// not in user-facing error messages. The structured logger redacts
|
||||
// sensitive keys and we further cap body length and strip Bearer tokens
|
||||
// so the diagnostic is bounded.
|
||||
log.error('401 from Skatteverket API', {
|
||||
// so the diagnostic is bounded. warn, not error: auth rejections are
|
||||
// expected states (expired sessions, stale scopes) and the thrown
|
||||
// SkatteverketAuthError below carries the signal to the caller.
|
||||
log.warn('401 from Skatteverket API', {
|
||||
url,
|
||||
statusCode: 401,
|
||||
body: safeBodyForLog(text),
|
||||
@@ -368,7 +387,7 @@ export async function skvRequest(
|
||||
const text = await response.text().catch(() => '')
|
||||
// Same diagnostic-vs-user-message split as the 401 path: log the body
|
||||
// server-side, surface only the actionable Swedish guidance.
|
||||
log.error('403 from Skatteverket API', {
|
||||
log.warn('403 from Skatteverket API', {
|
||||
url,
|
||||
statusCode: 403,
|
||||
body: safeBodyForLog(text),
|
||||
|
||||
@@ -181,3 +181,67 @@ export async function deleteTokens(
|
||||
.delete()
|
||||
.eq('user_id', userId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Terminal auth-error codes: the stored token can never recover on its own —
|
||||
* only a fresh BankID consent fixes it. SESSION_EXPIRED qualifies because
|
||||
* SKV's `per`-flow refresh tokens live 65 minutes: once expired there is
|
||||
* nothing left to refresh with.
|
||||
*/
|
||||
export const RECONSENT_ERROR_CODES = [
|
||||
'SESSION_EXPIRED',
|
||||
'REFRESH_EXHAUSTED',
|
||||
'MISSING_SCOPE',
|
||||
'TOKEN_CORRUPTED',
|
||||
] as const
|
||||
|
||||
/**
|
||||
* Flag a connection as needing re-consent so crons stop retrying it every
|
||||
* night and the UI can prompt proactively. storeTokens() (delete + insert)
|
||||
* resets the row to status 'active' on the next successful consent.
|
||||
* Best-effort: health bookkeeping must never mask the original auth error.
|
||||
*/
|
||||
export async function markNeedsReconsent(
|
||||
_supabase: SupabaseClient,
|
||||
userId: string,
|
||||
errorCode: string,
|
||||
): Promise<void> {
|
||||
const db = getServiceClient()
|
||||
const { error } = await db
|
||||
.from('skatteverket_tokens')
|
||||
.update({
|
||||
status: 'needs_reconsent',
|
||||
last_error_code: errorCode,
|
||||
last_error_at: new Date().toISOString(),
|
||||
})
|
||||
.eq('user_id', userId)
|
||||
if (error) {
|
||||
log.warn('failed to mark token row needs_reconsent', {
|
||||
userId,
|
||||
errorCode,
|
||||
error: error.message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the persisted connection health for a user's token row.
|
||||
* Returns null when no row exists (not connected).
|
||||
*/
|
||||
export async function getTokenHealth(
|
||||
_supabase: SupabaseClient,
|
||||
userId: string,
|
||||
): Promise<{ status: string; last_error_code: string | null; last_error_at: string | null } | null> {
|
||||
const db = getServiceClient()
|
||||
const { data, error } = await db
|
||||
.from('skatteverket_tokens')
|
||||
.select('status, last_error_code, last_error_at')
|
||||
.eq('user_id', userId)
|
||||
.maybeSingle()
|
||||
if (error || !data) return null
|
||||
return {
|
||||
status: (data.status as string | null) ?? 'active',
|
||||
last_error_code: (data.last_error_code as string | null) ?? null,
|
||||
last_error_at: (data.last_error_at as string | null) ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,6 +71,7 @@ function mockServiceClient(fromResults: QueuedResult[]) {
|
||||
const admin = {
|
||||
createUser: vi.fn().mockResolvedValue({ data: { user: { id: 'new-user-uuid' } }, error: null }),
|
||||
updateUserById: vi.fn().mockResolvedValue({ data: {}, error: null }),
|
||||
deleteUser: vi.fn().mockResolvedValue({ data: {}, error: null }),
|
||||
generateLink: vi.fn().mockResolvedValue({
|
||||
data: { properties: { hashed_token: 'magic-token-hash' } },
|
||||
error: null,
|
||||
@@ -189,6 +190,104 @@ describe('POST /bankid/complete', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('signup mode — rollback on partial failure', () => {
|
||||
// A half-created account strands the user: retrying signup hits
|
||||
// account_exists/already_linked, but the account only has a random
|
||||
// password they never saw. Every failure after createUser must delete
|
||||
// the created user so a retry starts clean.
|
||||
|
||||
it('deletes the created user when the bankid_identities insert fails', async () => {
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
const { admin } = mockServiceClient([
|
||||
{ data: null }, // pnr lookup → not linked
|
||||
{ data: null }, // email lookup → not taken
|
||||
{ error: { message: 'insert boom', code: 'XX000' } }, // identity insert FAILS
|
||||
])
|
||||
|
||||
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<{ error?: string }>(
|
||||
await findCompleteHandler()(req)
|
||||
)
|
||||
|
||||
expect(status).toBe(500)
|
||||
expect(body.error).toBe('internal_error')
|
||||
expect(admin.createUser).toHaveBeenCalled()
|
||||
expect(admin.deleteUser).toHaveBeenCalledWith('new-user-uuid')
|
||||
expect(admin.generateLink).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('deletes the created user when generateLink fails', async () => {
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
const { admin } = mockServiceClient([
|
||||
{ data: null }, // pnr lookup → not linked
|
||||
{ data: null }, // email lookup → not taken
|
||||
{ error: null }, // identity insert OK
|
||||
])
|
||||
admin.generateLink.mockResolvedValueOnce({
|
||||
data: null,
|
||||
error: { message: 'link boom' },
|
||||
} as never)
|
||||
|
||||
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<{ error?: string }>(
|
||||
await findCompleteHandler()(req)
|
||||
)
|
||||
|
||||
expect(status).toBe(500)
|
||||
expect(body.error).toBe('internal_error')
|
||||
expect(admin.deleteUser).toHaveBeenCalledWith('new-user-uuid')
|
||||
})
|
||||
|
||||
it('deletes the created user when the app_metadata update fails', async () => {
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
const { admin } = mockServiceClient([
|
||||
{ data: null }, // pnr lookup → not linked
|
||||
{ data: null }, // email lookup → not taken
|
||||
])
|
||||
admin.updateUserById.mockResolvedValueOnce({
|
||||
data: null,
|
||||
error: { message: 'meta boom', code: 'XX000' },
|
||||
} as never)
|
||||
|
||||
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<{ error?: string }>(
|
||||
await findCompleteHandler()(req)
|
||||
)
|
||||
|
||||
expect(status).toBe(500)
|
||||
expect(body.error).toBe('internal_error')
|
||||
expect(admin.deleteUser).toHaveBeenCalledWith('new-user-uuid')
|
||||
expect(admin.generateLink).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does NOT delete anything on the happy path', async () => {
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
const { admin } = mockServiceClient([
|
||||
{ data: null },
|
||||
{ data: null },
|
||||
{ error: null },
|
||||
])
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session', mode: 'signup', email: 'fresh@example.com' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await findCompleteHandler()(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(admin.deleteUser).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('login mode', () => {
|
||||
it('returns 404 no_account when the BankID pnr is not linked to any user', async () => {
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
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 } from '../lib/bankid-client'
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { ticExtension } from '../index'
|
||||
import type { ExtensionContext } from '@/lib/extensions/types'
|
||||
|
||||
const TEST_KEY = 'a'.repeat(64)
|
||||
|
||||
function findHandler(method: string, path: string) {
|
||||
const route = ticExtension.apiRoutes!.find((r) => r.method === method && r.path === path)
|
||||
if (!route) throw new Error(`${method} ${path} route not found in ticExtension.apiRoutes`)
|
||||
return route.handler
|
||||
}
|
||||
|
||||
type QueuedResult = { data?: unknown; error?: unknown }
|
||||
|
||||
/** Minimal chainable service-client mock (same pattern as bankid-complete.test.ts). */
|
||||
function mockServiceClient(fromResults: QueuedResult[], appMetadata: Record<string, unknown>) {
|
||||
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 = {
|
||||
updateUserById: vi.fn().mockResolvedValue({ data: {}, error: null }),
|
||||
getUserById: vi.fn().mockResolvedValue({
|
||||
data: { user: { id: 'user-1', app_metadata: appMetadata } },
|
||||
}),
|
||||
}
|
||||
|
||||
const client = {
|
||||
from: vi.fn().mockImplementation(() => chain()),
|
||||
auth: { admin },
|
||||
}
|
||||
|
||||
vi.mocked(createServiceClient).mockReturnValue(
|
||||
client as unknown as ReturnType<typeof createServiceClient>
|
||||
)
|
||||
|
||||
return { admin, client }
|
||||
}
|
||||
|
||||
const ctx = { userId: 'user-1' } as unknown as ExtensionContext
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.stubEnv('BANKID_ENCRYPTION_KEY', TEST_KEY)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
describe('POST /bankid/unlink', () => {
|
||||
it('returns 401 without an authenticated context', async () => {
|
||||
mockServiceClient([], {})
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/unlink', { method: 'POST' })
|
||||
const { status } = await parseJsonResponse(await findHandler('POST', '/bankid/unlink')(req))
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('merges app_metadata instead of replacing it — has_password must survive unlink', async () => {
|
||||
// A BankID-only user: has_password false. Wiping it would make
|
||||
// userHasPassword() infer TRUE (bankid_linked false ⇒ password assumed),
|
||||
// hiding the set-password escape hatch from a user with no login method.
|
||||
const { admin } = mockServiceClient(
|
||||
[{ error: null }], // bankid_identities delete OK
|
||||
{ has_password: false, bankid_linked: true, provider: 'email' }
|
||||
)
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/unlink', { method: 'POST' })
|
||||
const { status, body } = await parseJsonResponse<{ data?: { unlinked?: boolean } }>(
|
||||
await findHandler('POST', '/bankid/unlink')(req, ctx)
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.unlinked).toBe(true)
|
||||
expect(admin.updateUserById).toHaveBeenCalledWith('user-1', {
|
||||
app_metadata: { has_password: false, provider: 'email', bankid_linked: false },
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 500 when the identity delete fails and does not touch app_metadata', async () => {
|
||||
const { admin } = mockServiceClient(
|
||||
[{ error: { message: 'delete boom', code: 'XX000' } }],
|
||||
{ has_password: false, bankid_linked: true }
|
||||
)
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/unlink', { method: 'POST' })
|
||||
const { status } = await parseJsonResponse(
|
||||
await findHandler('POST', '/bankid/unlink')(req, ctx)
|
||||
)
|
||||
|
||||
expect(status).toBe(500)
|
||||
expect(admin.updateUserById).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /bankid/link', () => {
|
||||
function makeSession() {
|
||||
return {
|
||||
sessionId: 'test-session',
|
||||
status: 'complete',
|
||||
user: {
|
||||
personalNumber: '199001011234',
|
||||
givenName: 'Anna',
|
||||
surname: 'Andersson',
|
||||
name: 'Anna Andersson',
|
||||
},
|
||||
} as unknown as Awaited<ReturnType<typeof collectBankIdResult>>
|
||||
}
|
||||
|
||||
it('merges app_metadata so an existing has_password: true survives linking', async () => {
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
const { admin } = mockServiceClient(
|
||||
[
|
||||
{ data: null }, // pnr lookup → not linked anywhere
|
||||
{ error: null }, // bankid_identities insert OK
|
||||
],
|
||||
{ has_password: true }
|
||||
)
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/link', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data?: { linked?: boolean } }>(
|
||||
await findHandler('POST', '/bankid/link')(req, ctx)
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.linked).toBe(true)
|
||||
expect(admin.updateUserById).toHaveBeenCalledWith('user-1', {
|
||||
app_metadata: { has_password: true, bankid_linked: true },
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 409 already_linked when the personnummer belongs to another user', async () => {
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
const { admin } = mockServiceClient(
|
||||
[{ data: { user_id: 'someone-else' } }],
|
||||
{ has_password: true }
|
||||
)
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/link', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await findHandler('POST', '/bankid/link')(req, ctx)
|
||||
)
|
||||
|
||||
expect(status).toBe(409)
|
||||
expect(body.error).toBe('already_linked')
|
||||
expect(admin.updateUserById).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -878,11 +878,12 @@ export const ticExtension: Extension = {
|
||||
)
|
||||
}
|
||||
|
||||
// Verify BankID session is complete
|
||||
// Verify BankID session is complete. The message surfaces directly
|
||||
// in the register-page toast, so it must be Swedish.
|
||||
const session = await collectBankIdResult(sessionId)
|
||||
if (session.status !== 'complete' || !session.user) {
|
||||
return NextResponse.json(
|
||||
{ error: 'session_invalid', message: 'BankID session is not complete' },
|
||||
{ error: 'session_invalid', message: 'BankID-sessionen är inte längre giltig. Försök igen.' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
@@ -984,21 +985,46 @@ export const ticExtension: Extension = {
|
||||
if (createError || !newUser?.user) {
|
||||
log.error('createUser failed', { email: trimmedEmail, status: createError?.status, code: createError?.code, message: createError?.message })
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to create account', message: createError?.message },
|
||||
{ error: 'internal_error', message: 'Kunde inte skapa kontot. Försök igen.' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
const userId = newUser.user.id
|
||||
|
||||
// All-or-nothing signup: if any step after createUser fails, delete
|
||||
// the just-created user so the same email/BankID can retry cleanly.
|
||||
// Leaving the half-created account behind strands the user — a retry
|
||||
// hits account_exists/already_linked, but the account only has a
|
||||
// random password they never saw, so "log in instead" requires a
|
||||
// password reset. bankid_identities cascades on user delete.
|
||||
const rollbackSignup = async (step: string) => {
|
||||
const { error: deleteError } = await supabase.auth.admin.deleteUser(userId)
|
||||
if (deleteError) {
|
||||
log.error(`signup rollback after failed ${step} could not delete user — orphaned account`, {
|
||||
userId,
|
||||
message: deleteError.message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Mark user as BankID-linked (skips TOTP MFA) and record that they
|
||||
// do not have a password yet: the BankID signup gave them a random
|
||||
// server-side password they will never see. This flag gates MFA
|
||||
// enrollment (see lib/auth/has-password.ts).
|
||||
await supabase.auth.admin.updateUserById(userId, {
|
||||
const { error: metaError } = await supabase.auth.admin.updateUserById(userId, {
|
||||
app_metadata: { bankid_linked: true, has_password: false },
|
||||
})
|
||||
|
||||
if (metaError) {
|
||||
log.error('signup app_metadata update failed', { message: metaError.message, code: metaError.code })
|
||||
await rollbackSignup('app_metadata update')
|
||||
return NextResponse.json(
|
||||
{ error: 'internal_error', message: 'Kunde inte skapa kontot. Försök igen.' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
// Store BankID identity
|
||||
const { error: insertError } = await supabase
|
||||
.from('bankid_identities')
|
||||
@@ -1012,8 +1038,9 @@ export const ticExtension: Extension = {
|
||||
|
||||
if (insertError) {
|
||||
log.error('insert bankid_identities failed', { message: insertError.message, code: insertError.code })
|
||||
await rollbackSignup('bankid_identities insert')
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to link BankID identity' },
|
||||
{ error: 'internal_error', message: 'Kunde inte skapa kontot. Försök igen.' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
@@ -1026,8 +1053,9 @@ export const ticExtension: Extension = {
|
||||
|
||||
if (linkError || !link?.properties?.hashed_token) {
|
||||
log.error('generateLink failed for signup', { message: linkError?.message, code: linkError?.code })
|
||||
await rollbackSignup('generateLink')
|
||||
return NextResponse.json(
|
||||
{ error: 'Account created but failed to create session' },
|
||||
{ error: 'internal_error', message: 'Kunde inte skapa kontot. Försök igen.' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
@@ -1201,9 +1229,17 @@ export const ticExtension: Extension = {
|
||||
return NextResponse.json({ error: 'Failed to unlink BankID' }, { status: 500 })
|
||||
}
|
||||
|
||||
// Clear app_metadata.bankid_linked so MFA enforcement resumes
|
||||
// Clear app_metadata.bankid_linked so MFA enforcement resumes.
|
||||
// Read-merge-write: updateUserById REPLACES app_metadata wholesale
|
||||
// (same rationale as /bankid/link above). Writing only
|
||||
// { bankid_linked: false } would wipe has_password — a BankID-only
|
||||
// user (has_password: false) would then be inferred as HAVING a
|
||||
// password (lib/auth/has-password.ts) and could strand themselves
|
||||
// with no working login method.
|
||||
const { data: priorUser } = await supabase.auth.admin.getUserById(ctx.userId)
|
||||
const priorMeta = priorUser?.user?.app_metadata ?? {}
|
||||
await supabase.auth.admin.updateUserById(ctx.userId, {
|
||||
app_metadata: { bankid_linked: false },
|
||||
app_metadata: { ...priorMeta, bankid_linked: false },
|
||||
})
|
||||
|
||||
return NextResponse.json({ data: { unlinked: true } })
|
||||
|
||||
Reference in New Issue
Block a user