Files
accounted/components/settings/SkatteverketConnectPanel.tsx
T
Mattsson fdb5f6f891 feat(white-label): byra white-label infrastructure: brands, cockpit, home domains, branded email (#1956)
* feat(white-label): brand and team-kind foundation

- brands table: one white-label identity per byra team (unique mutable
  domain, row presence = live, email sender identity, hex color CHECKs)
- teams.kind ('personal'|'byra'): ops-only kind changes, deterministic
  ensure_user_team (personal team only), AFTER UPDATE role re-sync so a
  demoted consultant loses admin in client books immediately
- resolveBrandByHost/resolveBrandForCompany with 60s TTL cache, derived
  chrome tone and WCAG contrast gate; no brand row = default appearance

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(white-label): per-request brand theming, wordmark slot and source footer

- root layout resolves the brand from the Host header and injects a
  server-rendered style block (light + dark), font pair classes and a
  BrandProvider/useBranding context; default hosts render byte-identically
- BrandWordmark logo slot, host-aware manifest and favicon,
  images.remotePatterns for Supabase Storage logos
- curated font menu mechanism (font_key -> variable pair, preload:false
  for non-default entries)
- AGPL source-code footer link on login and public pages, both brands

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(white-label): byra team invites, member management and team billing

- team invites unfrozen behind a kind gate (byra teams only, owner/admin
  invite); members route handles multi-team membership; members/[id]
  unfrozen with last-owner protection; invite management UI in settings
- billing/status learns team-scoped grants and the settings page shows a
  read-only "part of the byra agreement" state instead of the upgrade pitch
- 30-day trial suppressed for companies created under a byra team

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(white-label): brand-aware outbound mail, auth email hook and public invoice branding

- every outbound mail is sent in the brand of the company it concerns:
  getSenderForCompany/getBaseUrlForCompany chain (verified brand domain,
  "via Accounted" fallback, canonical default) wired into invites,
  payslips, invoice deliveries and reminders
- Supabase Send Email hook endpoint (signature-verified with node:crypto,
  dormant until configured) renders auth mail per brand via redirect origin
- public invoice pages carry the company's brand mark
- snapshot suite per template class guards against wrong-brand mail

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(white-label): byra cockpit, home-domain rule and tab guard

- Klienter route: five urgency-sorted columns (company, unbooked, inbox,
  next deadline via the status engine, last booked) for byra team members,
  who land there after login on their home domain
- soft switch straight into a client and back; blocking two-exit tab
  guard against writes to the wrong active company
- client company creation admin-gated at the DB level (a created company
  is +1 on the byra invoice), bound to the byra team, no trial
- home-domain rule in the UI: switcher partitions companies by host,
  signpost page for companies homed elsewhere

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(white-label): brand-aware app name across UI strings

- 24 message keys per locale converted to the {appName} ICU parameter,
  27 call sites pass the active brand name (useBranding client-side,
  getRequestAppName server-side)
- 6 hardcoded JSX literals swept; statutory filing and API identity
  surfaces deliberately keep the Accounted name
- 34 new i18n keys for the cockpit, team invites, billing state, tab
  guard, signpost and source footer (sv/en parity verified)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs(white-label): domain glossary and decision log entries

- CONTEXT.md: the white-label ubiquitous language (brand, byra team,
  home domain, signpost, umbrella subdomain, brand color, cockpit)
- DECISIONS.md entries from the build waves

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(white-label): lean byra cockpit sidebar with company-mode back link

Byra team members now get a two-mode sidebar: on cockpit routes (/clients
and the new /byra pages) only Hem, Klienter, Automationer and Nyckeltal
show; entering a client company brings back the full company sidebar with
a pinned back-to-clients link (expanded, rail and mobile). New pages: /byra
home with client count, needs-action count and per-client urgent deadlines
reusing the fetchClientOverview aggregation, plus designed empty states for
/byra/automations and /byra/kpi. Signpost gate allows the byra routes;
non-byra users are unaffected.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(white-label): cockpit shows no active company and keeps lean sidebar under settings

In cockpit mode the bottom user widget no longer shows the active company
subline or the company-switcher flyout: the cockpit sits above the
companies and clients are entered through the Klienter list. The settings
modal previously flipped the sidebar to the full company nav behind it
because the pathname becomes /settings/*; the sidebar now keeps the mode
of the surface underneath.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(white-label): keep company picker in cockpit with nothing selected

The cockpit user menu gets the company-switcher flyout back, but neutral:
the row reads "Valj bolag", no company carries the check mark or active
styling, and picking any company (including the technically-active one)
enters it with a full navigation. Company mode is unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(db): renumber white-label migrations past main and add byra settings scope

Renumber 20260801100000-120000 to 20260804110000-113000: main already
carries applied versions up to 20260803231000, and Supabase branching
refuses local migrations stamped before the remote head (the repo rule
from 5932632f5: keep new versions strictly newest). Comment references
updated in the pg tests, route docs and onboarding precheck.

Also ships the byra settings scope: settings opened from the cockpit
(?ctx=byra, honored only for byra team members) show account-level
sections only (Konto, Medlemmar och roller), hide company-scoped
sections and the company kicker, and the team section is registered in
SETTINGS_SECTIONS so Medlemmar och roller renders inside the settings
window. The cockpit user menu drops Abonnemang and carries the scope on
its links; section switches preserve it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(byra): cross-client nyckeltal view in the cockpit

Period presets and company chips in the URL, summary tiles, merged
monthly income/expense chart and a sortable per-client KPI table.
Numbers come from the existing get_kpi_report_aggregates RPC per
client (no new migrations); calendar months are the cross-client
axis since clients can have different fiscal years.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(white-label): byra self-service brand logo and app name

New Varumarke settings section (byra scope, owner/admin): logo
upload/remove and an editable app name; domain stays read-only.
brands has no write RLS by design, so writes go through
/api/byra/brand routes with the service client behind an explicit
owner/admin team check. Files land in logos/byra/{teamId}/. The
expanded sidebar shows the brand app name beside the logo.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(white-label): route root layout through the shared brand resolver

app/layout.tsx carried a private copy of resolveRequestBrand, so it
and lib/branding/request-brand.ts could drift. The layout now uses
the shared function, which also gains a BRAND_DEV_DOMAIN override:
on literal localhost hosts only, resolve that brand so branding is
testable in local dev. Real domains are unaffected even if the
variable leaks into a deployment.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(byra): automations roadmap teaser and cockpit i18n strings

The Automationer tab now previews the planned automation set
(Monday briefing, deadline watch, rule-driven bookkeeping,
connection watch, monthly checklist, report delivery) instead of a
bare empty state. Bundles the sv/en strings for the whole cockpit
wave (nyckeltal, varumarke, automations) and the decision-log
entries.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(white-label): byra owners/admins land in the cockpit, not an auto-picked company

After login "/" resolved the first-membership fallback and opened a client
company nobody chose, and the top-left brand mark always linked back to it.
Byra owners/admins now home to /byra: the logo links there always, and "/"
redirects there unless a company was explicitly picked this browser session.

The middleware writes the fallback company back to user_preferences, so the
DB cannot tell picked from auto-picked; setActiveCompany stamps a session
cookie (gnubok-company-picked) on every explicit switch instead. The byra
check on "/" reuses the layout's team_members query via a request-cached
helper, so it costs no extra round trip. Byra members and regular users are
unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(white-label): drop brand color theming, keep monochrome everywhere

White-label is logo + app name + domain only (founder call): the
layout no longer injects brand color CSS variables, stamps
data-brand or colors the browser chrome. buildBrandVarsCss, its
WCAG gate and the brand_color/chrome_color columns stay dormant
for a future opt-in.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(db): arm SIE RPC statement_timeout via pgrst.db_pre_request hook

ALTER FUNCTION ... SET statement_timeout (20260629160100, 20260721144311)
never re-arms the running statement's timer, so large SIE imports still
died at the role default 8s. The pre-request hook runs as its own
statement before the main query, so set_config there is what the main
statement's timer is armed with. Scoped by request path to the three SIE
RPCs; every other request keeps 8s.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(byra): drop the 'what's coming' tail from the automations intro

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(white-label): byra owners/admins with zero companies land in the empty cockpit

Both no-company gates (Edge middleware and the dashboard layout) sent
every company-less user to the onboarding wizard, which forced a fresh
byra owner to create a personal company before ever seeing the cockpit.
Byra owners/admins now pass through to cockpit routes (/byra, /clients,
/companies/new, /settings, /api) and are steered to /byra elsewhere.
Plain byra members and regular users keep the onboarding redirect.
The membership lookup runs only in the rare no-company state, so the
middleware hot path is untouched.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(white-label): auth wordmark shows the brand logo alone

Byra logos usually carry their own name, so logo + app name text on the
login/register hero read as a duplicate. Branded hosts with an uploaded
logo now render the logo only, with the app name as the image's alt
text. Hosts without a logo keep the text wordmark unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(white-label): per-brand favicon via brands.favicon_url

Branded hosts used logo_url as the tab icon, which squashes wide byra
lockups at 16px. New optional brands.favicon_url holds a square mark;
the root layout prefers it and falls back to logo_url as before.
Migration applied to staging (idempotent DDL).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(auth): wire the villkor and integritetspolicy footer links

Both auth pages shipped with href="#" placeholders. Villkor now points
at the platform terms on the marketing site (accounted.se/terms; the
terms are the platform's even on branded byra hosts) and
integritetspolicy at the in-app /privacy page, host-relative so it
resolves on every branded domain. Both open in a new tab so the auth
form state survives.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(settings): styled popup for the team role dropdowns

The byra team panel's role pickers (member rows + invite form) were
native selects, so the opened list rendered as the unstylable OS menu.
Swapped to the Radix Select with the popup styled like every other
overlay; the trigger keeps the flat quiet SettingsSelect look.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(email): branded sender shows the brand name alone, no via-platform

Byra invite mail read "Willem via Accounted" in the From display name.
The tier-2 fallback (brand on the platform address) now renders just the
brand name; the platform stays visible in the actual From address until
the brand verifies its own sender domain (tier 1, unchanged).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(white-label): byra landing applies to every team member, not only owners/admins

An invited byra consultant (role member) still landed in an auto-picked
client company after signup. The cockpit landing rules ("/" redirect,
brand-mark home link, and both no-company gates) now key on byra team
MEMBERSHIP instead of the owner/admin role: anyone with cockpit access
homes to /byra. Regular users unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(email): branded team invite names the byra, not "ett team pa <platform>"

Subject, headline, body and text variant now read "Du har blivit
inbjuden till <Byra>" (brand casing kept) when the team has a brand.
Brandless teams keep the platform phrasing byte-identical.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(white-label): sidebar keeps cockpit mode after refresh on settings

The sidebar's cockpit/company decision on /settings/* rested on React
state remembering the surface underneath, which a hard reload wipes: a
byra user refreshing settings opened from the cockpit got the full
company nav and read it as landing in a client company. The ?ctx=byra
marker already in the URL survives reloads, so the sidebar now honors
it as the cockpit signal alongside the in-session memory.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(white-label): hide the active-company chip in byra-scoped settings

The full-page settings header (the hard-refresh fallback surface) showed
the ActiveCompanyBadge even under ?ctx=byra, so a byra user read the
auto-active client as "the company I am in". The chip now follows the
same byra-scope rule as the modal's kicker.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(white-label): tab guard no longer fires in the tab that initiated the switch

BroadcastChannel delivers the company-switch broadcast to every listener in
the same tab too, so the cockpit tab raised its own WL-09 "switched in
another tab" dialog over the hard navigation into the clicked client.
performCompanySwitch now marks the switch as self-initiated; CompanyTabSync
suppresses only the dialog for that observation (stray writes still get
their 409) and clears the marker on bfcache restore so back-navigation
regains the full guard.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(settings): styled popups for every settings dropdown

SettingsSelect rendered a native <select>, whose OS listbox cannot be
styled and clashes with the panel (same problem the team-panel role
dropdowns had). It now renders through Radix Select with the flat
dashed-underline trigger, keeping the native prop surface so all 13 call
sites work unchanged: value/defaultValue, onChange(e.target.value),
<option> children, and a hidden input that carries `name` into
SettingsFormWrapper's FormData read and raises the bubbling input event
its dirty tracking listens for. Empty-string option values map onto a
sentinel at the Radix boundary. The backup form's boxed fiscal-year
select moves to the shadcn Select with a placeholder.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(white-label): home-domain affinity redirect in middleware

Every signed-in user now homes on a domain: byra team members on their
brand's domain, everyone else on the platform app URL, except a byra's
client users, whose home is the byra domain their companies live under.
On any other product host the request redirects to the home domain's
root, where the user meets the RIGHT branded login (sessions are
per-domain by design). localhost, direct *.vercel.app hosts and IP
hosts are exempt; a 15-minute host-scoped cookie caches the "this is
home" verdict so the hot path costs zero extra queries; lookup failures
fail open. Complements the WL-01 signpost, which keeps handling
per-company homing inside a domain.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(white-label): render hero brand logo at 64px on auth pages

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(white-label): shareable invite link and re-send for byra team invites

A failed invite mail previously surfaced only as a toast description while
the invitation quietly waited for a mail that never arrived (the Arbore
case). The inviter now always has a recovery path:

- persistent share-link line after invite create/re-send: ochre attn line
  with a copy action when the mail did not go out, quiet muted line with
  the same action when it did
- POST /api/team/invite/[id] re-sends a pending invitation with a fresh
  token and expiry (same byra-only owner/admin gates as DELETE)
- brand mail sending extracted to lib/email/send-team-invite.ts, shared
  by create and re-send so the two paths cannot drift

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(white-label): sidebar shows uploaded brand logo alone, no app-name label

Byra logos usually carry their own name, so logo + text in the expanded
sidebar read as a duplicate (same founder call as BrandWordmark,
2026-08-05). The app-name label now renders only for branded hosts
without an uploaded logo.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(white-label): close the four skeptic refutations before merge

- trial seed: migration 130300 now carries the seven-key PAID body from
  20260818170000 plus the byra guard, instead of silently reverting it;
  pg test pins the full key set against PAID_CAPABILITIES
- byra gate: new migration 130600 adds the owner/admin gate to
  create_company_for_user (v1 API + MCP path), and both surfaces resolve
  the default team personal-only, so a consultant's private company can
  never attach to the byra team
- home-domain: byra staff who also have canonical-homed companies are no
  longer redirected off the platform host; the signpost handles per-company
  homing (5 new middleware tests)
- settings selects: the Radix popup renders optgroup group headers again
  (ROT/RUT work-type picker)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(schema): re-baseline unresolvable-expression ceiling after #1954 catch-up merge

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(white-label): pg-real rollback-safe assertions and deep-link-preserving affinity redirect

The byra company-creation pg test asserted persisted rows through the pool
after withUserContext, which always rolls back its transaction; the
assertions now run inside the transaction after RESET ROLE. The home-domain
affinity redirect carries the original path and query across the domain hop
(PR Agent finding), so invite links and deep links survive the correction.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-26 16:56:39 +02:00

584 lines
21 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 { 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 ? '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 ? '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
}