* feat(entitlements): partition the self-host bypass so connector capabilities fall through to grants; capability_grants.source accepts 'connector' Sovereign plan WS3 PR3: ships dark, nothing changes for hosted. - lib/entitlements/keys.ts: CONNECTOR_CAPABILITIES = bank_sync, skatteverket, org_lookup, migration (services Accounted operates that a self-hosted instance cannot provide itself) + isConnectorCapability(). Separate from PAID_CAPABILITIES and outside the trial-seed trigger on purpose: a hosted company can never hold a connector grant. - lib/entitlements/has-capability.ts: isPaywallBypassed() -> isBypassedFor(key). Hosted: byte-identical (dev / DISABLE_PAYWALL bypass, FORCE_PAYWALL wins, else the grant lookup). Self-host: local capabilities always on (FORCE_PAYWALL included, as the existing test demands); connector capabilities behave like hosted, i.e. dev bypass, FORCE_PAYWALL, else the grant lookup where the connector sync will write source='connector' rows. getCompanyEntitlements on a self-host: local paid keys + active connector keys, state 'paid' with an active connector grant else 'none' (never the hosted trial copy). - Migration 20260820122000: capability_grants.source CHECK gains 'connector', found through pg_constraint (the CHECK was declared inline and auto-named; Postgres stores IN as = ANY, matched accordingly). pg-real test: connector accepted, unknown source rejected, upsert on the (scope, key, source) identity, trial seed writes no connector rows. - Tests: self-hosted connector matrix (local all-on without DB, connector gated by grant/expiry, dev bypass all-on, FORCE_PAYWALL gates connector keys only, bulk resolution, entitlements shape); two pre-existing tests that asserted the old "self-host holds connector keys" contract updated to the new one. Verified: full unit suite green, pg-real suite for lib/entitlements green against a local supabase/postgres with every migration applied, lint ratchet, guards. Deferred to the instance-wiring PR: adding the connector extensions to the self-host Docker preset (dead-end upsells until a key can be issued). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor(entitlements): fold the self-host branch into the existing grants query One .or(scopeFilter), not two: the duplicated helper pushed the no-phantom-columns unresolvable-expression count to 380/379. Behaviour is unchanged; the self-host matrix tests still pass. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(connect): hosted connector-key registry + validate RPC + entitlements endpoint; instance sync writes connector grants hourly Sovereign plan WS3 PR4 ("key infra enabling manual sales"), stacked on the entitlement partition (#1747). Nothing is purchasable yet; this is the plumbing both ends need before the first manually issued key. Hosted side: - Migration 20260820123000: connector_keys (SHA-256 key_hash, prefix, org_number, pinned instance_url, scopes, status, Stripe ids, current_period_end, per-minute rate limit, active_company_count, last_seen/synced) and connector_usage_events (per-request metering, separate from metered_events whose company_id references hosted companies). RLS on, NO policies: service role only. RPC validate_and_increment_connector_key copies the api_keys pattern (FOR UPDATE, minute window, suspended reported not counted, revoked = no row) and is REVOKEd from PUBLIC/anon/authenticated, GRANTed to service_role. pg-real test covers validate/count, unknown+revoked, suspended, rate limit, execute privileges per role, RLS invisibility, usage cascade. - lib/connect/contract.ts (shared wire types), lib/connect/hosted/keys.ts (generate/hash/validate -> 401/403/429 mapping), with-connector-auth.ts (Bearer or X-Connector-Key, one usage row per request, 500 envelope on handler throw), /api/connect/entitlements GET + POST (records active_company_count, pins instance_url on first report, never moves a pinned one), scripts/issue-connector-key.ts (dry run unless --confirm, prints the key once + the .env lines). Instance side: - lib/connect/instance/config.ts (GNUBOK_CONNECTOR_KEY, GNUBOK_CONNECT_URL default https://app.gnubok.se), sync.ts: reports the active company count and writes source='connector' grants for every company x covered scope, expires_at = min(now+72h, period_end+3d); 401/403 or a non-active status deletes them (freeze-and-retain); network/5xx/429 leave them alone. /api/connector/sync/cron (hourly) runs it; not_configured without a key. - Crontab generator gains EXTRA_JOBS (variant-only jobs not in vercel.json, with reasons) + drift tests; docker/crontab.self-hosted regenerated with the hourly sync. Docs (SELF-HOSTING connector section, env templates), DECISIONS. Tests: 52 new unit tests (keys, auth wrapper, route, config, sync outcomes and grant arithmetic, cron route, crontab EXTRA_JOBS) + 7 pg-real tests run locally against supabase/postgres with every migration applied. no-phantom-columns ceiling +1 with a reason (the bulk grant upsert). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(connect): Enable Banking proxy for self-hosted instances, with a secret-free ownership ledger and a global rate budget Sovereign plan WS3 PR5a, stacked on the connector-key infra (#1748). A self-hosted instance with a `bank_sync`-scoped connector key can now connect a bank through Arcim's PSD2 credentials; the bank session id and all transaction data stay in the instance's own database (founder decision: tokens on the instance, proxy stateless). - Migration 20260820124000: `connector_connections` (secret-free ledger: sha256 of the EB session id + account uids, service-role only), `connector_upstream_counters` + RPC `connector_reserve_upstream` (global budget under EB Annex 1 §5's 300/min, shared with hosted), and `connector_keys.limits` jsonb; validate RPC v2 returns limits. All RPCs REVOKEd from PUBLIC/anon/authenticated, GRANTed service_role. pg-real covers all of it. - EB JWT minting moved to lib/connect/upstreams/enable-banking-jwt.ts (core must not import @/extensions/); the extension re-exports it, tests unchanged. - lib/connect/hosted/{state,ledger,upstream-budget}.ts: HMAC-signed connector state (15-min TTL) so the consent redirect can use OUR registered EB callback and bounce back to the instance, no per-instance redirect URI at EB; the callback route gains that connector branch. - app/api/connect/bank/[...path]: path allowlist (aspsps, auth, sessions, accounts/{uid}/{balances,transactions}), never open passthrough. POST /auth enforces the per-company connection quota + rewrites redirect/state; reads/deletes verify ledger ownership; every upstream call takes the global budget (429 + Retry-After when exhausted). - issue-connector-key.ts: scopes default bank_sync,skatteverket (TIC out of v1), --bank/skv-connections-per-company + --sync-min-interval. - Docs (SELF-HOSTING: bank connector live), DECISIONS. Verified: 52 connect unit tests + 13 pg-real (run locally against supabase/postgres with all migrations) + EB extension suite (225, jwt relocation intact); full unit suite 15 979 green; tsc, guards, lint clean. Not in this PR: SKV broker (PR5b) and instance wiring (PR6). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(connect): Skatteverket broker + data proxy for self-hosted instances (tokens stay on the instance) Sovereign plan WS3 PR5b, stacked on the bank proxy (#1751). A self-hosted instance with a `skatteverket`-scoped connector key can now run the BankID consent, file VAT/AGI and sync skattekonto through Arcim's registered Skatteverket client; the SKV tokens are returned to the instance and stored (encrypted) there. - lib/connect/upstreams/skatteverket-oauth.ts: core-side SKV OAuth + data helpers (authorize URL, code/refresh exchange with Arcim's client secret, the four backing-API base URLs, the API-gateway Client_Id/Client_Secret headers). Core can't import @/extensions/, so this duplicates the extension's endpoints/scope set (one integrator = Arcim), mirroring the EB JWT relocation. - app/api/connect/skv/oauth/authorize-url: builds the authorize URL against OUR registered redirect_uri + a signed connector state, per-company SKV connection quota, pending ledger row. - app/api/connect/skv/oauth/token: exchanges/refreshes and RETURNS the tokens to the instance; the ledger keeps only sha256(access_token) + sha256(refresh_token). - app/api/connect/skv/api/[...path]: allowlist over moms / skattekonto / agd-inlamning / agd-period. The instance sends the user's SKV Bearer (as X-Connector-Upstream-Authorization) + X-Connector-Key; the proxy checks the token hash against the ledger, adds Arcim's gateway credentials (never exposed to the instance), forwards. Same per-key + global budget as bank. - The Skatteverket extension /callback gains the connector branch (isConnectorState -> 302 back to the instance; code never exchanged there). - Docs (SELF-HOSTING: SKV connector live) + DECISIONS. Tests: SKV oauth lib, authorize-url, token, data proxy, callback connector branch (all green; 74 connect + 425 connect/SKV). tsc, guards, lint clean; no-phantom-columns held at 380 (literal update branches). Not in this PR: instance-side wiring (PR6). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(connect): self-host connector enablement: EB/SKV in the preset, connector-mode seam, status endpoint Sovereign plan WS3 PR6 (enablement layer), stacked on the SKV broker (#1757). - docker/extensions.self-hosted.json += enable-banking, skatteverket: a connector-key self-host now ships the bank + Skatteverket extensions; a key with the matching scope makes them work, without one they show the existing capability_blocked upsell (unconfigured extensions no-op). - lib/connect/instance/upstreams.ts: the connector-mode seam. An upstream is in connector mode only when GNUBOK_CONNECTOR_KEY is set AND the instance has no own credentials for it (hasOwnEnableBankingCredentials / hasOwnSkatteverketCredentials). Hosted always has own credentials, so hosted is provably never in connector mode: the guard is what keeps hosted byte-identical. Base URLs GNUBOK_CONNECT_URL/api/connect/{bank,skv}, headers X-Connector-Company / X-Connector-Upstream-Authorization. - GET /api/connector/status: the operator's wiring view (self_hosted, per upstream own_credentials|connector|unconfigured, key prefix never the key, granted connector capabilities). Hosted returns self_hosted:false. - Docs (SELF-HOSTING: status endpoint + extensions ship in the image), DECISIONS. Tests: connector-mode detection matrix (off without a key, off with own creds incl. the _PRODUCTION EB variants, on via the proxy, CONNECT_URL override) + status route (self-host vs hosted, unconfigured, per-upstream mode, prefix-not-key). 83 connect/connector tests green; tsc, guards, lint. DEFERRED to PR6b (needs a live connector key + a real bank/SKV to verify end to end, touches the live consent path): wiring the EB api-client / consent callback and the SKV oauth / api-client to call the proxy in connector mode, and the "Synka nu" settings row (UI, needs visual sign-off). The seam + preset + status route make PR6b a contained follow-up. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor(connect): upstreams seam reuses lib/entitlements/own-credentials Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UzNkSsR18pLFitJdYn8QEb * test(connector): status route tests pass the Next params argument (post-merge withRouteContext signature) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UzNkSsR18pLFitJdYn8QEb * docs(self-host): collapse the re-duplicated connector section; correct the crontab generator's preset comment Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UzNkSsR18pLFitJdYn8QEb * fix(self-host): UpgradeNote and SKV tooltip name the connector key, never the hosted subscription; SOVEREIGN.md updated to merged reality Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UzNkSsR18pLFitJdYn8QEb * fix(self-host): BankSyncNowButton gate copy branches like UpgradeNote (connector key, not hosted billing) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UzNkSsR18pLFitJdYn8QEb --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: Emil <emilmattsson14@gmail.com>
597 lines
22 KiB
TypeScript
597 lines
22 KiB
TypeScript
'use client'
|
|
|
|
import { useTranslations } from 'next-intl'
|
|
import Image from 'next/image'
|
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Badge } from '@/components/ui/badge'
|
|
import { useToast } from '@/components/ui/use-toast'
|
|
import { useCapability } from '@/contexts/CompanyContext'
|
|
import { isAllowedSkvPopupOrigin } from '@/lib/skatteverket/popup-origin'
|
|
import { isSelfHosted } from '@/lib/env/public-flags'
|
|
import { CAPABILITY } from '@/lib/entitlements/keys'
|
|
import { UpgradeNote } from '@/components/billing/UpgradeNote'
|
|
import {
|
|
SettingsGroup,
|
|
SettingsRow,
|
|
SettingsRowEnd,
|
|
SettingsRowNote,
|
|
} from '@/components/settings/SettingsRows'
|
|
import { CheckCircle2, ExternalLink, Loader2, ShieldOff, FlaskConical, ShieldAlert } from 'lucide-react'
|
|
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
|
import { useBranding } from '@/lib/branding/brand-context'
|
|
|
|
type Environment = 'test' | 'prod'
|
|
|
|
type Status =
|
|
| { connected: false; environment?: Environment; disabled?: boolean }
|
|
| {
|
|
connected: true
|
|
expired: boolean
|
|
canRefresh: boolean
|
|
needsReconsent?: boolean
|
|
lastErrorCode?: string | null
|
|
scope: string
|
|
expiresAt: string
|
|
environment?: Environment
|
|
disabled?: boolean
|
|
}
|
|
|
|
/** Live warning inside a settings group: one warning-tone line, no banner. */
|
|
function WarningLine({ children }: { children: React.ReactNode }) {
|
|
return (
|
|
<p className="border-b border-border px-1 py-3 text-[12.5px] leading-relaxed text-attn">
|
|
{children}
|
|
</p>
|
|
)
|
|
}
|
|
|
|
export function SkatteverketConnectPanel() {
|
|
return (
|
|
<>
|
|
<SkatteverketPersonalConnectionCard />
|
|
<SkatteverketSystemConnectionCard />
|
|
</>
|
|
)
|
|
}
|
|
|
|
function SkatteverketPersonalConnectionCard() {
|
|
const t = useTranslations('settings_skatteverket_connect')
|
|
// Toast strings shared with TaxSettingsContent's query-param fallback path.
|
|
const tOauth = useTranslations('settings_skatteverket')
|
|
const { toast } = useToast()
|
|
const hasSkatteverket = useCapability(CAPABILITY.skatteverket)
|
|
const [status, setStatus] = useState<Status | null>(null)
|
|
const [loading, setLoading] = useState(true)
|
|
const [disconnecting, setDisconnecting] = useState(false)
|
|
// True while an OAuth tab opened from this panel is still alive. Disables
|
|
// the connect button so a second click cannot start a parallel flow: each
|
|
// /authorize call overwrites the stored oauth_state + PKCE verifier, so a
|
|
// parallel flow guarantees a CSRF failure for whichever tab finishes last.
|
|
const [connecting, setConnecting] = useState(false)
|
|
// Handle of the OAuth tab opened by startConnect: used to verify the
|
|
// sender identity of incoming postMessages and to detect abandonment.
|
|
const popupRef = useRef<Window | null>(null)
|
|
const watchTimerRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
|
const delayedRefetchRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
|
|
|
const stopWatchingOauthTab = useCallback(() => {
|
|
if (watchTimerRef.current) {
|
|
clearInterval(watchTimerRef.current)
|
|
watchTimerRef.current = null
|
|
}
|
|
setConnecting(false)
|
|
}, [])
|
|
|
|
useEffect(() => {
|
|
return () => {
|
|
if (watchTimerRef.current) clearInterval(watchTimerRef.current)
|
|
if (delayedRefetchRef.current) clearTimeout(delayedRefetchRef.current)
|
|
}
|
|
}, [])
|
|
|
|
// docs: https://www7.skatteverket.se/portal-wapi/open/apier-och-oppna-data/utvecklarportalen/v1/getFile/tjanstebeskrivning-skattekonto-hamta-huvudmans-saldo-och-transaktioner-v101
|
|
const SCOPE_LABELS: Record<string, string> = {
|
|
momsdeklaration: t('scope_momsdeklaration'),
|
|
inkforetag: t('scope_inkforetag'),
|
|
ska: t('scope_ska'),
|
|
skahmst: t('scope_skahmst'),
|
|
skattekonto: t('scope_skattekonto'),
|
|
agd: t('scope_agd'),
|
|
}
|
|
|
|
// Only the first load blanks the section to the loading state: later
|
|
// refetches (postMessage, closed-tab watcher, delayed sync refetch,
|
|
// visibility) update in the background so the panel doesn't flash on every
|
|
// signal.
|
|
const hasLoadedRef = useRef(false)
|
|
const loadStatus = useCallback(async () => {
|
|
if (!hasLoadedRef.current) setLoading(true)
|
|
try {
|
|
const res = await fetch('/api/extensions/ext/skatteverket/status')
|
|
if (res.status === 503) {
|
|
setStatus({ connected: false })
|
|
return
|
|
}
|
|
const data = (await res.json()) as Status
|
|
setStatus(data)
|
|
} catch {
|
|
setStatus({ connected: false })
|
|
} finally {
|
|
hasLoadedRef.current = true
|
|
setLoading(false)
|
|
}
|
|
}, [])
|
|
|
|
useEffect(() => {
|
|
loadStatus()
|
|
}, [loadStatus])
|
|
|
|
// Safety net for completion signals that never reach this tab: a mobile
|
|
// BankID app-switch can land the OAuth return in a different browser tab,
|
|
// and a bfcache-restored page shows a pre-connection snapshot. Refetch
|
|
// status whenever the tab regains visibility, throttled so rapid tab
|
|
// toggling doesn't hammer the API.
|
|
const lastVisibilityFetchRef = useRef(0)
|
|
useEffect(() => {
|
|
function onVisible() {
|
|
if (document.visibilityState !== 'visible') return
|
|
const now = Date.now()
|
|
if (now - lastVisibilityFetchRef.current < 5_000) return
|
|
lastVisibilityFetchRef.current = now
|
|
loadStatus()
|
|
}
|
|
document.addEventListener('visibilitychange', onVisible)
|
|
return () => document.removeEventListener('visibilitychange', onVisible)
|
|
}, [loadStatus])
|
|
|
|
// Listen for OAuth completion from the BankID popup (same pattern as
|
|
// AGIPanel): the callback page posts success/error and closes itself, so
|
|
// the settings page never navigates and we just re-fetch the status.
|
|
useEffect(() => {
|
|
function handleMessage(event: MessageEvent) {
|
|
// The popup runs on the pinned SKV OAuth host, which differs from the
|
|
// app origin after the app.accounted.se cutover.
|
|
if (!isAllowedSkvPopupOrigin(event.origin, window.location.origin)) return
|
|
// Source-identity check: only the popup this component opened can
|
|
// trigger the handler; a window reference cannot be forged by other
|
|
// same-origin scripts.
|
|
if (!popupRef.current || event.source !== popupRef.current) return
|
|
if (event.data?.type === 'skatteverket-oauth-success') {
|
|
stopWatchingOauthTab()
|
|
toast({
|
|
title: tOauth('connected_title'),
|
|
description: tOauth('connected_description'),
|
|
})
|
|
loadStatus()
|
|
// Verified success: rebroadcast as an internal DOM event so passive
|
|
// consumers (e.g. the salary page) can react without trusting raw
|
|
// postMessage.
|
|
window.dispatchEvent(new CustomEvent('skatteverket-connection-updated'))
|
|
// The post-connect refresh (skattekonto sync, AGI settle, token
|
|
// health) now runs server-side AFTER the callback responds, so the
|
|
// status fetched above predates it. Refetch once more when it has
|
|
// plausibly settled so synced data and health flags (e.g.
|
|
// MISSING_SCOPE) show up without a manual reload.
|
|
if (delayedRefetchRef.current) clearTimeout(delayedRefetchRef.current)
|
|
delayedRefetchRef.current = setTimeout(() => {
|
|
loadStatus()
|
|
window.dispatchEvent(new CustomEvent('skatteverket-connection-updated'))
|
|
}, 15_000)
|
|
} else if (event.data?.type === 'skatteverket-oauth-error') {
|
|
stopWatchingOauthTab()
|
|
toast({
|
|
title: tOauth('connect_failed_title'),
|
|
description:
|
|
typeof event.data.reason === 'string' && event.data.reason
|
|
? event.data.reason
|
|
: undefined,
|
|
variant: 'destructive',
|
|
})
|
|
}
|
|
}
|
|
window.addEventListener('message', handleMessage)
|
|
return () => window.removeEventListener('message', handleMessage)
|
|
}, [loadStatus, stopWatchingOauthTab, toast, tOauth])
|
|
|
|
function startConnect() {
|
|
// Open the BankID OAuth flow in a NEW TAB, not a popup. The old 600x750
|
|
// popup could not fit Skatteverket's consent page: the approve button
|
|
// sat below the fold and users got stranded mid-consent. A tab gets the
|
|
// full viewport (and behaves natively on mobile). The callback page
|
|
// detects `window.opener`, posts back a message and closes itself: the
|
|
// settings page never navigates, so browser history stays clean and
|
|
// closing the settings afterwards cannot walk Back into the consumed
|
|
// OAuth chain (the "redirected to Skatteverket again" bug).
|
|
const returnTo = encodeURIComponent('/settings/tax')
|
|
const url = `/api/extensions/ext/skatteverket/authorize?return_to=${returnTo}`
|
|
const tab = window.open(url, '_blank')
|
|
popupRef.current = tab
|
|
if (!tab) {
|
|
// Tab blocked: fall back to the full-page flow. The callback then
|
|
// lands on /settings/tax?skv_connected=true, handled by
|
|
// TaxSettingsContent's query-param effect.
|
|
window.location.href = url
|
|
return
|
|
}
|
|
setConnecting(true)
|
|
// Detect abandonment: if the tab goes away without posting a message
|
|
// (closed manually, stranded on Skatteverket's side), re-enable the
|
|
// button and refresh status. This also fires after a successful
|
|
// self-close; the extra status fetch is harmless.
|
|
if (watchTimerRef.current) clearInterval(watchTimerRef.current)
|
|
watchTimerRef.current = setInterval(() => {
|
|
if (popupRef.current?.closed) {
|
|
stopWatchingOauthTab()
|
|
loadStatus()
|
|
}
|
|
}, 1000)
|
|
}
|
|
|
|
async function disconnect() {
|
|
// No disconnect while an OAuth tab is in flight: the callback completing
|
|
// right after the disconnect would silently recreate the tokens.
|
|
if (connecting) return
|
|
setDisconnecting(true)
|
|
try {
|
|
const res = await fetch('/api/extensions/ext/skatteverket/disconnect', {
|
|
method: 'POST',
|
|
})
|
|
if (!res.ok) throw new Error(t('disconnect_failed'))
|
|
toast({ title: t('toast_disconnected') })
|
|
await loadStatus()
|
|
// Connection state changed: notify passive consumers via the same
|
|
// internal event as a verified OAuth success.
|
|
window.dispatchEvent(new CustomEvent('skatteverket-connection-updated'))
|
|
} catch (err) {
|
|
toast({
|
|
title: t('toast_disconnect_failed'),
|
|
description: err instanceof Error ? getUserErrorMessage(err) : undefined,
|
|
variant: 'destructive',
|
|
})
|
|
} finally {
|
|
setDisconnecting(false)
|
|
}
|
|
}
|
|
|
|
// Static connect guidance lives behind the "?": what the connection is
|
|
// used for, plus the consent-page instructions ("godkänn alla
|
|
// behörigheter", the ska/skahmst explainer). The consent notes only matter
|
|
// when the user can actually reach the consent page: hidden while the
|
|
// feature is entitlement-gated.
|
|
const connectHelp = (
|
|
<div className="space-y-2">
|
|
<p>{t('connect_intro')}</p>
|
|
{hasSkatteverket && (
|
|
<>
|
|
<p>{t('connect_approve_all')}</p>
|
|
<p>
|
|
{t.rich('skahmst_note', {
|
|
code: (chunks) => <span className="font-mono">{chunks}</span>,
|
|
})}
|
|
</p>
|
|
</>
|
|
)}
|
|
</div>
|
|
)
|
|
|
|
if (loading) {
|
|
return (
|
|
<SettingsGroup>
|
|
<SettingsRow label={
|
|
<span className="inline-flex items-center gap-2">
|
|
<Image src="/logos/skatteverket.svg" alt="" aria-hidden="true" width={14} height={14} className="dark:invert" />
|
|
{t('title')}
|
|
</span>
|
|
} help={connectHelp} borderless>
|
|
<SettingsRowNote>{t('loading_status')}</SettingsRowNote>
|
|
</SettingsRow>
|
|
</SettingsGroup>
|
|
)
|
|
}
|
|
|
|
if (!status?.connected) {
|
|
return (
|
|
<SettingsGroup>
|
|
{status?.disabled && <WarningLine>{t('disabled_message')}</WarningLine>}
|
|
<SettingsRow label={
|
|
<span className="inline-flex items-center gap-2">
|
|
<Image src="/logos/skatteverket.svg" alt="" aria-hidden="true" width={14} height={14} className="dark:invert" />
|
|
{t('title')}
|
|
</span>
|
|
} help={connectHelp} borderless={!hasSkatteverket}>
|
|
<EnvironmentBadge environment={status?.environment} disabled={status?.disabled} />
|
|
<SettingsRowEnd>
|
|
<Button
|
|
size="sm"
|
|
onClick={startConnect}
|
|
disabled={status?.disabled || !hasSkatteverket || connecting}
|
|
title={
|
|
!hasSkatteverket
|
|
? isSelfHosted()
|
|
? 'Anslutning till Skatteverket kräver en connector-nyckel eller egna API-uppgifter'
|
|
: 'Anslutning till Skatteverket kräver ett abonnemang'
|
|
: undefined
|
|
}
|
|
>
|
|
<ExternalLink className="mr-2 h-4 w-4" />
|
|
{connecting ? t('connect_waiting') : t('connect_with_bankid')}
|
|
</Button>
|
|
</SettingsRowEnd>
|
|
</SettingsRow>
|
|
{!hasSkatteverket && (
|
|
<div className="px-1 py-3">
|
|
<UpgradeNote>Anslutning till Skatteverket kräver ett abonnemang.</UpgradeNote>
|
|
</div>
|
|
)}
|
|
</SettingsGroup>
|
|
)
|
|
}
|
|
|
|
const scopes = (status.scope || '').split(/\s+/).filter(Boolean)
|
|
const expiresAtDate = new Date(status.expiresAt)
|
|
const expiresInMinutes = Math.round(
|
|
(expiresAtDate.getTime() - Date.now()) / 60_000,
|
|
)
|
|
|
|
return (
|
|
<SettingsGroup>
|
|
{status.needsReconsent && (
|
|
<WarningLine>
|
|
{/* MISSING_SCOPE right after a connect means the user skipped a
|
|
behörighet on SKV's consent page; tell them exactly that
|
|
instead of the generic "session expired" prompt. */}
|
|
{status.lastErrorCode === 'MISSING_SCOPE'
|
|
? t('missing_scope_message')
|
|
: t('needs_reconsent_message')}
|
|
</WarningLine>
|
|
)}
|
|
|
|
<SettingsRow label={
|
|
<span className="inline-flex items-center gap-2">
|
|
<Image src="/logos/skatteverket.svg" alt="" aria-hidden="true" width={14} height={14} className="dark:invert" />
|
|
{t('title')}
|
|
</span>
|
|
} help={connectHelp}>
|
|
{status.expired ? (
|
|
<Badge variant="warning">{t('expired')}</Badge>
|
|
) : (
|
|
<Badge variant="success">
|
|
<CheckCircle2 className="mr-1 h-3 w-3" />
|
|
{t('connected')}
|
|
</Badge>
|
|
)}
|
|
<EnvironmentBadge environment={status.environment} disabled={status.disabled} />
|
|
<SettingsRowEnd>
|
|
{/* `ska` gates the interactive skattekonto API (saldo +
|
|
transaktioner); a grant without it cannot sync, so offer the
|
|
reconnect even while the token is otherwise healthy. */}
|
|
{(status.expired || status.needsReconsent || !status.canRefresh || !scopes.includes('ska') || !scopes.includes('agd')) && (
|
|
<Button
|
|
size="sm"
|
|
onClick={startConnect}
|
|
disabled={status.disabled || !hasSkatteverket || connecting}
|
|
title={
|
|
!hasSkatteverket
|
|
? isSelfHosted()
|
|
? 'Anslutning till Skatteverket kräver en connector-nyckel eller egna API-uppgifter'
|
|
: 'Anslutning till Skatteverket kräver ett abonnemang'
|
|
: undefined
|
|
}
|
|
>
|
|
<ExternalLink className="mr-2 h-4 w-4" />
|
|
{connecting ? t('connect_waiting') : t('reconnect')}
|
|
</Button>
|
|
)}
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={disconnect}
|
|
disabled={disconnecting || connecting}
|
|
>
|
|
<ShieldOff className="mr-2 h-4 w-4" />
|
|
{disconnecting ? t('disconnecting') : t('disconnect')}
|
|
</Button>
|
|
</SettingsRowEnd>
|
|
</SettingsRow>
|
|
|
|
<SettingsRow label={t('token_expires_label')}>
|
|
<SettingsRowNote className="tabular-nums">
|
|
{expiresAtDate.toLocaleString('sv-SE')}
|
|
{!status.expired && expiresInMinutes > 0 && (
|
|
<> {t('expires_in_minutes', { minutes: expiresInMinutes })}</>
|
|
)}
|
|
</SettingsRowNote>
|
|
</SettingsRow>
|
|
|
|
<SettingsRow label={t('refresh_label')}>
|
|
<SettingsRowNote>
|
|
{status.canRefresh ? t('refresh_auto') : t('refresh_exhausted')}
|
|
</SettingsRowNote>
|
|
</SettingsRow>
|
|
|
|
<SettingsRow label={t('permissions_label')}>
|
|
<div className="flex flex-wrap gap-2">
|
|
{scopes.map(s => (
|
|
<Badge key={s} variant="outline">
|
|
{SCOPE_LABELS[s] ?? s}
|
|
</Badge>
|
|
))}
|
|
</div>
|
|
</SettingsRow>
|
|
|
|
{/* `ska` is the scope the interactive skattekonto API enforces;
|
|
skahmst (bulk E-transport service) does not substitute for it.
|
|
Missing scopes are actionable state: keep them visible. */}
|
|
{!scopes.includes('ska') && <WarningLine>{t('missing_skattekonto')}</WarningLine>}
|
|
{!scopes.includes('agd') && <WarningLine>{t('missing_agd')}</WarningLine>}
|
|
{status.disabled && <WarningLine>{t('disabled_filings_message')}</WarningLine>}
|
|
</SettingsGroup>
|
|
)
|
|
}
|
|
|
|
type GrantStatus = 'unknown' | 'granted' | 'denied' | 'error'
|
|
|
|
interface SystemConnectionState {
|
|
available: boolean
|
|
mode?: string
|
|
environment?: string
|
|
ombud_org_number?: string | null
|
|
grant_url?: string
|
|
cert?: { notAfter: string; daysUntilExpiry: number; expiresSoon: boolean } | null
|
|
connection?: {
|
|
status: string
|
|
lasombud_status: GrantStatus
|
|
moms_ombud_status: GrantStatus
|
|
verified_at: string | null
|
|
last_probe_at: string | null
|
|
} | null
|
|
}
|
|
|
|
/**
|
|
* The system (ombud + organization certificate) connection: the one-time
|
|
* grant that lets background syncs run without a personal BankID session.
|
|
* Renders nothing until SKATTEVERKET_SYSTEM_AUTH_MODE is switched on
|
|
* server-side, so the whole section is invisible during Phase 1.
|
|
*/
|
|
function SkatteverketSystemConnectionCard() {
|
|
const t = useTranslations('settings_skatteverket_connect')
|
|
const { appName } = useBranding()
|
|
const { toast } = useToast()
|
|
const [state, setState] = useState<SystemConnectionState | null>(null)
|
|
const [verifying, setVerifying] = useState(false)
|
|
|
|
async function loadState() {
|
|
try {
|
|
const res = await fetch('/api/extensions/ext/skatteverket/system-connection')
|
|
if (!res.ok) {
|
|
setState({ available: false })
|
|
return
|
|
}
|
|
setState((await res.json()) as SystemConnectionState)
|
|
} catch {
|
|
setState({ available: false })
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
loadState()
|
|
}, [])
|
|
|
|
async function verify() {
|
|
setVerifying(true)
|
|
try {
|
|
const res = await fetch('/api/extensions/ext/skatteverket/system-connection/verify', {
|
|
method: 'POST',
|
|
})
|
|
const body = await res.json().catch(() => ({}))
|
|
if (res.status === 429) {
|
|
toast({ title: t('system_verify_rate_limited') })
|
|
return
|
|
}
|
|
if (!res.ok) {
|
|
toast({
|
|
title: t('system_verify_failed'),
|
|
description: typeof body?.error === 'string' ? body.error : undefined,
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
await loadState()
|
|
} catch {
|
|
toast({ title: t('system_verify_failed'), variant: 'destructive' })
|
|
} finally {
|
|
setVerifying(false)
|
|
}
|
|
}
|
|
|
|
if (!state?.available) return null
|
|
|
|
const grantBadge = (status: GrantStatus | undefined) => {
|
|
switch (status) {
|
|
case 'granted':
|
|
return (
|
|
<Badge variant="success">
|
|
<CheckCircle2 className="mr-1 h-3 w-3" />
|
|
{t('system_status_granted')}
|
|
</Badge>
|
|
)
|
|
case 'denied':
|
|
return <Badge variant="destructive">{t('system_status_denied')}</Badge>
|
|
case 'error':
|
|
return <Badge variant="warning">{t('system_status_error')}</Badge>
|
|
default:
|
|
return <Badge variant="outline">{t('system_status_unknown')}</Badge>
|
|
}
|
|
}
|
|
|
|
return (
|
|
<SettingsGroup label={t('system_title')} help={t('system_intro', { appName })}>
|
|
{state.ombud_org_number && (
|
|
<SettingsRow label={t('system_org_label')}>
|
|
<span className="font-mono text-sm tabular-nums">{state.ombud_org_number}</span>
|
|
</SettingsRow>
|
|
)}
|
|
|
|
<SettingsRow label={t('system_behorighet_lasombud')}>
|
|
{grantBadge(state.connection?.lasombud_status)}
|
|
</SettingsRow>
|
|
<SettingsRow label={t('system_behorighet_moms')}>
|
|
{grantBadge(state.connection?.moms_ombud_status)}
|
|
</SettingsRow>
|
|
|
|
{state.cert?.expiresSoon && (
|
|
<WarningLine>
|
|
{t('system_cert_expires_soon', { days: state.cert.daysUntilExpiry, appName })}
|
|
</WarningLine>
|
|
)}
|
|
|
|
<div className="flex flex-wrap items-center gap-4 px-1 py-3">
|
|
{state.grant_url && (
|
|
<a
|
|
href={state.grant_url}
|
|
target="_blank"
|
|
rel="noopener noreferrer"
|
|
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground transition-colors duration-150 hover:text-foreground"
|
|
>
|
|
<ExternalLink className="h-3.5 w-3.5" />
|
|
{t('system_open_ombud')}
|
|
</a>
|
|
)}
|
|
<Button size="sm" onClick={verify} disabled={verifying}>
|
|
{verifying && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
|
{verifying ? t('system_verifying') : t('system_verify')}
|
|
</Button>
|
|
</div>
|
|
</SettingsGroup>
|
|
)
|
|
}
|
|
|
|
function EnvironmentBadge({ environment, disabled }: { environment?: Environment; disabled?: boolean }) {
|
|
const t = useTranslations('settings_skatteverket_connect')
|
|
if (disabled) {
|
|
return (
|
|
<Badge variant="destructive">
|
|
<ShieldAlert className="mr-1 h-3 w-3" />
|
|
{t('env_disabled')}
|
|
</Badge>
|
|
)
|
|
}
|
|
if (environment === 'test') {
|
|
return (
|
|
<Badge variant="warning">
|
|
<FlaskConical className="mr-1 h-3 w-3" />
|
|
{t('env_test')}
|
|
</Badge>
|
|
)
|
|
}
|
|
if (environment === 'prod') {
|
|
return (
|
|
<Badge variant="success">
|
|
{t('env_prod')}
|
|
</Badge>
|
|
)
|
|
}
|
|
return null
|
|
}
|