feat: MCP server, API keys, OAuth, and KPI dashboard (#72)

* fix: prevent Chrome auto-translate from crashing React during onboarding

Chrome auto-translate modifies DOM text nodes when it detects a Swedish
page (lang="sv") in a browser set to English. React does not expect
external DOM mutations and throws, crashing the entire component tree
into global-error.tsx on every step transition.

Add translate="no" and <meta name="google" content="notranslate"> to
suppress browser translation. Also fix timezone-unsafe date parsing in
fiscal period validation (new Date("YYYY-MM-DD") + getDate() returns
local-timezone values, shifting dates by -1 day in Western timezones).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: add notranslate meta tag to global-error.tsx for consistency

Per review feedback — global-error.tsx renders its own <html> document,
so it needs the same <meta name="google" content="notranslate"> tag as
layout.tsx to fully suppress Chrome translation on error pages.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: add MCP server extension with OAuth, API keys, and KPI dashboard

Let users do bookkeeping through Claude Desktop, Claude Code, or any
MCP-compatible client. "Show my uncategorized transactions." "Book that
as office supplies." "Invoice Acme for 15,000 kr."

MCP server (extension):
- 10 tools: transactions, categorization, customers, invoices,
  trial balance, VAT report, KPI report, income statement
- JSON-RPC 2.0 protocol (no SDK dependency, works in serverless)
- Tool annotations, pagination, input validation per MCP best practices
- Same engine as web UI (VAT rules, exchange rates, event emission)

API key infrastructure (core):
- api_keys table with RLS, rate limiting (100 RPM), scopes column
- Atomic rate limit via DB RPC (validate_and_increment_api_key)
- Key management API routes + settings UI panel

OAuth 2.1 for Claude Desktop connectors:
- .well-known/oauth-protected-resource + oauth-authorization-server
- Authorization endpoint with consent page
- Token endpoint with PKCE verification
- Stateless encrypted auth codes (AES-256-GCM, no DB storage)
- Dynamic client registration

KPI dashboard:
- /nyckeltal page with hero cards, operational grid, trend chart
- GET /api/reports/kpi endpoint
- Gross margin, cash position, expense ratio, avg payment days,
  VAT liability, revenue/expense trend

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address OAuth security vulnerabilities from code review

Critical fixes:
- Auth code replay: Track used codes in oauth_used_codes table with
  unique constraint. Codes are single-use per OAuth 2.1 §4.1.2.
- Open redirect: Validate redirect_uri against hardcoded allowlist
  of known Claude callback URLs + localhost for dev.

P1 fixes:
- Move API key creation from /authorize to /token endpoint. Keys are
  only created after PKCE verification, preventing orphaned keys on
  abandoned OAuth flows.
- Add ensureInitialized() to MCP server so event handlers load and
  transaction.categorized events reach extensions.

P2 fixes:
- Remove 'plain' from PKCE methods — only S256 is advertised and
  accepted.
- Fix extension count in sectors test (10 → 11 for mcp-server).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: remove duplicate ensureInitialized() that caused circular import

The extension router (ext/[...path]/route.ts) already calls
ensureInitialized() before dispatching to handlers. The duplicate
call in server.ts created a circular import that Turbopack couldn't
resolve, breaking the Vercel build.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-03-21 12:57:14 +01:00
committed by GitHub
co-authored by Claude Opus 4.6
parent 2b75ef6538
commit 5d66dd6bfc
41 changed files with 6742 additions and 4 deletions
+2
View File
@@ -24,6 +24,7 @@ import {
Building2,
FileInput,
Wallet,
TrendingUp,
} from 'lucide-react'
import { resolveIcon } from '@/lib/extensions/icon-resolver'
import type { EntityType } from '@/types'
@@ -54,6 +55,7 @@ interface NavItem {
// All nav items for sidebar and mobile drawer
const navItems: NavItem[] = [
{ href: '/', label: 'Översikt', icon: LayoutDashboard, group: 'main' },
{ href: '/nyckeltal', label: 'Nyckeltal', icon: TrendingUp, group: 'main' },
{ href: '/deadlines', label: 'Deadlines', icon: Calendar, group: 'main' },
{ href: '/invoices', label: 'Fakturor', icon: Receipt, group: 'finans' },
{ href: '/customers', label: 'Kunder', icon: Users, group: 'finans' },
+69
View File
@@ -0,0 +1,69 @@
'use client'
import { Card, CardContent } from '@/components/ui/card'
import { formatCurrency } from '@/lib/utils'
import type { KPIReport } from '@/types'
interface KPIHeroCardsProps {
report: KPIReport
}
export function KPIHeroCards({ report }: KPIHeroCardsProps) {
return (
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
{/* Gross margin */}
<Card>
<CardContent className="p-5">
<p className="text-xs text-muted-foreground mb-1">Bruttomarginal</p>
<p className="font-display text-xl tabular-nums tracking-tight">
{report.grossMargin !== null ? `${report.grossMargin}%` : '—'}
</p>
<p className="text-xs text-muted-foreground mt-1">av intäkter</p>
</CardContent>
</Card>
{/* Net result */}
<Card>
<CardContent className="p-5">
<p className="text-xs text-muted-foreground mb-1">Resultat</p>
<p className={`font-display text-xl tabular-nums tracking-tight ${
report.netResult >= 0 ? 'text-[hsl(var(--chart-1))]' : 'text-[hsl(var(--chart-2))]'
}`}>
{formatCurrency(report.netResult)}
</p>
<p className="text-xs text-muted-foreground mt-1">netto</p>
</CardContent>
</Card>
{/* Cash position */}
<Card>
<CardContent className="p-5">
<p className="text-xs text-muted-foreground mb-1">Kassa</p>
<p className={`font-display text-xl tabular-nums tracking-tight ${
report.cashPosition > 0 ? 'text-[hsl(var(--chart-1))]' : 'text-[hsl(var(--chart-2))]'
}`}>
{formatCurrency(report.cashPosition)}
</p>
<p className="text-xs text-muted-foreground mt-1">likvida medel</p>
</CardContent>
</Card>
{/* Outstanding receivables */}
<Card>
<CardContent className="p-5">
<p className="text-xs text-muted-foreground mb-1">Kundfordringar</p>
<p className="font-display text-xl tabular-nums tracking-tight">
{formatCurrency(report.outstandingReceivables)}
</p>
{report.overdueReceivables > 0 ? (
<p className="text-xs text-[hsl(var(--chart-2))] mt-1">
varav förfallet: {formatCurrency(report.overdueReceivables)}
</p>
) : (
<p className="text-xs text-muted-foreground mt-1">utestående</p>
)}
</CardContent>
</Card>
</div>
)
}
+99
View File
@@ -0,0 +1,99 @@
'use client'
import { Card, CardContent } from '@/components/ui/card'
import { TrendingUp, TrendingDown, Info } from 'lucide-react'
import { formatCurrency } from '@/lib/utils'
import type { KPIReport } from '@/types'
interface KPIOperationalGridProps {
report: KPIReport
}
export function KPIOperationalGrid({ report }: KPIOperationalGridProps) {
return (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{/* Revenue growth */}
<Card>
<CardContent className="p-5">
<p className="text-xs text-muted-foreground mb-1">Intäktstillväxt</p>
{!report.periodComplete ? (
<p className="text-sm text-muted-foreground">Välj ett avslutat räkenskapsår</p>
) : report.revenueGrowth !== null ? (
<div className="flex items-center gap-2">
{report.revenueGrowth >= 0 ? (
<TrendingUp className="h-4 w-4 text-[hsl(var(--chart-1))]" />
) : (
<TrendingDown className="h-4 w-4 text-[hsl(var(--chart-2))]" />
)}
<p className={`font-display text-xl tabular-nums tracking-tight ${
report.revenueGrowth >= 0 ? 'text-[hsl(var(--chart-1))]' : 'text-[hsl(var(--chart-2))]'
}`}>
{report.revenueGrowth > 0 ? '+' : ''}{report.revenueGrowth}%
</p>
</div>
) : (
<p className="text-sm text-muted-foreground">Första räkenskapsåret</p>
)}
</CardContent>
</Card>
{/* Expense ratio */}
<Card>
<CardContent className="p-5">
<p className="text-xs text-muted-foreground mb-1">Kostnadsandel</p>
{report.expenseRatio !== null ? (
<>
<p className="font-display text-xl tabular-nums tracking-tight">
{report.expenseRatio}%
</p>
<div className="mt-2 h-1.5 rounded-full bg-muted overflow-hidden">
<div
className="h-full rounded-full bg-[hsl(var(--chart-2))]/60 transition-all"
style={{ width: `${Math.min(report.expenseRatio, 100)}%` }}
/>
</div>
</>
) : (
<p className="text-sm text-muted-foreground">Inga intäkter</p>
)}
</CardContent>
</Card>
{/* Avg payment days */}
<Card>
<CardContent className="p-5">
<div className="flex items-center gap-1.5 mb-1">
<p className="text-xs text-muted-foreground">Snittbetaltid</p>
{report.avgPaymentDays === null && (
<span title="Kräver minst 5 betalda fakturor med betalningsdatum. Sätts via fakturering i gnubok eller bankmatchning.">
<Info className="h-3 w-3 text-muted-foreground/60" />
</span>
)}
</div>
{report.avgPaymentDays !== null ? (
<p className="font-display text-xl tabular-nums tracking-tight">
{report.avgPaymentDays} <span className="text-sm font-normal text-muted-foreground">dagar</span>
</p>
) : (
<p className="text-sm text-muted-foreground">Inte tillräckligt med data</p>
)}
</CardContent>
</Card>
{/* VAT liability */}
<Card>
<CardContent className="p-5">
<p className="text-xs text-muted-foreground mb-1">Momsskuld</p>
<p className={`font-display text-xl tabular-nums tracking-tight ${
report.vatLiability > 0 ? 'text-[hsl(var(--chart-2))]' : 'text-[hsl(var(--chart-1))]'
}`}>
{formatCurrency(Math.abs(report.vatLiability))}
</p>
<p className="text-xs text-muted-foreground mt-1">
{report.vatLiability > 0 ? 'Att betala' : report.vatLiability < 0 ? 'Att återfå' : 'Jämnt'}
</p>
</CardContent>
</Card>
</div>
)
}
+96
View File
@@ -0,0 +1,96 @@
'use client'
import {
Area,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
Legend,
Line,
ComposedChart,
} from 'recharts'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { formatCurrency } from '@/lib/utils'
interface KPITrendChartProps {
months: { label: string; income: number; expenses: number; net: number }[]
}
export function KPITrendChart({ months }: KPITrendChartProps) {
if (months.length === 0) return null
return (
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-base">Intäkter, kostnader & resultat per månad</CardTitle>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={300}>
<ComposedChart
data={months}
margin={{ top: 5, right: 10, left: 10, bottom: 5 }}
>
<CartesianGrid strokeDasharray="3 3" vertical={false} />
<XAxis dataKey="label" tick={{ fontSize: 12 }} />
<YAxis
tickFormatter={(v) =>
new Intl.NumberFormat('sv-SE', { notation: 'compact' }).format(v)
}
tick={{ fontSize: 11 }}
/>
<Tooltip
formatter={(value, name) => [
formatCurrency(Number(value)),
name === 'income'
? 'Intäkter'
: name === 'expenses'
? 'Kostnader'
: 'Resultat',
]}
contentStyle={{
fontSize: '12px',
borderRadius: '8px',
border: '1px solid hsl(var(--border))',
backgroundColor: 'hsl(var(--card))',
}}
/>
<Legend
formatter={(value: string) =>
value === 'income'
? 'Intäkter'
: value === 'expenses'
? 'Kostnader'
: 'Resultat'
}
/>
<Area
type="monotone"
dataKey="income"
fill="hsl(var(--chart-1))"
fillOpacity={0.15}
stroke="hsl(var(--chart-1))"
strokeWidth={1.5}
/>
<Area
type="monotone"
dataKey="expenses"
fill="hsl(var(--chart-2))"
fillOpacity={0.15}
stroke="hsl(var(--chart-2))"
strokeWidth={1.5}
/>
<Line
type="monotone"
dataKey="net"
stroke="hsl(var(--chart-3))"
strokeWidth={2}
dot={false}
/>
</ComposedChart>
</ResponsiveContainer>
</CardContent>
</Card>
)
}
+305
View File
@@ -0,0 +1,305 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { useToast } from '@/components/ui/use-toast'
import { Loader2, Plus, Copy, Check, Trash2, Key } from 'lucide-react'
interface ApiKey {
id: string
key_prefix: string
name: string
scopes: string[] | null
rate_limit_rpm: number
last_used_at: string | null
revoked_at: string | null
created_at: string
}
export function ApiKeysPanel() {
const { toast } = useToast()
const [keys, setKeys] = useState<ApiKey[]>([])
const [isLoading, setIsLoading] = useState(true)
const [isCreating, setIsCreating] = useState(false)
const [showCreateDialog, setShowCreateDialog] = useState(false)
const [showKeyDialog, setShowKeyDialog] = useState(false)
const [newKeyName, setNewKeyName] = useState('')
const [newKeyValue, setNewKeyValue] = useState('')
const [copied, setCopied] = useState(false)
const [revokingId, setRevokingId] = useState<string | null>(null)
const fetchKeys = useCallback(async () => {
try {
const res = await fetch('/api/settings/api-keys')
const json = await res.json()
if (json.data) {
setKeys(json.data.filter((k: ApiKey) => !k.revoked_at))
}
} catch {
toast({ title: 'Fel', description: 'Kunde inte hämta API-nycklar', variant: 'destructive' })
} finally {
setIsLoading(false)
}
}, [toast])
useEffect(() => {
fetchKeys()
}, [fetchKeys])
async function handleCreate() {
setIsCreating(true)
try {
const res = await fetch('/api/settings/api-keys', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: newKeyName || 'MCP-nyckel' }),
})
const json = await res.json()
if (!res.ok) {
toast({ title: 'Fel', description: json.error, variant: 'destructive' })
return
}
setNewKeyValue(json.data.key)
setShowCreateDialog(false)
setShowKeyDialog(true)
setNewKeyName('')
fetchKeys()
} catch {
toast({ title: 'Fel', description: 'Kunde inte skapa nyckel', variant: 'destructive' })
} finally {
setIsCreating(false)
}
}
async function handleRevoke(id: string) {
setRevokingId(id)
try {
await fetch(`/api/settings/api-keys/${id}`, { method: 'DELETE' })
setKeys((prev) => prev.filter((k) => k.id !== id))
toast({ title: 'Nyckel återkallad' })
} catch {
toast({ title: 'Fel', description: 'Kunde inte återkalla nyckel', variant: 'destructive' })
} finally {
setRevokingId(null)
}
}
function handleCopy() {
navigator.clipboard.writeText(newKeyValue)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
}
function formatDate(iso: string | null) {
if (!iso) return '—'
return new Date(iso).toLocaleDateString('sv-SE', {
year: 'numeric',
month: 'short',
day: 'numeric',
})
}
const mcpUrl = typeof window !== 'undefined'
? `${window.location.origin}/api/extensions/ext/mcp-server/mcp`
: '/api/extensions/ext/mcp-server/mcp'
return (
<div className="space-y-6">
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle>API-nycklar</CardTitle>
<CardDescription>
Hantera nycklar för MCP-klienter (Claude, Cursor) och andra integrationer.
</CardDescription>
</div>
<Button
size="sm"
onClick={() => setShowCreateDialog(true)}
disabled={keys.length >= 10}
>
<Plus className="mr-1.5 h-3.5 w-3.5" />
Skapa nyckel
</Button>
</div>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : keys.length === 0 ? (
<div className="flex flex-col items-center justify-center py-8 text-center">
<Key className="h-8 w-8 text-muted-foreground/50 mb-3" />
<p className="text-sm text-muted-foreground">Inga API-nycklar ännu.</p>
<p className="text-xs text-muted-foreground mt-1">
Skapa en nyckel för att koppla din MCP-klient.
</p>
</div>
) : (
<div className="space-y-3">
{keys.map((key) => (
<div
key={key.id}
className="flex items-center justify-between rounded-md border px-4 py-3"
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<p className="text-sm font-medium truncate">{key.name}</p>
</div>
<div className="flex items-center gap-3 mt-1">
<code className="text-xs text-muted-foreground font-mono">
{key.key_prefix}...
</code>
<span className="text-xs text-muted-foreground">
Skapad {formatDate(key.created_at)}
</span>
<span className="text-xs text-muted-foreground">
{key.last_used_at
? `Använd ${formatDate(key.last_used_at)}`
: 'Aldrig använd'}
</span>
</div>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => handleRevoke(key.id)}
disabled={revokingId === key.id}
className="text-destructive hover:text-destructive"
>
{revokingId === key.id ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Trash2 className="h-3.5 w-3.5" />
)}
</Button>
</div>
))}
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base">Anslut MCP-klient</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
<div>
<p className="text-sm font-medium mb-1">Claude Desktop</p>
<p className="text-xs text-muted-foreground mb-2">
Inställningar &rarr; Connectors &rarr; Add custom connector. Klistra in URL:en nedan.
Du loggas in automatiskt via OAuth.
</p>
<pre className="rounded-md bg-muted p-3 text-xs font-mono overflow-x-auto select-all">
{mcpUrl}
</pre>
</div>
<div>
<p className="text-sm font-medium mb-1">Claude Code / Cursor</p>
<p className="text-xs text-muted-foreground mb-2">
Kör i terminalen med en API-nyckel:
</p>
<pre className="rounded-md bg-muted p-4 text-xs font-mono overflow-x-auto">
{`claude mcp add gnubok --transport http \\
--url ${mcpUrl} \\
--header "Authorization: Bearer gnubok_sk_..."`}
</pre>
</div>
</CardContent>
</Card>
{/* Create key dialog */}
<Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle>Skapa API-nyckel</DialogTitle>
<DialogDescription>
Ge nyckeln ett namn så du vet vad den används till.
</DialogDescription>
</DialogHeader>
<div className="space-y-3">
<Label htmlFor="key-name">Namn</Label>
<Input
id="key-name"
placeholder="t.ex. Claude Desktop"
value={newKeyName}
onChange={(e) => setNewKeyName(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleCreate()}
/>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setShowCreateDialog(false)}>
Avbryt
</Button>
<Button onClick={handleCreate} disabled={isCreating}>
{isCreating && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
Skapa
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Show key once dialog */}
<Dialog open={showKeyDialog} onOpenChange={(open) => {
if (!open) {
setNewKeyValue('')
setCopied(false)
}
setShowKeyDialog(open)
}}>
<DialogContent>
<DialogHeader>
<DialogTitle>Din nya API-nyckel</DialogTitle>
<DialogDescription>
Kopiera nyckeln nu. Den visas bara en gång.
</DialogDescription>
</DialogHeader>
<div className="relative">
<code className="block rounded-md bg-muted p-4 pr-12 text-sm font-mono break-all">
{newKeyValue}
</code>
<Button
variant="ghost"
size="sm"
className="absolute right-2 top-2"
onClick={handleCopy}
>
{copied ? (
<Check className="h-4 w-4 text-green-600" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
<DialogFooter>
<Button onClick={() => {
setShowKeyDialog(false)
setNewKeyValue('')
setCopied(false)
}}>
Klar
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}