Add/customer mcp (#1055)

* feat(mcp): kontoplan account tools + verifikat notes exposure

Two gaps reported by an MCP-driven user: no account management in the
API, and verifikat notes invisible to agents (they exist in the product
but MCP could neither read nor write them).

- add staged gnubok_create_account / gnubok_update_account (BAS 2026
  prefill for catalog numbers; rename/VAT-default/SRU/activate via
  update; both LOW risk reference data)
- add staged gnubok_set_voucher_note (notes-only annotation, legal on
  posted entries per the 20260608120000 trigger carve-out) and return
  entry_notes from gnubok_query_journal
- new pending_operations types create_account / update_account /
  set_voucher_note (CHECK migration + validate companion, applied to
  staging)
- tools/list payload ceiling 54K -> 56K (documented; wire contract,
  descriptions trimmed first)

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

* fix(skatteverket): unstick BankID connect flow and stale connection views

- respond to the OAuth callback immediately and run the post-connect
  refresh after the response (next/server after()): users no longer
  stare at Skatteverket's consumed consent page for up to 40s
- open the consent flow in a full tab instead of a 600x750 popup that
  hid the approve button below the fold
- disable connect buttons while the OAuth tab is open (parallel flows
  overwrote oauth_state + the PKCE verifier) and recover via a
  closed-tab watcher plus a delayed status refetch
- persist MISSING_SCOPE token health from the post-connect sync and
  show an actionable "approve all permissions" notice
- refetch connection state on tab visibility (settings connect panel,
  enable-banking panel, /skattekonto) so a connect completed in another
  tab or after a mobile app-switch shows up without a manual reload;
  fix /skattekonto never clearing its not-connected state

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

* feat(article-form): add article number field with validation to ArticleForm

* feat(account): enforce account type consistency with BAS class and add validation

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-07-17 14:13:53 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent bfd5b42eb1
commit 0e9cca2750
28 changed files with 1944 additions and 101 deletions
+35 -17
View File
@@ -131,6 +131,7 @@ export default function ArticleForm({
const schema = useMemo(
() =>
z.object({
article_number: z.string().trim().max(64, t('number_too_long')).optional(),
name: z.string().min(1, t('name_required')),
name_en: z.string().optional(),
type: z.enum(['vara', 'tjanst']),
@@ -161,6 +162,7 @@ export default function ArticleForm({
} = useForm<FormData>({
resolver: zodResolver(schema),
defaultValues: {
article_number: initialData?.article_number || '',
name: initialData?.name || '',
name_en: initialData?.name_en || '',
type: initialData?.type || 'tjanst',
@@ -180,6 +182,7 @@ export default function ArticleForm({
const onFormSubmit = (data: FormData) => {
onSubmit({
article_number: data.article_number?.trim() || null,
name: data.name,
name_en: data.name_en || null,
type: data.type,
@@ -197,24 +200,39 @@ export default function ArticleForm({
return (
<form onSubmit={handleSubmit(onFormSubmit)} className="space-y-6">
{/* Type */}
<div className="space-y-2">
<Label>{t('type_label')}</Label>
<Controller
name="type"
control={control}
render={({ field }) => (
<Select value={field.value} onValueChange={(v) => { if (v) field.onChange(v) }}>
<SelectTrigger>
<SelectValue placeholder={t('type_placeholder')} />
</SelectTrigger>
<SelectContent>
<SelectItem value="vara">{t('type_vara')}</SelectItem>
<SelectItem value="tjanst">{t('type_tjanst')}</SelectItem>
</SelectContent>
</Select>
{/* Type + article number */}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label>{t('type_label')}</Label>
<Controller
name="type"
control={control}
render={({ field }) => (
<Select value={field.value} onValueChange={(v) => { if (v) field.onChange(v) }}>
<SelectTrigger>
<SelectValue placeholder={t('type_placeholder')} />
</SelectTrigger>
<SelectContent>
<SelectItem value="vara">{t('type_vara')}</SelectItem>
<SelectItem value="tjanst">{t('type_tjanst')}</SelectItem>
</SelectContent>
</Select>
)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="article_number">{t('number_label')}</Label>
<Input
id="article_number"
className="tabular-nums"
{...register('article_number')}
/>
{errors.article_number ? (
<p className="text-sm text-destructive">{errors.article_number.message}</p>
) : (
<p className="text-xs text-muted-foreground">{t('number_hint')}</p>
)}
/>
</div>
</div>
{/* Name */}
+72 -27
View File
@@ -150,6 +150,11 @@ export function AGIPanel(props: AGIPanelProps) {
const [success, setSuccess] = useState<string | null>(null)
const [chain, setChain] = useState<ChainProgress | null>(null)
const [showAdvanced, setShowAdvanced] = useState(false)
// True while an OAuth tab opened from this panel is still alive. Disables
// the connect buttons 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)
// "2026-06" for user-facing copy; the period prop is compact YYYYMM.
const prettyPeriod = `${period.slice(0, 4)}-${period.slice(4)}`
@@ -213,9 +218,26 @@ export function AGIPanel(props: AGIPanelProps) {
fetchStatus()
}, [fetchStatus])
// Handle of the OAuth popup opened by handleConnect: used to verify the
// sender identity of incoming postMessages.
// Handle of the OAuth tab opened by handleConnect: 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)
}
}, [])
// Listen for OAuth completion from the BankID popup. When the popup posts
// back a success/error message we re-fetch status so the panel flips from
@@ -228,6 +250,7 @@ export function AGIPanel(props: AGIPanelProps) {
// same-origin scripts.
if (!popupRef.current || event.source !== popupRef.current) return
if (event.data?.type === 'skatteverket-oauth-success') {
stopWatchingOauthTab()
setError(null)
setSuccess(t('oauth_success'))
fetchStatus()
@@ -235,7 +258,18 @@ export function AGIPanel(props: AGIPanelProps) {
// 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 show up
// without a manual reload.
if (delayedRefetchRef.current) clearTimeout(delayedRefetchRef.current)
delayedRefetchRef.current = setTimeout(() => {
fetchStatus()
window.dispatchEvent(new CustomEvent('skatteverket-connection-updated'))
}, 15_000)
} else if (event.data?.type === 'skatteverket-oauth-error') {
stopWatchingOauthTab()
const reason =
typeof event.data.reason === 'string' && event.data.reason
? event.data.reason
@@ -245,7 +279,7 @@ export function AGIPanel(props: AGIPanelProps) {
}
window.addEventListener('message', handleMessage)
return () => window.removeEventListener('message', handleMessage)
}, [fetchStatus, t])
}, [fetchStatus, stopWatchingOauthTab, t])
// Drop a stale "AGI-XML saknas" error once the run's AGI is (re)generated.
// That error is set when "Skicka in underlag" runs before the XML exists; if
@@ -377,6 +411,9 @@ export function AGIPanel(props: AGIPanelProps) {
}, [submission?.status, checkKvittens])
const handleDisconnect = useCallback(async () => {
// No disconnect while an OAuth tab is in flight: the callback completing
// right after the disconnect would silently recreate the tokens.
if (connecting) return
setActionLoading('disconnect')
setError(null)
setSuccess(null)
@@ -397,35 +434,43 @@ export function AGIPanel(props: AGIPanelProps) {
} finally {
setActionLoading(null)
}
}, [fetchStatus, onRefreshSubmission, t])
}, [connecting, fetchStatus, onRefreshSubmission, t])
const handleConnect = () => {
// Open the BankID OAuth flow in a centered popup. The callback page
// 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` and posts back a `skatteverket-oauth-success`
// (or `-error`) message, then closes itself: see the postMessage
// listener below. `return_to` is still passed so the popup-less fallback
// path (e.g. popup blockers) lands on the salary run page rather than
// the default /reports tab.
// listener below. `return_to` is still passed so the tab-blocked
// fallback path lands on the salary run page rather than the default
// /reports tab.
const returnTo = typeof window !== 'undefined'
? window.location.pathname + window.location.search
: ''
const url = `/api/extensions/ext/skatteverket/authorize${
returnTo ? `?return_to=${encodeURIComponent(returnTo)}` : ''
}`
const w = 600
const h = 750
const left = window.screenX + (window.outerWidth - w) / 2
const top = window.screenY + (window.outerHeight - h) / 2
const popup = window.open(
url,
'skatteverket-oauth',
`width=${w},height=${h},left=${left},top=${top}`,
)
popupRef.current = popup
if (!popup) {
// Popup blocked: fall back to a full-page navigation.
const tab = window.open(url, '_blank')
popupRef.current = tab
if (!tab) {
// Tab blocked: fall back to a full-page navigation.
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
// buttons 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()
fetchStatus()
}
}, 1000)
}
/**
@@ -803,9 +848,9 @@ export function AGIPanel(props: AGIPanelProps) {
{t('connect_description')}
</p>
{!readOnly && (
<Button onClick={handleConnect}>
<Button onClick={handleConnect} disabled={connecting}>
<Link2 className="mr-2 h-4 w-4" />
{t('connect_button')}
{connecting ? t('connect_waiting') : t('connect_button')}
</Button>
)}
</CardContent>
@@ -851,7 +896,7 @@ export function AGIPanel(props: AGIPanelProps) {
<button
type="button"
onClick={handleDisconnect}
disabled={actionLoading === 'disconnect'}
disabled={actionLoading === 'disconnect' || connecting}
className="inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5 text-[11px] font-normal text-muted-foreground transition-colors hover:border-destructive/50 hover:text-destructive disabled:cursor-not-allowed disabled:opacity-50"
title={t('disconnect_title')}
>
@@ -911,9 +956,9 @@ export function AGIPanel(props: AGIPanelProps) {
<p className="mt-1 text-xs text-muted-foreground">
{t('expired_banner_description')}
</p>
<Button size="sm" variant="outline" className="mt-2" onClick={handleConnect}>
<Button size="sm" variant="outline" className="mt-2" onClick={handleConnect} disabled={connecting}>
<Link2 className="mr-1.5 h-3.5 w-3.5" />
{t('reconnect_button')}
{connecting ? t('connect_waiting') : t('reconnect_button')}
</Button>
</div>
)}
@@ -1076,9 +1121,9 @@ export function AGIPanel(props: AGIPanelProps) {
{error}
{sessionExpired && !readOnly && (
<div className="mt-2">
<Button size="sm" variant="outline" onClick={handleConnect}>
<Button size="sm" variant="outline" onClick={handleConnect} disabled={connecting}>
<Link2 className="mr-1.5 h-3.5 w-3.5" />
{t('reconnect_button')}
{connecting ? t('connect_waiting') : t('reconnect_button')}
</Button>
</div>
)}
@@ -45,9 +45,31 @@ function SkatteverketPersonalConnectionCard() {
const [status, setStatus] = useState<Status | null>(null)
const [loading, setLoading] = useState(true)
const [disconnecting, setDisconnecting] = useState(false)
// Handle of the OAuth popup opened by startConnect: used to verify the
// sender identity of incoming postMessages.
// 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> = {
@@ -58,8 +80,12 @@ function SkatteverketPersonalConnectionCard() {
agd: t('scope_agd'),
}
// Only the first load blanks the card 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 () => {
setLoading(true)
if (!hasLoadedRef.current) setLoading(true)
try {
const res = await fetch('/api/extensions/ext/skatteverket/status')
if (res.status === 503) {
@@ -71,6 +97,7 @@ function SkatteverketPersonalConnectionCard() {
} catch {
setStatus({ connected: false })
} finally {
hasLoadedRef.current = true
setLoading(false)
}
}, [])
@@ -79,6 +106,24 @@ function SkatteverketPersonalConnectionCard() {
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.
@@ -90,6 +135,7 @@ function SkatteverketPersonalConnectionCard() {
// 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'),
@@ -99,7 +145,18 @@ function SkatteverketPersonalConnectionCard() {
// 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:
@@ -112,35 +169,46 @@ function SkatteverketPersonalConnectionCard() {
}
window.addEventListener('message', handleMessage)
return () => window.removeEventListener('message', handleMessage)
}, [loadStatus, toast, tOauth])
}, [loadStatus, stopWatchingOauthTab, toast, tOauth])
function startConnect() {
// Open the BankID OAuth flow in a centered popup. The callback page
// 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 w = 600
const h = 750
const left = window.screenX + (window.outerWidth - w) / 2
const top = window.screenY + (window.outerHeight - h) / 2
const popup = window.open(
url,
'skatteverket-oauth',
`width=${w},height=${h},left=${left},top=${top}`,
)
popupRef.current = popup
if (!popup) {
// Popup blocked: fall back to the full-page flow. The callback then
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', {
@@ -206,11 +274,11 @@ function SkatteverketPersonalConnectionCard() {
)}
<Button
onClick={startConnect}
disabled={status?.disabled || !hasSkatteverket}
disabled={status?.disabled || !hasSkatteverket || connecting}
title={!hasSkatteverket ? 'Anslutning till Skatteverket kräver ett abonnemang' : undefined}
>
<ExternalLink className="mr-2 h-4 w-4" />
{t('connect_with_bankid')}
{connecting ? t('connect_waiting') : t('connect_with_bankid')}
</Button>
</CardContent>
</Card>
@@ -245,7 +313,14 @@ function SkatteverketPersonalConnectionCard() {
{status.needsReconsent && (
<div className="flex gap-2 rounded-md border border-border bg-secondary/40 p-3 text-sm text-foreground">
<ShieldAlert className="h-4 w-4 mt-0.5 shrink-0" />
<p>{t('needs_reconsent_message')}</p>
{/* 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. */}
<p>
{status.lastErrorCode === 'MISSING_SCOPE'
? t('missing_scope_message')
: t('needs_reconsent_message')}
</p>
</div>
)}
<dl className="grid grid-cols-1 gap-3 text-sm sm:grid-cols-2">
@@ -306,17 +381,17 @@ function SkatteverketPersonalConnectionCard() {
{(status.expired || status.needsReconsent || !status.canRefresh || !(scopes.includes('skahmst') || scopes.includes('skattekonto')) || !scopes.includes('agd')) && (
<Button
onClick={startConnect}
disabled={status.disabled || !hasSkatteverket}
disabled={status.disabled || !hasSkatteverket || connecting}
title={!hasSkatteverket ? 'Anslutning till Skatteverket kräver ett abonnemang' : undefined}
>
<ExternalLink className="mr-2 h-4 w-4" />
{t('reconnect')}
{connecting ? t('connect_waiting') : t('reconnect')}
</Button>
)}
<Button
variant="outline"
onClick={disconnect}
disabled={disconnecting}
disabled={disconnecting || connecting}
>
<ShieldOff className="mr-2 h-4 w-4" />
{disconnecting ? t('disconnecting') : t('disconnect')}