feat: implement skattekonto drift detection and alerting (#525)
* feat: implement skattekonto drift detection and alerting - Add skattekonto drift computation logic to compare Skatteverket's saldo with GL 1630 sum. - Implement alerting mechanism for significant drift changes, with throttling to prevent alert spamming. - Introduce database functions to sum GL 1630 entries and list unbooked skattekonto rows. feat: create own account transfer detection - Develop logic to detect transfers between a company's own cash accounts based on counterparty IBAN. - Implement tests to validate detection logic under various scenarios, including matching and non-matching IBANs. feat: establish cash accounts as a first-class entity - Create cash_accounts table to manage routable cash accounts, replacing ad-hoc JSONB structures. - Implement functions for listing, upserting, and managing cash accounts, including primary account designation. feat: enhance GL line reconciliation functionality - Modify get_unlinked_1930_lines RPC to accept any account number for reconciliation, improving flexibility for different currencies. - Update related functions to ensure compatibility with the new cash_accounts structure. feat: capture counterparty IBAN in transactions - Add counterparty_iban column to transactions table to facilitate intra-account transfer detection. - Create index for efficient lookups based on counterparty IBAN. * feat: Enhance cash account handling and reconciliation processes - Updated reconciliation routes to enforce cash account validation for all account numbers, including '1930'. - Improved error handling for unknown cash accounts in reconciliation status and unmatched entries routes. - Changed CashAccountSelector to use sessionStorage instead of localStorage for better data privacy. - Fixed mapping for employer payroll taxes to route to the correct account (2730 instead of 2731). - Added safety checks for company IDs in the guessCounterAccount function to prevent injection vulnerabilities. - Introduced atomic RPC for setting primary cash accounts to avoid intermediate states during updates. - Seeded default cash accounts for new companies to ensure reconciliation routes are accessible from day one. - Updated email notifications for drift detection to avoid exposing sensitive financial data. - Enhanced bank reconciliation logic to handle multi-currency transactions correctly. - Renamed and updated tests to reflect changes in the underlying RPCs and ensure accurate coverage. - Migrated existing cash account rules to correct mappings in compliance with Swedish accounting standards.
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { listForCompany } from '@/lib/cash-accounts/service'
|
||||
|
||||
/**
|
||||
* GET /api/cash-accounts
|
||||
*
|
||||
* Returns the active company's cash accounts (cash_accounts table). Used by the
|
||||
* reconciliation CashAccountSelector (Item 5) and any other surface that needs
|
||||
* the canonical list of routable cash accounts. UI panels that just display PSD2
|
||||
* connection state may still read bank_connections.accounts_data until that
|
||||
* column is dropped in a follow-up migration.
|
||||
*
|
||||
* Query params:
|
||||
* - enabled_only=true → only accounts with enabled=true (default returns all)
|
||||
*/
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const companyId = await getActiveCompanyId(supabase, user.id)
|
||||
if (!companyId) {
|
||||
return NextResponse.json({ error: 'No company context' }, { status: 400 })
|
||||
}
|
||||
|
||||
const url = new URL(request.url)
|
||||
const enabledOnly = url.searchParams.get('enabled_only') === 'true'
|
||||
|
||||
const accounts = await listForCompany(supabase, companyId, { enabledOnly })
|
||||
return NextResponse.json({ data: accounts })
|
||||
}
|
||||
@@ -3,6 +3,21 @@ import { NextResponse } from 'next/server'
|
||||
import { createSession, type AccountInfo } from '@/extensions/general/enable-banking/lib/api-client'
|
||||
import type { StoredAccount } from '@/extensions/general/enable-banking/types'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import { upsertFromPsd2 } from '@/lib/cash-accounts/service'
|
||||
|
||||
// Suggested BAS account per currency. Mirrors the AccountPickerDialog defaults
|
||||
// (SEK→1930, EUR→1932, USD→1933, GBP→1934). The user can re-map in the picker
|
||||
// after this callback redirects them.
|
||||
const CURRENCY_DEFAULTS: Record<string, string> = {
|
||||
SEK: '1930',
|
||||
EUR: '1932',
|
||||
USD: '1933',
|
||||
GBP: '1934',
|
||||
}
|
||||
|
||||
function defaultLedgerForCurrency(currency: string): string {
|
||||
return CURRENCY_DEFAULTS[currency.toUpperCase()] ?? '1930'
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/extensions/enable-banking/callback
|
||||
@@ -170,6 +185,56 @@ export async function GET(request: Request) {
|
||||
throw new Error(`Failed to update connection: ${updateError.message}`)
|
||||
}
|
||||
|
||||
// Mirror each PSD2 account into cash_accounts so routing decisions read from
|
||||
// the canonical entity table. The user picks a ledger_account in the
|
||||
// AccountPickerDialog after this redirect; until then we route SEK→1930,
|
||||
// EUR→1932, USD→1933, GBP→1934 by convention.
|
||||
for (const account of accountsMetadata) {
|
||||
const targetLedger = defaultLedgerForCurrency(account.currency)
|
||||
try {
|
||||
await upsertFromPsd2(supabase, updatedConnection.company_id, {
|
||||
bank_connection_id: updatedConnection.id,
|
||||
external_uid: account.uid,
|
||||
currency: account.currency,
|
||||
ledger_account: targetLedger,
|
||||
iban: account.iban ?? null,
|
||||
name: account.name ?? null,
|
||||
enabled: account.enabled ?? true,
|
||||
})
|
||||
} catch (cashErr) {
|
||||
const reason = cashErr instanceof Error ? cashErr.message : String(cashErr)
|
||||
console.error('[enable-banking] Failed to mirror cash_account on callback', {
|
||||
connectionId: updatedConnection.id,
|
||||
uid: account.uid,
|
||||
error: reason,
|
||||
})
|
||||
// Persist the failure to event_log so a security review can see that
|
||||
// a PSD2 account returned by the bank was not mirrored into our
|
||||
// routing table — otherwise this is only visible in console output
|
||||
// (ASVS V16 / ISO 27001 A.8.15 / SOC 2 CC7.2).
|
||||
try {
|
||||
await eventBus.emit({
|
||||
type: 'bank_connection.cash_account_mirror_failed',
|
||||
payload: {
|
||||
connectionId: updatedConnection.id,
|
||||
bankName: updatedConnection.bank_name ?? null,
|
||||
accountUid: account.uid,
|
||||
ledgerAccount: targetLedger,
|
||||
currency: account.currency,
|
||||
reason,
|
||||
userId: updatedConnection.user_id,
|
||||
companyId: updatedConnection.company_id,
|
||||
},
|
||||
})
|
||||
} catch (emitError) {
|
||||
console.error('[enable-banking] Failed to emit cash_account_mirror_failed event', {
|
||||
connectionId: updatedConnection.id,
|
||||
error: emitError instanceof Error ? emitError.message : String(emitError),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Audit trail: PSD2 consent has been exchanged and account metadata stored.
|
||||
// ASVS V16 requires this transition to be logged as a security event; emit
|
||||
// here so the event_log handler persists it (30-day TTL).
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { createExtensionContext } from '@/lib/extensions/context-factory'
|
||||
import { computeSkattekontoDrift } from '@/extensions/general/skatteverket/lib/skattekonto-drift'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
const log = createLogger('skattekonto-drift-route')
|
||||
|
||||
/**
|
||||
* GET /api/extensions/skatteverket/skattekonto/drift
|
||||
*
|
||||
* Returns the current SKV saldo vs GL 1630 drift snapshot for the active
|
||||
* company. Backs the dashboard SkattekontoDriftTile. Returns null when no
|
||||
* snapshot exists yet (fresh company, never synced).
|
||||
*
|
||||
* Access is recorded through the structured logger (Sentry / Vercel logs)
|
||||
* because the response carries sensitive GL drift figures. Persisting every
|
||||
* dashboard tile poll into event_log would be too noisy — the structured
|
||||
* log line gives an auditable record without overrunning the 30-day event
|
||||
* log retention (SOC 2 CC8.1, ISO 27001 A.8.15).
|
||||
*/
|
||||
export async function GET(_request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
const ctx = createExtensionContext(supabase, user.id, companyId, 'skatteverket')
|
||||
|
||||
const drift = await computeSkattekontoDrift(ctx)
|
||||
log.info('skattekonto drift snapshot accessed', {
|
||||
userId: user.id,
|
||||
companyId,
|
||||
hasDrift: drift !== null,
|
||||
})
|
||||
return NextResponse.json({ data: drift })
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { ensureInitialized } from '@/lib/init'
|
||||
import { verifyCronSecret } from '@/lib/auth/cron'
|
||||
import { createExtensionContext } from '@/lib/extensions/context-factory'
|
||||
import { syncSkattekonto, SKATTEKONTO_LAST_SYNCED_AT_KEY } from '@/extensions/general/skatteverket/lib/skattekonto-sync'
|
||||
import { computeSkattekontoDrift, maybeAlertDrift } from '@/extensions/general/skatteverket/lib/skattekonto-drift'
|
||||
import { SkatteverketAuthError } from '@/extensions/general/skatteverket/lib/api-client'
|
||||
import { SkatteverketSkattekontoError } from '@/extensions/general/skatteverket/lib/skattekonto-client'
|
||||
|
||||
@@ -115,6 +116,19 @@ export async function GET(request: Request) {
|
||||
const ctx = createExtensionContext(supabase, userId, companyId, 'skatteverket')
|
||||
const syncResult = await syncSkattekonto(ctx)
|
||||
|
||||
// Drift check: compare the fresh SKV saldo against GL 1630 sum. Emits
|
||||
// `skattekonto.drift_detected` when |drift| > tolerance and not throttled.
|
||||
try {
|
||||
const drift = await computeSkattekontoDrift(ctx)
|
||||
if (drift) await maybeAlertDrift(ctx, drift)
|
||||
} catch (driftErr) {
|
||||
console.error('[skattekonto-sync-cron] Drift check failed', {
|
||||
userId,
|
||||
companyId,
|
||||
message: driftErr instanceof Error ? driftErr.message : String(driftErr),
|
||||
})
|
||||
}
|
||||
|
||||
results.push({
|
||||
userId,
|
||||
companyId,
|
||||
|
||||
@@ -5,7 +5,14 @@ import { createAuthCode } from '@/lib/auth/oauth-codes'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
import { isAllowedRedirectUri } from '@/lib/auth/oauth-allowlist'
|
||||
import { API_KEY_SCOPES, type ApiKeyScope } from '@/lib/auth/api-keys'
|
||||
import {
|
||||
ALL_SCOPES,
|
||||
API_KEY_SCOPES,
|
||||
DEFAULT_OAUTH_SCOPES,
|
||||
SCOPE_GROUPS,
|
||||
validateScopes,
|
||||
type ApiKeyScope,
|
||||
} from '@/lib/auth/api-keys'
|
||||
|
||||
/**
|
||||
* OAuth 2.0 Authorization Endpoint.
|
||||
@@ -23,20 +30,21 @@ type ScopeParseResult =
|
||||
|
||||
/**
|
||||
* Parse the OAuth `scope` query param (RFC 6749 §3.3 — space-delimited list)
|
||||
* into the subset of API_KEY_SCOPES that the user actually granted.
|
||||
* into the subset of API_KEY_SCOPES the client is asking for. Used to drive
|
||||
* pre-checked defaults on the consent UI; the user's actual grant comes from
|
||||
* their checkbox selection.
|
||||
*
|
||||
* Returns:
|
||||
* - { ok, scopes: undefined } when no scope param was supplied — the token
|
||||
* endpoint will fall back to DEFAULT_OAUTH_SCOPES (read-only, GDPR
|
||||
* Art.25(2) data-protection-by-default).
|
||||
* - { ok, scopes: undefined } when no scope param was supplied — the consent
|
||||
* UI pre-checks DEFAULT_OAUTH_SCOPES (read-only, GDPR Art. 25(2)).
|
||||
* - { ok, scopes: [...] } when at least one valid scope was requested.
|
||||
* - { invalid_scope } when a scope param was supplied but every value was
|
||||
* unknown — refusing the request is safer than silently widening the
|
||||
* grant to ALL_SCOPES (V10.2.6).
|
||||
* unknown — refusing the request is safer than silently dropping it back
|
||||
* to defaults the caller didn't ask for (V10.2.6).
|
||||
*
|
||||
* The bare `mcp` marker is treated as "no granular scopes" and accepted for
|
||||
* backwards compatibility with Claude's connector — it falls through to
|
||||
* `undefined` so the default-OAuth fallback applies.
|
||||
* `undefined` so the read-only defaults apply.
|
||||
*/
|
||||
function parseRequestedScopes(scopeParam: string | null): ScopeParseResult {
|
||||
if (!scopeParam) return { kind: 'ok', scopes: undefined }
|
||||
@@ -179,12 +187,27 @@ export async function GET(request: Request) {
|
||||
|
||||
const appNameLower = escapeHtml(getBranding().appName.toLowerCase())
|
||||
|
||||
// CSP nonce for the inline consent UI controls. A nonce-bound script-src
|
||||
// makes the inline block executable while keeping the rest of the page
|
||||
// immune to script injection — without this the consent page is
|
||||
// incompatible with a strict CSP and counts as unsafe-inline (ASVS V3.3,
|
||||
// SOC 2 CC6.1). The nonce is regenerated per response.
|
||||
const cspNonce = crypto.randomBytes(16).toString('base64')
|
||||
|
||||
// Bind the requested scope to the consent display. The HMAC signature is
|
||||
// verified on POST so a tampered form submission cannot widen the grant
|
||||
// beyond what the user actually saw (V10.3.1).
|
||||
const scopeBindingValue = scopeParam ?? ''
|
||||
const scopeBindingSignature = signScopeBinding(scopeBindingValue)
|
||||
|
||||
// The grant ceiling is the set of scopes the client requested, or
|
||||
// DEFAULT_OAUTH_SCOPES when the client passed no scope param. Pre-checks
|
||||
// everything in the ceiling. The POST handler enforces the same ceiling
|
||||
// server-side so a tampered form can't widen the grant past what the
|
||||
// client actually asked for (RFC 6749 §3.3, SOC 2 CC6.3).
|
||||
const grantCeiling = new Set<ApiKeyScope>(parsed.scopes ?? DEFAULT_OAUTH_SCOPES)
|
||||
const scopeCheckboxesHtml = renderScopeCheckboxes(grantCeiling, grantCeiling)
|
||||
|
||||
// Render consent page
|
||||
const html = `<!DOCTYPE html>
|
||||
<html lang="sv">
|
||||
@@ -195,15 +218,26 @@ export async function GET(request: Request) {
|
||||
<title>Anslut MCP-klient — ${appNameLower}</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body { font-family: system-ui, -apple-system, sans-serif; background: #fafafa; color: #111; display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 1rem; }
|
||||
.card { background: white; border-radius: 12px; border: 1px solid #e5e5e5; padding: 2rem; max-width: 400px; width: 100%; }
|
||||
body { font-family: system-ui, -apple-system, sans-serif; background: #fafafa; color: #111; display: flex; align-items: flex-start; justify-content: center; min-height: 100vh; padding: 2rem 1rem; }
|
||||
.card { background: white; border-radius: 12px; border: 1px solid #e5e5e5; padding: 2rem; max-width: 520px; width: 100%; }
|
||||
h1 { font-size: 1.25rem; font-weight: 600; margin-bottom: 0.5rem; }
|
||||
p { font-size: 0.875rem; color: #666; line-height: 1.5; margin-bottom: 1rem; }
|
||||
.account { font-size: 0.875rem; color: #111; font-weight: 500; background: #f5f5f5; padding: 0.75rem 1rem; border-radius: 8px; margin-bottom: 1.5rem; }
|
||||
.permissions { font-size: 0.8125rem; color: #444; margin-bottom: 1.5rem; }
|
||||
.permissions li { margin-bottom: 0.25rem; }
|
||||
.actions { display: flex; gap: 0.75rem; }
|
||||
button { flex: 1; padding: 0.625rem 1rem; border-radius: 8px; font-size: 0.875rem; font-weight: 500; cursor: pointer; border: 1px solid #e5e5e5; }
|
||||
.scopes-header { font-size: 0.75rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: #666; margin-bottom: 0.75rem; }
|
||||
.scopes-controls { display: flex; gap: 0.75rem; margin-bottom: 1rem; }
|
||||
.scopes-controls button { padding: 0.25rem 0.625rem; font-size: 0.75rem; font-weight: 500; background: white; color: #444; border: 1px solid #e5e5e5; border-radius: 6px; cursor: pointer; }
|
||||
.scopes-controls button:hover { background: #f5f5f5; }
|
||||
.scope-group { border: 1px solid #ececec; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.5rem; }
|
||||
.scope-group-title { font-size: 0.8125rem; font-weight: 600; color: #111; margin-bottom: 0.5rem; }
|
||||
.scope-row { display: flex; gap: 0.625rem; padding: 0.375rem 0; align-items: flex-start; }
|
||||
.scope-row input { margin-top: 0.1875rem; cursor: pointer; }
|
||||
.scope-row label { font-size: 0.8125rem; color: #333; cursor: pointer; line-height: 1.4; }
|
||||
.scope-row .scope-name { font-weight: 500; color: #111; }
|
||||
.scope-row .scope-desc { color: #666; font-size: 0.75rem; display: block; margin-top: 0.125rem; }
|
||||
.scope-row.write .scope-name::after { content: " · skriv"; color: #b85c2c; font-weight: 500; }
|
||||
.warn { font-size: 0.75rem; color: #8b5a00; background: #fff7e6; border: 1px solid #f0d6a1; border-radius: 6px; padding: 0.625rem 0.75rem; margin: 1rem 0; line-height: 1.4; }
|
||||
.actions { display: flex; gap: 0.75rem; margin-top: 1.5rem; }
|
||||
.actions button { flex: 1; padding: 0.625rem 1rem; border-radius: 8px; font-size: 0.875rem; font-weight: 500; cursor: pointer; border: 1px solid #e5e5e5; }
|
||||
.allow { background: #111; color: white; border-color: #111; }
|
||||
.allow:hover { background: #333; }
|
||||
.deny { background: white; color: #111; }
|
||||
@@ -213,34 +247,73 @@ export async function GET(request: Request) {
|
||||
<body>
|
||||
<div class="card">
|
||||
<h1>Anslut MCP-klient</h1>
|
||||
<p>En extern applikation vill ansluta till ditt ${appNameLower}-konto.</p>
|
||||
<p>En extern applikation vill ansluta till ditt ${appNameLower}-konto. Välj vilka behörigheter du vill ge.</p>
|
||||
<div class="account">${escapeHtml(companyName)}</div>
|
||||
<ul class="permissions">
|
||||
<li>Visa och kategorisera transaktioner</li>
|
||||
<li>Skapa och visa fakturor</li>
|
||||
<li>Visa kunder och rapporter</li>
|
||||
<li>Skapa verifikationer</li>
|
||||
</ul>
|
||||
<div class="actions">
|
||||
<form method="POST" action="${url.pathname}${url.search}" style="flex:1;display:flex;">
|
||||
<input type="hidden" name="consent" value="deny">
|
||||
<input type="hidden" name="scope_binding" value="${escapeHtml(scopeBindingValue)}">
|
||||
<input type="hidden" name="scope_binding_sig" value="${escapeHtml(scopeBindingSignature)}">
|
||||
<button type="submit" class="deny" style="width:100%;">Neka</button>
|
||||
</form>
|
||||
<form method="POST" action="${url.pathname}${url.search}" style="flex:1;display:flex;">
|
||||
<input type="hidden" name="consent" value="allow">
|
||||
<input type="hidden" name="scope_binding" value="${escapeHtml(scopeBindingValue)}">
|
||||
<input type="hidden" name="scope_binding_sig" value="${escapeHtml(scopeBindingSignature)}">
|
||||
<button type="submit" class="allow" style="width:100%;">Tillåt</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<form method="POST" action="${url.pathname}${url.search}" id="consent-form">
|
||||
<input type="hidden" name="scope_binding" value="${escapeHtml(scopeBindingValue)}">
|
||||
<input type="hidden" name="scope_binding_sig" value="${escapeHtml(scopeBindingSignature)}">
|
||||
|
||||
<div class="scopes-header">Behörigheter</div>
|
||||
<div class="scopes-controls">
|
||||
<button type="button" id="select-read">Endast läs</button>
|
||||
<button type="button" id="select-all">Markera alla</button>
|
||||
<button type="button" id="select-none">Avmarkera alla</button>
|
||||
</div>
|
||||
|
||||
${scopeCheckboxesHtml}
|
||||
|
||||
<div class="warn">
|
||||
Skrivbehörigheter låter agenten stagea verifikationer, fakturor och löner. Alla skrivoperationer kräver din godkännande i ${appNameLower} innan de skrivs till databasen.
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<button type="submit" name="consent" value="deny" class="deny">Neka</button>
|
||||
<button type="submit" name="consent" value="allow" class="allow">Tillåt</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<script nonce="${cspNonce}">
|
||||
(function() {
|
||||
var form = document.getElementById('consent-form');
|
||||
var boxes = form.querySelectorAll('input[name="scopes"]');
|
||||
function setAll(predicate) {
|
||||
boxes.forEach(function(b) { b.checked = predicate(b); });
|
||||
}
|
||||
document.getElementById('select-read').addEventListener('click', function() {
|
||||
setAll(function(b) { return b.dataset.kind === 'read'; });
|
||||
});
|
||||
document.getElementById('select-all').addEventListener('click', function() {
|
||||
setAll(function() { return true; });
|
||||
});
|
||||
document.getElementById('select-none').addEventListener('click', function() {
|
||||
setAll(function() { return false; });
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
</div>
|
||||
</body>
|
||||
</html>`
|
||||
|
||||
// script-src bound to the per-request nonce ensures the consent page's
|
||||
// inline JS can only be the block we actually emitted. Anything injected
|
||||
// by a forged response or persisted XSS would be blocked.
|
||||
const csp = [
|
||||
"default-src 'none'",
|
||||
`script-src 'nonce-${cspNonce}'`,
|
||||
"style-src 'unsafe-inline'",
|
||||
"form-action 'self'",
|
||||
"base-uri 'none'",
|
||||
"frame-ancestors 'none'",
|
||||
].join('; ')
|
||||
|
||||
return new Response(html, {
|
||||
headers: { 'Content-Type': 'text/html; charset=utf-8' },
|
||||
headers: {
|
||||
'Content-Type': 'text/html; charset=utf-8',
|
||||
'Content-Security-Policy': csp,
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Referrer-Policy': 'no-referrer',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -286,8 +359,11 @@ export async function POST(request: Request) {
|
||||
}
|
||||
|
||||
// Verify the scope binding signed at consent display matches what was
|
||||
// submitted with the form. This prevents a tampered POST from widening the
|
||||
// grant beyond what the user actually saw (V10.3.1).
|
||||
// submitted with the form. This pins the form to the GET that minted it,
|
||||
// so an attacker who tricks the user into submitting a crafted form can't
|
||||
// change the client's `scope=` querystring midway through the flow
|
||||
// (V10.3.1). The granted scopes themselves come from the user's checkbox
|
||||
// selection and are bounded server-side by API_KEY_SCOPES.
|
||||
const presentedScopeBinding = formData.get('scope_binding')
|
||||
const presentedScopeBindingSig = formData.get('scope_binding_sig')
|
||||
const presentedScopeStr = typeof presentedScopeBinding === 'string' ? presentedScopeBinding : ''
|
||||
@@ -305,21 +381,44 @@ export async function POST(request: Request) {
|
||||
)
|
||||
}
|
||||
|
||||
// Parse the bound scope rather than re-reading the querystring at POST time
|
||||
// so the auth code always reflects the consent the user gave. parseRequestedScopes
|
||||
// already rejects requests where every scope is unknown (V10.2.6).
|
||||
// Validate the client's original scope request (rejects an entirely-unknown
|
||||
// scope set — V10.2.6). The actual grant comes from the user's checkbox
|
||||
// selection below, not from this querystring.
|
||||
const parsed = parseRequestedScopes(querystringScopeParam)
|
||||
if (parsed.kind === 'invalid_scope') {
|
||||
return errorRedirect(redirectUri, state, 'invalid_scope', parsed.description)
|
||||
}
|
||||
const requestedScopes = parsed.scopes
|
||||
|
||||
// The user selects scopes via checkboxes on the consent page. Two upper
|
||||
// bounds apply server-side, regardless of what the form posts:
|
||||
//
|
||||
// 1. validateScopes drops any value that isn't in API_KEY_SCOPES — guards
|
||||
// against forged values from a tampered POST.
|
||||
// 2. The grant must be a subset of what the client *originally asked for*
|
||||
// (the `scope` querystring on the GET). Otherwise a client that
|
||||
// requested only read scopes could end up with write grants because
|
||||
// the user ticked extra boxes — that's a least-privilege violation
|
||||
// (RFC 6749 §3.3, SOC 2 CC6.3, NIST AC-6) and removes the client's
|
||||
// ability to advertise the access surface it actually intends to use.
|
||||
//
|
||||
// When the client didn't pass a scope param at all (parsed.scopes is
|
||||
// undefined), the consent UI defaults to DEFAULT_OAUTH_SCOPES — that becomes
|
||||
// the implicit ceiling for the grant.
|
||||
const submittedScopes = formData.getAll('scopes').filter((s): s is string => typeof s === 'string')
|
||||
const validated = validateScopes(submittedScopes)
|
||||
const clientCeiling: ApiKeyScope[] = parsed.scopes ?? [...DEFAULT_OAUTH_SCOPES]
|
||||
const ceilingSet = new Set<ApiKeyScope>(clientCeiling)
|
||||
const boundedToClient = (validated ?? []).filter(s => ceilingSet.has(s))
|
||||
const grantedScopes: ApiKeyScope[] = boundedToClient.length > 0
|
||||
? boundedToClient
|
||||
: [...DEFAULT_OAUTH_SCOPES].filter(s => ceilingSet.has(s))
|
||||
|
||||
// Create auth code with userId (NO API key — that's created at /token after PKCE)
|
||||
const code = createAuthCode({
|
||||
userId: user.id,
|
||||
codeChallenge,
|
||||
redirectUri,
|
||||
...(requestedScopes ? { scopes: requestedScopes } : {}),
|
||||
scopes: grantedScopes,
|
||||
})
|
||||
|
||||
// Redirect to callback with the code
|
||||
@@ -333,6 +432,64 @@ export async function POST(request: Request) {
|
||||
return NextResponse.redirect(callbackUrl.toString(), 303)
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the scope checkbox UI grouped by domain. Only scopes in `ceiling`
|
||||
* (the client's `scope` querystring, or DEFAULT_OAUTH_SCOPES) are surfaced —
|
||||
* scopes outside the ceiling are dropped from the consent UI so the user
|
||||
* can't tick boxes that the POST handler would refuse anyway. Pre-checks
|
||||
* every visible row by default.
|
||||
*/
|
||||
function renderScopeCheckboxes(
|
||||
preChecked: Set<ApiKeyScope>,
|
||||
ceiling: Set<ApiKeyScope>,
|
||||
): string {
|
||||
const renderedInGroups = new Set<ApiKeyScope>()
|
||||
const groups: string[] = []
|
||||
|
||||
for (const group of SCOPE_GROUPS) {
|
||||
const rows: string[] = []
|
||||
if (group.read && ceiling.has(group.read)) {
|
||||
rows.push(scopeRow(group.read, preChecked.has(group.read), 'read'))
|
||||
renderedInGroups.add(group.read)
|
||||
}
|
||||
if (group.write && ceiling.has(group.write)) {
|
||||
rows.push(scopeRow(group.write, preChecked.has(group.write), 'write'))
|
||||
renderedInGroups.add(group.write)
|
||||
}
|
||||
if (rows.length > 0) {
|
||||
groups.push(
|
||||
`<div class="scope-group"><div class="scope-group-title">${escapeHtml(group.label)}</div>${rows.join('')}</div>`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const remaining = ALL_SCOPES.filter(s => ceiling.has(s) && !renderedInGroups.has(s))
|
||||
if (remaining.length > 0) {
|
||||
const rows = remaining.map((s) =>
|
||||
scopeRow(s, preChecked.has(s), s.endsWith(':write') || s.endsWith(':manage') || s.endsWith(':approve') ? 'write' : 'read')
|
||||
)
|
||||
groups.push(
|
||||
`<div class="scope-group"><div class="scope-group-title">Övriga</div>${rows.join('')}</div>`
|
||||
)
|
||||
}
|
||||
|
||||
return groups.join('')
|
||||
}
|
||||
|
||||
function scopeRow(scope: ApiKeyScope, checked: boolean, kind: 'read' | 'write'): string {
|
||||
const meta = API_KEY_SCOPES[scope]
|
||||
const id = `scope-${scope.replace(/[^a-z0-9]/gi, '-')}`
|
||||
return `
|
||||
<div class="scope-row ${kind}">
|
||||
<input type="checkbox" id="${id}" name="scopes" value="${escapeHtml(scope)}" data-kind="${kind}" ${checked ? 'checked' : ''}>
|
||||
<label for="${id}">
|
||||
<span class="scope-name">${escapeHtml(meta.label)}</span>
|
||||
<span class="scope-desc">${escapeHtml(meta.description)}</span>
|
||||
</label>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
|
||||
function escapeHtml(str: string): string {
|
||||
return str
|
||||
.replace(/&/g, '&')
|
||||
|
||||
@@ -24,11 +24,34 @@ export async function POST(request: Request) {
|
||||
|
||||
const validation = await validateBody(request, RunReconciliationSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const { date_from, date_to, dry_run } = validation.data
|
||||
const { date_from, date_to, account_number, dry_run } = validation.data
|
||||
|
||||
const accountNumber = account_number ?? '1930'
|
||||
|
||||
// Defense-in-depth: only allow account numbers the company has registered as
|
||||
// a cash account. Applies uniformly including '1930' — the cash_accounts
|
||||
// backfill seeds 1930 for every company that had a SEK PSD2 account, and the
|
||||
// AccountPickerDialog seeds it for new companies on first connection.
|
||||
const { data: cashAccount } = await supabase
|
||||
.from('cash_accounts')
|
||||
.select('currency')
|
||||
.eq('company_id', companyId)
|
||||
.eq('ledger_account', accountNumber)
|
||||
.maybeSingle()
|
||||
|
||||
if (!cashAccount) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Okänt kassakonto för det här företaget' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
const currency = (cashAccount.currency as string | undefined) ?? 'SEK'
|
||||
|
||||
const result = await runReconciliation(supabase, companyId, user.id, {
|
||||
dateFrom: date_from,
|
||||
dateTo: date_to,
|
||||
accountNumber,
|
||||
currency,
|
||||
dryRun: dry_run ?? false,
|
||||
})
|
||||
|
||||
|
||||
@@ -16,8 +16,35 @@ export async function GET(request: Request) {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const dateFrom = searchParams.get('date_from') || undefined
|
||||
const dateTo = searchParams.get('date_to') || undefined
|
||||
const accountNumber = searchParams.get('account_number') || '1930'
|
||||
|
||||
const status = await getReconciliationStatus(supabase, companyId, dateFrom, dateTo)
|
||||
// Look up the cash account so we can pair the bank account with the right
|
||||
// currency. Comparing EUR GL movements against SEK transactions silently
|
||||
// produces nonsense.
|
||||
const { data: cashAccount } = await supabase
|
||||
.from('cash_accounts')
|
||||
.select('currency')
|
||||
.eq('company_id', companyId)
|
||||
.eq('ledger_account', accountNumber)
|
||||
.maybeSingle()
|
||||
|
||||
if (!cashAccount && accountNumber !== '1930') {
|
||||
return NextResponse.json(
|
||||
{ error: 'Okänt kassakonto för det här företaget' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
const currency = (cashAccount?.currency as string | undefined) ?? 'SEK'
|
||||
|
||||
const status = await getReconciliationStatus(
|
||||
supabase,
|
||||
companyId,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
accountNumber,
|
||||
currency,
|
||||
)
|
||||
|
||||
return NextResponse.json({ data: status })
|
||||
}
|
||||
|
||||
@@ -16,8 +16,29 @@ export async function GET(request: Request) {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const dateFrom = searchParams.get('date_from') || undefined
|
||||
const dateTo = searchParams.get('date_to') || undefined
|
||||
const accountNumber = searchParams.get('account_number') || '1930'
|
||||
|
||||
const lines = await fetchUnlinkedGLLines(supabase, companyId, dateFrom, dateTo)
|
||||
// Defense-in-depth: only allow account numbers that the company has actually
|
||||
// registered as a cash account. Without this, a curious caller could probe
|
||||
// arbitrary GL accounts for posted-but-unmatched amounts. Applies uniformly
|
||||
// including '1930' — the cash_accounts backfill seeds 1930 for every company
|
||||
// that had a SEK PSD2 account, and the AccountPickerDialog seeds it for new
|
||||
// companies on first connection.
|
||||
const { data: cashAccount } = await supabase
|
||||
.from('cash_accounts')
|
||||
.select('id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('ledger_account', accountNumber)
|
||||
.maybeSingle()
|
||||
|
||||
if (!cashAccount) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Okänt kassakonto för det här företaget' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
const lines = await fetchUnlinkedGLLines(supabase, companyId, accountNumber, dateFrom, dateTo)
|
||||
|
||||
return NextResponse.json({ data: lines })
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user